Skip to content

Instantly share code, notes, and snippets.

@mgeeky
Created October 22, 2024 22:16
Show Gist options
  • Save mgeeky/b797d0a752437ee2f8c1b26cf5d2f4d8 to your computer and use it in GitHub Desktop.
Save mgeeky/b797d0a752437ee2f8c1b26cf5d2f4d8 to your computer and use it in GitHub Desktop.
Rebuilt RtlAddVectoredExceptionHandler so that it doesn't use the ntdll imported function. This way it would be more difficult than just putting a breakpoint on RtlAddVectoredExceptionHandler to log your function. To make it a little better you could inline EncodePointer which would only a few extra lines. Structs might be documented somewhere h…
#include <Windows.h>
#include <winternl.h>
// Types
using LdrProtectMrdata_t = void(__stdcall*)(int);
using LdrProtectMrdataHeap_t = void(__thiscall*)(int);
struct ExceptionRecord_t {
LIST_ENTRY entry;
int* unknown_intptr;
int unknown_int;
void* handler_fn;
};
struct Handler_t {
PSRWLOCK lock;
LIST_ENTRY entry;
};
// Functions
void* NtAllocateHeap(size_t nSize) {
return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nSize);
}
void AddExceptionHandlerRebuilt(void* pVeh) {
Handler_t* LdrpVectorHandlerList = *(Handler_t**)(PatternScan(g_hNtdll, "81 C3 ? ? ? ? 8D 7B 04") + 2);
LdrProtectMrdata_t LdrProtectMrdata = PatternScan<LdrProtectMrdata_t>(g_hNtdll, "8B FF 55 8B EC 51 56 57 BF ? ? ? ? 57");
LdrProtectMrdataHeap_t LdrProtectMrdataHeap = PatternScan<LdrProtectMrdataHeap_t>(g_hNtdll, "8B FF 53 56 57 8B F9 E8 ? ? ? ?");
ExceptionRecord_t* pNewRecord = (ExceptionRecord_t*)NtAllocateHeap(sizeof(ExceptionRecord_t));
pNewRecord->unknown_intptr = (int*)NtAllocateHeap(sizeof(int));
*pNewRecord->unknown_intptr = 1;
pNewRecord->handler_fn = EncodePointer(pVeh);
Handler_t* pHandler = &LdrpVectorHandlerList[0];
LIST_ENTRY* pEntry = &pHandler->entry;
LdrProtectMrdataHeap(0);
LdrProtectMrdata(0);
AcquireSRWLockExclusive(pHandler->lock);
if (pEntry->Flink == pEntry)
_interlockedbittestandset((volatile LONG*)(__readfsdword(0x30) + 0x28), 2);
if (pEntry->Flink->Blink == pEntry) {
pNewRecord->entry.Flink = pEntry->Flink;
pNewRecord->entry.Blink = pEntry;
pEntry->Flink->Blink = &pNewRecord->entry;
pEntry->Flink = &pNewRecord->entry;
}
ReleaseSRWLockExclusive(pHandler->lock);
LdrProtectMrdata(1);
LdrProtectMrdataHeap(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment