cwindowswinapiheap-corruption

How to Intentionally cause Windows Heap Corruption?


I'm trying to test the Windows API HeapSetInformation with the value HeapEnableTerminationOnCorruption by attempting to create an Exception code 0xC0000374 which means STATUS_HEAP_CORRUPTION.

Is there some easy C code to intentionally corrupt the heap? I've tried the following but does not crash or generate any exception?

#include <windows.h>
#include <stdio.h>

int main(void)
{
    BOOL bResult = HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

    HANDLE hHeap = HeapCreate(0, 0, 0);
    LPVOID pBuf = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, 1024);

    memset(pBuf, 0x41, 2048);

    HeapFree(hHeap, 0, pBuf);

    return 0;
}

Edited

Adding the HeapFree() call generated an exception.

Faulting application name: memory-map.exe, version: 0.0.0.0, time stamp: 0x61412573
Faulting module name: ntdll.dll, version: 10.0.19041.1110, time stamp: 0x8a32a22a
Exception code: 0xc0000374
Fault offset: 0x000e6c23
Faulting process id: 0x8218
Faulting application start time: 0x01d7a9ba304122bd
Faulting application path: C:\Users\John\source\repos\memory-map\Release\memory-map.exe
Faulting module path: C:\WINDOWS\SYSTEM32\ntdll.dll
Report Id: 5b61df71-3ee7-4432-b84b-33251814127d
Faulting package full name: 
Faulting package-relative application ID: 

I was hoping memset() would trigger WER and terminate the process at that code point. But, instead it was the HeapFree(). I'm not really sure how HeapSetInformation() works.


Solution

  • Your problem is not how to corrupt the heap. You already know how to do that. Your problem is to get the OS to notice so you can verify that it works.

    To do that, you need to corrupt the heap and call heap functions until it does. Clearly the easiest way is to allocate a buffer, fill it and well past, then free it. If somehow that doesn't work, try again subtracting 32 from the pointer you got from allocating first.