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.

Revisions

  1. @dalkrawr dalkrawr revised this gist Feb 1, 2023. No changes.
  2. @dalkrawr dalkrawr created this gist Feb 1, 2023.
    58 changes: 58 additions & 0 deletions AddVectoredExceptionHandler.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    #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);
    }