Utilizing Hardware Breakpoints For Hooking (2)
In the previous module, the main emphasis was on comprehending the utilization of hardware breakpoints for patchless API hooking. While the initial code presented was functional...
Jump to Section (18)
- Introduction
- Updating The Implementation
- DESCRIPTOR_ENTRY Structure
- Importing Functions
- Installing And Removing Hooks In Different Threads
- SnapshotInsertHardwareBreakpointHookIntoTargetThread Function
- SetHardwareBreakpoint Helper Function
- InstallHardwareBreakingPntHook Function - Installing Hooks
- RemoveHardwareBreakingPntHook Function
- Hooking Newly Spawned Threads
- NtCreateThreadEx Function
- Solution 1 - Hooking NtCreateThreadEx
- Solution 2 - Callback Functions
- NtCreateThreadExDetour Function
- Library Implementation
- Hooking Example (1)
- Hooking Example (2)
- Conclusion
- Companion Source Code
Introduction
In the previous module, the main emphasis was on comprehending the utilization of hardware breakpoints for patchless API hooking. While the initial code presented was functional, it was limited to the main thread's context. The previous implementation would not work correctly if the hooked function was executed from a different thread apart from the main thread.
Additionally, if a function is successfully hooked in the current thread and later executed from a new thread, it would not execute the detour function. This is because hardware breakpoints are installed within the context of a specific thread. Therefore, in the context of a new thread, the hardware breakpoints will not be installed in the Dr0-3 registers, resulting in the failure to raise an exception and thus preventing the invocation of the detour function.
To summarize, the previous implementation lacked two main functionalities:
1. Hooking other existing non-main threads.
2.Hooking functions in newly created threads.
Updating The Implementation
The functionality presented in this module will be developed based on VX API's hooking library. The desired features for implementation are already encompassed within this hooking library. However, its code was further improved to enhance readability and functionality.
The implementation in this module is similar to the one introduced in the previous module. However, the new library employs linked lists instead of arrays to manage the installed hooks for each thread. In this approach, each node in the linked list is distinguished by the thread ID to which it belongs.
DESCRIPTOR_ENTRY Structure
Each node from the linked list is of type DESCRIPTOR_ENTRY but the original definition is updated to the one shown below.
typedef struct DESCRIPTOR_ENTRY {
PUINT_VAR_T Address; // Address of the breakpoint
enum DRX Drx; // The index of the breakpoint in Dr0-3 debug registers
DWORD ThreadId; // The thread id of where the breakpoint is installed
VOID(*CallbackFunction)(PCONTEXT); // The callback function pointer (the detour function)
BOOL Processed; // Used as a flag to show that the node is processed in the VEH function - resolving a bug
struct DESCRIPTOR_ENTRY* Next; // Pointer to the next element in the linked list
struct DESCRIPTOR_ENTRY* Previous; // Pointer to the previous element in the linked list
}DESCRIPTOR_ENTRY, * PDESCRIPTOR_ENTRY;Importing Functions
Some functions from the previous module's implementation will be imported to enhance comprehensibility.
- The
SetDr7Bitsfunction is used to enable or disable the hardware breakpoints installed via theG0throughG3flags in theDr7register.
unsigned long long SetDr7Bits(unsigned long long CurrentDr7Register, int StartingBitPosition, int NmbrOfBitsToModify, unsigned long long NewBitValu
e) {
unsigned long long mask = (1UL << NmbrOfBitsToModify) - 1UL;
unsigned long long NewDr7Register = (CurrentDr7Register & ~(mask << StartingBitPosition)) | (NewBitValue << StartingBitPosition);
return NewDr7Register;
}- The
BLOCK_REALfunction is used to terminate the hooked function's code execution.
#pragma section(".text")
__declspec(allocate(".text")) const unsigned char ucRet[] = { 0xC3 };
VOID BLOCK_REAL(IN PCONTEXT pThreadCtx) {
pThreadCtx->Rip = (ULONG_PTR)&ucRet;
}- The
GetFunctionArgumentandSetFunctionArgumentfunctions are used to fetch and set the hooked function's parameters, respectively.
PBYTE GetFunctionArgument(IN PCONTEXT pThreadCtx, IN DWORD dwParmIndex) {
// the first 4 arguments in x64 are in the "RCX - RDX - R8 - R9" registers
switch (dwParmIndex) {
case 0x01:
return (ULONG_PTR)pThreadCtx->Rcx;
case 0x02:
return (ULONG_PTR)pThreadCtx->Rdx;
case 0x03:
return (ULONG_PTR)pThreadCtx->R8;
case 0x04:
return (ULONG_PTR)pThreadCtx->R9;
default:
break;
}
// else more arguments are pushed to the stack
return *(ULONG_PTR*)(pThreadCtx->Rsp + (dwParmIndex * sizeof(PVOID)));
}
VOID SetFunctionArgument(IN PCONTEXT pThreadCtx, IN ULONG_PTR uValue, IN DWORD dwParmIndex) {
// the first 4 arguments in x64 are in the "RCX - RDX - R8 - R9" registers
switch (dwParmIndex) {
case 0x01:
(ULONG_PTR)pThreadCtx->Rcx = uValue; return;
case 0x02:
(ULONG_PTR)pThreadCtx->Rdx = uValue; return;
case 0x03:
(ULONG_PTR)pThreadCtx->R8 = uValue; return;
case 0x04:
(ULONG_PTR)pThreadCtx->R9 = uValue; return;
default:
break;
}
// else more arguments are pushed to the stack
*(ULONG_PTR*)(pThreadCtx->Rsp + (dwParmIndex * sizeof(PVOID))) = uValue;
}- The
CONTINUE_EXECUTIONmacro is used to resume code execution past the hardware breakpoint. And theRETURN_VALUEmacro is used to modify the return value of the hooked function.
#define CONTINUE_EXECUTION(CTX)(CTX->EFlags = CTX->EFlags | (1 << 16))
#define RETURN_VALUE(CTX, VALUE)((ULONG_PTR)CTX->Rax = (ULONG_PTR)VALUE)Installing And Removing Hooks In Different Threads
Since hardware breakpoints are installed within the context of a specific thread, one way to install a hook in a different thread is through thread enumeration. By enumerating the existing threads and identifying the target thread, the OpenThread, GetThreadContext, and SetThreadContext WinAPIs can be utilized to install the desired hardware breakpoint.
In the VX API hooking library, enumerating the threads is done via snapshot APIs, which can be found in the SnapshotInsertHardwareBreakpointHookIntoTargetThread function. While utilizing snapshot APIs works for this, it is recommended to make modifications to open-source online libraries whenever possible. Therefore, the SnapshotInsertHardwareBreakpointHookIntoTargetThread function will be modified to use the NtQuerySystemInformation syscall for thread enumeration which was shown in the Thread Enumeration NtQuerySystemInformation module.
Moreover, this implementation can be extended to install hooks on all currently running threads simultaneously. This can be achieved by enumerating all the active threads and installing the same hardware breakpoint within the context of each thread. This functionality can be triggered by passing a specific flag as a parameter to the function, which will be shown later on.
SnapshotInsertHardwareBreakpointHookIntoTargetThread Function
The SnapshotInsertHardwareBreakpointHookIntoTargetThread function searches for the target thread's identifier and upon finding it, the function will call a helper function, SetHardwareBreakpoint, which is responsible for installing or removing a hardware breakpoint on the specified address.
AddressA pointer to the target function to hook.DrxAn enumeration of typeDRX. This value determines what register to use to install the hardware breakpoint.bInitializeHWBPInstall or remove a hardware breaking point depending on its value.TRUEto set, andFALSEto remove.ThreadIdThe target TID where the hook should be installed. This parameter can be set to theALL_THREADSflag which installs or removes hardware breakpoints on all the existing threads of the local process.
#define STATUS_SUCCESS 0x00000000
#define STATUS_INFO_LENGTH_MISMATCH 0xC0000004
typedef NTSTATUS(WINAPI* fnNtQuerySystemInformation)(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformat
ionLength, PULONG ReturnLength);BOOL SnapshotInsertHardwareBreakpointHookIntoTargetThread(IN PUINT_VAR_T Address, IN DRX Drx, IN BOOL bInitializeHWBP, IN DWORD ThreadId)
{
fnNtQuerySystemInformation pNtQuerySystemInformation = NULL;
ULONG uReturnLen1 = NULL,
uReturnLen2 = NULL;
PSYSTEM_PROCESS_INFORMATION SystemProcInfo = NULL;
PVOID pValueToFree = NULL;
NTSTATUS STATUS = NULL;
BOOL bFlag = FALSE;
pNtQuerySystemInformation = (fnNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"NTDLL.DLL"), "NtQuerySystemInformation");
if (pNtQuerySystemInformation == NULL)
goto _EndOfFunc;
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, NULL, NULL, &uReturnLen1)) != STATUS_SUCCESS && STATUS != STATUS_INFO_LENGTH_
MISMATCH)
goto _EndOfFunc;
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)HeapAlloc(_GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)uReturnLen1);
if (SystemProcInfo == NULL)
goto _EndOfFunc;
pValueToFree = SystemProcInfo;
if ((STATUS = pNtQuerySystemInformation(SystemProcessInformation, SystemProcInfo, uReturnLen1, &uReturnLen2)) != STATUS_SUCCESS)
goto _EndOfFunc;
while (TRUE) {
// If PID is equal to our's
if (SystemProcInfo->UniqueProcessId == _GetCurrentProcessId()) {
PSYSTEM_THREAD_INFORMATION SystemThreadInfo = (PSYSTEM_THREAD_INFORMATION)SystemProcInfo->Threads;
// Enumerating local threads
for (DWORD i = 0; i < SystemProcInfo->NumberOfThreads; i++) {
// If the 'ThreadId' parameter is equal to the 'ALL_THREADS' flag, call 'SetHardwareBreakpoint' for all threads
if (ThreadId != ALL_THREADS && ThreadId != SystemThreadInfo[i].ClientId.UniqueThread)
continue;
// Install/remove hardware breaking points on thread of 'SystemThreadInfo[i].ClientId.UniqueThread' TID
if (!SetHardwareBreakpoint(SystemThreadInfo[i].ClientId.UniqueThread, Address, Drx, bInitializeHWBP))
goto _EndOfFunc;
}
break;
}
if (!SystemProcInfo->NextEntryOffset)
break;
SystemProcInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)SystemProcInfo + SystemProcInfo->NextEntryOffset);
}
bFlag = TRUE;
_EndOfFunc:
if (pValueToFree)
HeapFree(_GetProcessHeap(), 0, pValueToFree);
return bFlag;
}SetHardwareBreakpoint Helper Function
SetHardwareBreakpoint is shown below, and it takes the following parameters:
ThreadIdThe target TID where the hook should be installed. This parameter can be set to theALL_THREADSflag which installs or removes hardware breakpoints on all the existing threads of the local process.AddressA pointer to the target function to hook.DrxAn enumeration of typeDRX. This value determines what register to use to install the hardware breakpoint.bInitializeHWBPA boolean variable that is used as a flag. If set toTRUE, the function installs a breakpoint, and if set toFALSE, the function removes it.
BOOL SetHardwareBreakpoint(IN DWORD ThreadId, IN PUINT_VAR_T Address, IN DRX Drx, IN BOOL bInitializeHWBP)
{
CONTEXT Context = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
HANDLE hThread = INVALID_HANDLE_VALUE;
BOOL bFlag = FALSE;
// Open handle to the target thread if it is not the current thread
if (ThreadId != _GetCurrentThreadId()){
hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadId);
if (hThread == NULL)
goto EXIT_ROUTINE;
}
else
hThread = ((HANDLE)(LONG_PTR)-2);
// Get local thread context
if (!GetThreadContext(hThread, &Context))
goto EXIT_ROUTINE;
// If install
if (bInitializeHWBP){
// Sets the value of the Dr0-3 registers
(&Context.Dr0)[Drx] = Address;
// Enable the breakpoint: Populate the G0-3 flags depending on the saved breakpoint position in the Dr0-3 registers
Context.Dr7 = SetDr7Bits(Context.Dr7, (Drx * 2), 1, 1);
}
// If remove
else {
// If breakpoint found in the thread context
if ((&Context.Dr0)[Drx] == Address){
// Remove the address of the hooked function from the thread context
(&Context.Dr0)[Drx] = 0ull;
// Disabling the hardware breakpoint by setting the target G0-3 flag to zero
Context.Dr7 = SetDr7Bits(Context.Dr7, (Drx * 2), 1, 0);
}
}
// Set the thread context after editing it
if (!SetThreadContext(hThread, &Context))
goto EXIT_ROUTINE;
bFlag = TRUE;
EXIT_ROUTINE:
if (hThread)
CloseHandle(hThread);
return bFlag;
}InstallHardwareBreakingPntHook Function - Installing Hooks
The SnapshotInsertHardwareBreakpointHookIntoTargetThread and SetHardwareBreakpoint functions were explained to clarify the code, however, the user will not need to directly interact with these functions. Instead, the InstallHardwareBreakingPntHook function is used for installing a hook, which internally calls the SnapshotInsertHardwareBreakpointHookIntoTargetThread function.
InstallHardwareBreakingPntHook takes the required parameters to install the hook and adds them to the global linked list where it will be used later to retrieve the detour function pointer from the VEH function. After that, the SnapshotInsertHardwareBreakpointHookIntoTargetThread function is called to install the hook on the specified TID.
InstallHardwareBreakingPntHook is shown below, and it takes the following parameters:
AddressA pointer to the target function to hook.DrxEnumeration of typeDRX. This value determines what register to use to install the hardware breakpoint.CallbackRoutineA pointer to the detour function.ThreadIdThe target TID where the hook is installed. This can be set to theALL_THREADSflag. When this flag is used, the function will install the same hook into all the currently running threads.
BOOL InstallHardwareBreakingPntHook(IN PUINT_VAR_T Address, IN DRX Drx, IN PVOID CallbackRoutine, IN DWORD ThreadId)
{
DESCRIPTOR_ENTRY* NewEntry = NULL;
NewEntry = (DESCRIPTOR_ENTRY*)HeapAlloc(_GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DESCRIPTOR_ENTRY));
if (NewEntry == NULL)
return FALSE;
EnterCriticalSection(&g_CriticalSection);
NewEntry->Address = Address;
NewEntry->Drx = Drx;
NewEntry->ThreadId = ThreadId;
NewEntry->CallbackFunction = CallbackRoutine;
NewEntry->Next = g_Head;
NewEntry->Previous = NULL;
if (g_Head != NULL)
g_Head->Previous = NewEntry;
g_Head = NewEntry;
LeaveCriticalSection(&g_CriticalSection);
return SnapshotInsertHardwareBreakpointHookIntoTargetThread(Address, Drx, TRUE, ThreadId);
}RemoveHardwareBreakingPntHook Function
Removing the hooks is done by calling the RemoveHardwareBreakingPntHook function. RemoveHardwareBreakingPntHook searches the linked list to find the target address and TID that match and then proceeds to remove the associated nodes.
The RemoveHardwareBreakingPntHook function takes the following parameters:
AddressPointer of the hooked function to unhook.ThreadIdThe target thread's identifier to where the hook is to be removed. This can be set to theALL_THREADSflag. When this flag is used, the function will remove all the hooks on theAddressaddress from all the currently running threads.
BOOL RemoveHardwareBreakingPntHook(IN PUINT_VAR_T Address, IN DWORD ThreadId)
{
DESCRIPTOR_ENTRY* TempObject = NULL;
enum DRX Drx = -1;
BOOL bFlag = FALSE,
Found = FALSE;
EnterCriticalSection(&g_CriticalSection);
TempObject = g_Head;
// Remove 'Address' and 'ThreadId' from the linked list
while (TempObject != NULL)
{
if (TempObject->Address == Address && TempObject->ThreadId == ThreadId)
{
Found = TRUE;
Drx = TempObject->Drx;
if (g_Head == TempObject)
g_Head = TempObject->Next;
if (TempObject->Next != NULL)
TempObject->Next->Previous = TempObject->Previous;
if (TempObject->Previous != NULL)
TempObject->Previous->Next = TempObject->Next;
}
if (TempObject)
TempObject = TempObject->Next;
}
LeaveCriticalSection(&g_CriticalSection);
if (Found)
bFlag = SnapshotInsertHardwareBreakpointHookIntoTargetThread(Address, Drx, FALSE, ThreadId);
return bFlag;
}Hooking Newly Spawned Threads
Even when attempting to hook a function across all currently running threads, the same function will not be hooked if it is called from a newly created thread. This limitation exists because the function was invoked after the InstallHardwareBreakingPntHook function call, meaning that the new thread did not exist during the installation of the target function hook.
However, since threads are typically created using the NtCreateThreadEx syscall, it's possible to hook this function to retrieve the handle of the newly created thread. By suspending the new thread, the hooks can be installed before it executes the target function, ensuring that it does not execute the function prematurely. The suspension of the new thread guarantees that the hooks are properly installed before execution resumes.
NtCreateThreadEx Function
The NtCreateThreadEx syscall is shown below.
NTSTATUS NtCreateThreadEx(
OUT PHANDLE hThread, // Parameter of interest
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
);The parameter of interest is the hThread parameter. By obtaining the value of this parameter, one can proceed to invoke the GetThreadContext and SetThreadContext WinAPIs, which are essential for installing hardware breakpoints at the target function's address. However, it should be noted that the hTread parameter is an OUT parameter, and is not populated unless the syscall is executed successfully. This poses a challenge when hooking NtCreateThreadEx since it does not directly provide the created thread handle.
Solution 1 - Hooking NtCreateThreadEx
To address this issue, a potential solution involves invoking NtCreateThreadEx from within the detour function itself, as demonstrated in the provided NtCreateThreadExHook.cpp example. By blocking the original call with a ret instruction, it becomes possible to gain control over the execution of the new thread and easily retrieve its thread handle.
However, it is important to note that this approach will result in all new threads starting from the detour function within our implementation's .text section, rather than their original spawning locations. As a result, if a thread was originally intended to start within the ntdll.dll address space of the local process, it will instead begin from the detour function. Consequently, while this solution is effective, it does harm the call stack, which can be utilized by security vendors to detect malicious activity, especially when stack-tracing techniques are employed.
Solution 2 - Callback Functions
Another solution involves the use of callback functions. Given that the NtCreateThreadEx function will not execute unless the CONTINUE_EXECUTION macro is called and the detour function is returned, a callback function can be executed to wait for the hThread parameter to be populated while the actual detour function terminates its execution with the CONTINUE_EXECUTION macro. By adopting this approach, the thread start address will remain the same as that of the original function, while simultaneously retrieving the handle of the new thread. The following are the steps in which this solution will be applied:
1. The NtCreateThreadEx syscall will be hooked to execute its detour version, NtCreateThreadExDetour.
2.When NtCreateThreadExDetour is executed, it will perform two steps:
- Add the
THREAD_CREATE_FLAGS_CREATE_SUSPENDEDflag to the created thread'sFlagsparameter, subsequently, creating the thread in a suspended state. Fetch the pointer to thehThreadparameter and pass it to another function that waits for it to be populated. The function waiting forhThreadto be populated should be executed as a callback function. TheCreateTimerQueueTimerWinAPI will be utilized as the callback function.
3. NtCreateThreadExDetour should then call the CONTINUE_EXECUTION macro to force NtCreateThreadEx's execution.
NtCreateThreadExDetour Function
The NtCreateThreadExDetour function is NtCreateThreadEx's detour function which was explained in the previous section.
VOID NtCreateThreadExDetour(PCONTEXT Ctx) {
// 0. Get the pointer to the thread handle
PHANDLE pThread = (PHANDLE)GETPARM_1(Ctx);
// 1. Modify the 'Flags' parameter to create the thread suspended
ULONG uNewFalg = GETPARM_7(Ctx);
uNewFalg = uNewFalg | THREAD_CREATE_FLAGS_CREATE_SUSPENDED;
SETPARM_7(Ctx, uNewFalg);
// 2. Execute the hook as a callback function
HANDLE hTimer = INVALID_HANDLE_VALUE;
CreateTimerQueueTimer(&hTimer, NULL, (WAITORTIMERCALLBACK)TimedHookCallback, pThread, 0, 0, 0);
// 3. Execute the original thread
CONTINUE_EXECUTION(Ctx);
}It is worth noting that when the NtCreateThreadExDetour function is executed, the hThread parameter will not be populated yet. This is because the execution of NtCreateThreadEx is deferred until the NtCreateThreadExDetour function executes the CONTINUE_EXECUTION macro and returns. Additionally, the aforementioned CreateTimerQueueTimer call invokes the TimedHookCallback callback function, which is defined similarly to the WaitOrTimerCallback function. This callback function is utilized for executing callback functions with CreateTimerQueueTimer.
For more information on the parameters of CreateTimerQueueTimer, you can refer to CreateTimerQueueTimer's parameters.
Note that the TimedHookCallback function only copies the first four hooks installed with the ALL_THREADS flag to the newly spawned thread.
VOID CALLBACK TimedHookCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) {
// 4. Wait for NtCreateThreadEx to return a HANDLE
HANDLE hThread = (HANDLE)(*(HANDLE*)lpParameter);
while (!hThread) {
}
EnterCriticalSection(&g_CriticalSection);
// 5. Search for hooks that should be installed on all threads, and copy them to the new thread as well
DESCRIPTOR_ENTRY* TempObject = g_Head;
INT i = 0;
while (TempObject != NULL){
if (TempObject->Address && TempObject->CallbackFunction && TempObject->ThreadId == ALL_THREADS){
// 6. Install the hooks that should be set for all threads
InstallHardwareBreakingPntHook(TempObject->Address, TempObject->Drx, TempObject->CallbackFunction, GetThreadId(hThread));
i++;
}
// Used to get the first four 'ALL_THREADS' hooks
if (i == 4)
break;
TempObject = TempObject->Next;
}
LeaveCriticalSection(&g_CriticalSection);
// 7. Resume thread because it was created suspended
ResumeThread(hThread);
}Library Implementation
The library user is not required to directly interact with the NtCreateThreadExDetour and TimedHookCallback functions. Instead, they can simply call the InstallHooksOnNewThreads function provided below. This function retrieves the address of the NtCreateThreadEx system call and utilizes it to invoke the InstallHardwareBreakingPntHook function. This, in turn, installs the hook responsible for executing the detour function NtCreateThreadExDetour on all currently active threads.
Since the InstallHardwareBreakingPntHook requires a Drx enumeration value, InstallHooksOnNewThreads must also require the same parameter, allowing the library user to decide what debug register will be used to save NtCreateThreadEx's address, and subsequently hook it.
PVOID g_pNtCreateThreadEx = NULL;
BOOL InstallHooksOnNewThreads(IN DRX Drx) {
// Install a hook on NtCreateThreadEx, executing the NtCreateThreadExCallback detour function
g_pNtCreateThreadEx = (PVOID)GetProcAddress(GetModuleHandle(TEXT("NTDLL")), "NtCreateThreadEx");
if (!g_pNtCreateThreadEx)
return FALSE;
return InstallHardwareBreakingPntHook(g_pNtCreateThreadEx, Drx, NtCreateThreadExDetour, ALL_THREADS);
}On the other hand, the RemoveHooksOnNewThreads function will be called to uninstall the NtCreateThreadEx hook. RemoveHooksOnNewThreads calls the RemoveHardwareBreakingPntHook function.
BOOL RemoveHooksOnNewThreads() {
// Remove the NtCreateThreadEx hook from all the threads
return RemoveHardwareBreakingPntHook(g_pNtCreateThreadEx, ALL_THREADS);
}Hooking Example (1)
After covering all the essential information required to utilize the library, the following code demonstrates an example to hook the Sleep and MessageBoxA functions on all currently active threads. The corresponding detour functions, SleepDetour and MessageBoxADetour, are provided below. These detour functions serve as modified versions of the original Sleep and MessageBoxA functions, respectively.
VOID SleepDetour(PCONTEXT pThreadCtx) {
printf("[i] Sleep's Old Parameters: \n");
printf("\t> %d \n", (DWORD)GETPARM_1(pThreadCtx));
BLOCK_REAL(pThreadCtx);
CONTINUE_EXECUTION(pThreadCtx);
}VOID MessageBoxADetour(PCONTEXT pThreadCtx) {
printf("[i] MessageBoxA's Old Parameters: \n");
printf("\t> %s \n", (char*)GETPARM_2(pThreadCtx));
printf("\t> %s \n", (char*)GETPARM_3(pThreadCtx)); RETURN_VALUE(pThreadCtx, MessageBoxA(NULL, "This is the hook", "MessageBoxADetour", MB_OK | MB_ICONEXCLAMATION));
BLOCK_REAL(pThreadCtx);
CONTINUE_EXECUTION(pThreadCtx);
}To test the ALL_THREADS flag, a thread will be executed prior to the InstallHardwareBreakingPntHook function call. This thread will wait before executing the hooked functions to give InstallHardwareBreakingPntHook time to install the hooks to it. The main function is also presented below.
VOID ThreadToExecuteHookedFuncs() {
// Wait so that hooks are installed on this thread before calling the hooked functions
WaitForSingleObject((HANDLE)-2, 1000);
// HOOKED
MessageBoxA(NULL, "This Wont Execute", "Will it?", MB_OK);
// HOOKED
Sleep(-1);
}
int main() {
// Creating the thread before calling 'InstallHardwareBreakingPntHook', so it gets hooked as well
DWORD dwThreadId = 0x00;
CreateThread(NULL, NULL, ThreadToExecuteHookedFuncs, NULL, NULL, &dwThreadId);
printf("[+] Hooked functions will be called from thread of ID : %d \n", dwThreadId);
// Initialize
if (!InitHardwareBreakpointHooking())
return -1;
printf("[i] Installing Hooks On All Threads... ");
// Hook 'MessageBoxA' to call 'MessageBoxADetour' instead - using the Dr0 register
if (!InstallHardwareBreakingPntHook(MessageBoxA, Dr0, MessageBoxADetour, ALL_THREADS))
return -1;
// Hook 'Sleep' to call 'SleepDetour' instead - using the Dr1 register
if (!InstallHardwareBreakingPntHook(Sleep, Dr1, SleepDetour, ALL_THREADS))
return -1;
printf("[+] DONE \n");
printf("[#] Press <Enter> To Cleanup And Exit ... \n");
getchar();
// Clean up
if (!CleapUpHardwareBreakpointHooking())
return -1;
return 0;
}Running this implementation will output the following results:
- Successfully executing the detour function of
MessageBoxA.

- Successfully executing the detour function of
Sleep.

Hooking Example (2)
Another scenario to explore involves hooking the target functions from a newly spawned thread. To conduct this experiment, one can create a thread that invokes the hooked functions after calling the InstallHardwareBreakingPntHook and InstallHooksOnNewThreads functions. The code snippet below demonstrates this scenario, where the Sleep and MessageBoxA functions are still the ones being hooked.
VOID NewlySpawnedThread() {
// HOOKED
MessageBoxA(NULL, "This Wont Execute", "Will it?", MB_OK);
// HOOKED
Sleep(-1);
}int main() {
// Initialize
if (!InitHardwareBreakpointHooking())
return -1;
printf("[i] Installing Hooks ... ");
// Hook 'MessageBoxA' to call 'MessageBoxADetour' instead - using the Dr0 register
if (!InstallHardwareBreakingPntHook(MessageBoxA, Dr0, MessageBoxADetour, ALL_THREADS))
return -1;
// Hook 'Sleep' to call 'SleepDetour' instead - using the Dr1 register
if (!InstallHardwareBreakingPntHook(Sleep, Dr1, SleepDetour, ALL_THREADS))
return -1;
printf("[+] DONE \n"); printf("[i] Installing The Same Hooks On New Threads ... ");
// Install the same 'ALL_THREADS' hooks on new threads created in the future - using the Dr2 register
if (!InstallHooksOnNewThreads(Dr2))
return -1;
printf("[+] DONE \n"); // MessageBoxA & Sleep are called and hooked in a new thread
WaitForSingleObject(CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)NewlySpawnedThread, NULL, NULL, NULL), INFINITE); printf("[#] Press <Enter> To Cleanup And Exit ... \n");
getchar();
// Clean up
if (!CleapUpHardwareBreakpointHooking())
return -1;
return 0;
}Executing the code above will result in the following:
- Successfully executing the detour function of
MessageBoxAof the new thread.

- Successfully executing the detour function of
Sleepof the new thread.

Conclusion
At this point, one should have a solid foundation on the theory of hardware breakpoints along with the ability to integrate them within their custom-built malware. It's highly encouraged to review VX API's hooking library along with the code provided in this module. This will be the code used in any future modules that make use of hardware breakpoints.
Companion Project & Source Code
7 readable source/config files extracted directly from the archive
#include <Windows.h>
#ifndef HARDWARE_BP
#define HARDWARE_BP
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------------
// PRIVATE
typedef uintptr_t PUINT_VAR_T;
typedef struct __HARDWARE_ENGINE_INIT_SETTINGS_GLOBAL {
PVOID HandlerObject;
BOOL IsInit;
}HARDWARE_ENGINE_INIT_SETTINGS_GLOBAL, * PHARDWARE_ENGINE_INIT_SETTINGS_GLOBAL;
typedef enum _DRX
{
Dr0,
Dr1,
Dr2,
Dr3
}DRX, * PDRX;
typedef struct DESCRIPTOR_ENTRY {
PUINT_VAR_T Address; // Address of the breaking point
enum DRX Drx; // The index of the breaking point in Dr0-3 debug registers
DWORD ThreadId; // The thread id of where the breaking point is installed
VOID(*CallbackFunction)(PCONTEXT); // The callback function pointer (the detour function)
BOOL Processed; // Used as a flag to show that the node is processed in the VEH handler function - resolving the bug: https://github.com/vxunderground/VX-API/blob/main/VX-API/ExceptHandlerCallbackRoutine.cpp#L19
struct DESCRIPTOR_ENTRY* Next; // Pointer to the next element in the linked list
struct DESCRIPTOR_ENTRY* Previous; // Pointer to the previous element in the linked list
}DESCRIPTOR_ENTRY, * PDESCRIPTOR_ENTRY;
PBYTE GetFunctionArgument(IN PCONTEXT pThreadCtx, IN DWORD dwParmIndex);
VOID SetFunctionArgument(IN PCONTEXT pThreadCtx, IN ULONG_PTR uValue, IN DWORD dwParmIndex);
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------------
// MACROS TO BE CALLED FROM WITHIN THE DETOUR FUNCTIONS
// Called in the detour functions to continue execution
#define CONTINUE_EXECUTION(CTX)(CTX->EFlags = CTX->EFlags | (1 << 16))
// Called in the detour function to return a value
#define RETURN_VALUE(CTX, VALUE)((ULONG_PTR)CTX->Rax = (ULONG_PTR)VALUE)
// Called in the detour function to block the execution of the original function
VOID BLOCK_REAL(IN PCONTEXT pThreadCtx);
// Get Parameters
#define GETPARM_1(CTX)(GetFunctionArgument(CTX, 0x1))
#define GETPARM_2(CTX)(GetFunctionArgument(CTX, 0x2))
#define GETPARM_3(CTX)(GetFunctionArgument(CTX, 0x3))
#define GETPARM_4(CTX)(GetFunctionArgument(CTX, 0x4))
#define GETPARM_5(CTX)(GetFunctionArgument(CTX, 0x5))
#define GETPARM_6(CTX)(GetFunctionArgument(CTX, 0x6))
#define GETPARM_7(CTX)(GetFunctionArgument(CTX, 0x7))
#define GETPARM_8(CTX)(GetFunctionArgument(CTX, 0x8))
#define GETPARM_9(CTX)(GetFunctionArgument(CTX, 0x9))
#define GETPARM_A(CTX)(GetFunctionArgument(CTX, 0xA))
#define GETPARM_B(CTX)(GetFunctionArgument(CTX, 0xB))
// Set Parameters
#define SETPARM_1(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x1))
#define SETPARM_2(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x2))
#define SETPARM_3(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x3))
#define SETPARM_4(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x4))
#define SETPARM_5(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x5))
#define SETPARM_6(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x6))
#define SETPARM_7(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x7))
#define SETPARM_8(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x8))
#define SETPARM_9(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0x9))
#define SETPARM_A(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0xA))
#define SETPARM_B(CTX, VALUE)(SetFunctionArgument(CTX, VALUE, 0xB))
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------------
// PUBLIC LIBRARY FUNCTIONS
#define ALL_THREADS 0x00
// Initialize hardware breaking point library (populate global variables & set up the veh handler)
BOOL InitHardwareBreakpointHooking();
// Disable all the breaking points set and delete the veh handler
BOOL CleapUpHardwareBreakpointHooking();
// Install hook on a specified address \
* Address = Harware breaking point address (where to install) \
* Drx = Can be Dr0 -> Dr3 \
* CallbackRoutine = Pointer to the detour function \
* ThreadId = Thread identifier to hook | 'ALL_THREADS' to hook all threads
BOOL InstallHardwareBreakingPntHook(IN PUINT_VAR_T Address, IN DRX Drx, IN PVOID CallbackRoutine, IN DWORD ThreadId);
// Remove hook on a specified address \
* Address = Harware breaking point address (where to unhook) \
* ThreadId = Thread identifier to unhook | 'ALL_THREADS' to remove hook from all threads
BOOL RemoveHardwareBreakingPntHook(IN PUINT_VAR_T Address, IN DWORD ThreadId);
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------------
// CREATE HOOKS IN NEW THREADS
// Install hooks on new threads. It only copies 'ALL_THREADS' hooks, it takes the following parameter \
* Drx = Can be Dr0->Dr3 (Used to hook 'NtCreateThreadEx')
BOOL InstallHooksOnNewThreads(IN DRX Drx);
// Remove the 'NtCreateThreadEx' hook, disabling the new threads from being hooked
BOOL RemoveHooksOnNewThreads();
#endif // !HARDWARE_BP
Full Archive Manifest (8 files inside .zip)
- HardwareBPHookingLib/HardwareBPHookingLib.sln
- HardwareBPHookingLib/HardwareBPHookingLib/HardwareBPHookingLib.vcxproj
- HardwareBPHookingLib/HardwareBPHookingLib/HardwareBPHookingLib.vcxproj.filters
- HardwareBPHookingLib/HardwareBPHookingLib/HardwareBPHookingLib.vcxproj.user
- HardwareBPHookingLib/HardwareBPHookingLib/HardwareBreaking.h
- HardwareBPHookingLib/HardwareBPHookingLib/HardwareBreakingLib.c
- HardwareBPHookingLib/HardwareBPHookingLib/Structs.h
- HardwareBPHookingLib/HardwareBPHookingLib/main.c