MalDev Study
Advanced Module 9advanced6 code files

Utilizing Hardware Breakpoints For Hooking (1)

In previous modules, hooks were implemented using trampolines by patching the original execution flow with unconditional jump shellcodes. The unconditional jump causes the execu...

Jump to Section (37)

Introduction

In previous modules, hooks were implemented using trampolines by patching the original execution flow with unconditional jump shellcodes. The unconditional jump causes the execution flow to be redirected to a detour function, where it executes alternate code logic instead of the intended code of the original function.

Despite this method's effectiveness and seamless functionality, it can be easily detected by searching for the jmp instruction opcode. Additionally, hooks can be detected by comparing a function's binary representation in memory to that on disk which can expose runtime patches and thus detect any installed trampolines. Using trampolines also requires changing the memory permissions of the hooked function to allow writing the trampoline shellcode, which in itself can be an IoC.

A solution would be to utilize hardware breakpoints alongside a Vectored Exception Handler VEH , which will be the main focus of this module.

Understanding Hardware Breakpoints

To understand hardware breakpoints, one must first understand software breakpoints. When installing a software breakpoint on an address (e.g. when debugging on Visual Studio), an int 3 instruction is injected into that address. This instruction is equivalent to the 0xCC opcode on both 32-bit and 64-bit systems and is often referred to as a software interrupt instruction. This instruction raises a specific type of exception when executed which is handled by a pre-initialized exception handler that will be responsible for handling the triggered exception, and therefore control execution at the target address.

Hardware breakpoints work in the same manner by setting up an exception handler that will handle the exception raised at the target address. The main difference is how this exception is raised. For example, when setting a hardware breakpoint at address X, that address will be saved into one of four debug registers, Dr0, Dr1, Dr2 or Dr3. These registers are used to store memory addresses where hardware breakpoints are set. When one of these registers is populated with an address, an EXCEPTION_SINGLE_STEP exception will be raised whenever execution reaches address X.

EFLAGS Register

As previously explained, four debug registers are used to store the target address Dr0, Dr1, Dr2 or Dr3. In addition to that, hardware breakpoints use the EFLAGS register and the Dr7 debug register.

The EFLAGS register has several flags, but the main focus is the Resume Flag (RF) which is bit 16 of the EFLAGS register. Setting this flag to 1 resumes code execution when execution is paused at a breakpoint. The following image shows the EFLAGS register and the Resume Flag within.

Utilizing Hardware Breakpoints For Hooking (1) figure

Dr7 Register

The Dr7 register, also called the debug control register, enables or disables breakpoints. An image of the Dr7 register is shown below which is taken from Intel's Software Developer’s Manual. The flags of interest for this module will be G0-3 which have been highlighted in the image below.

Utilizing Hardware Breakpoints For Hooking (1) figure

The Global Breakpoint Enable Flags

The G0-3 and L0-3 flags are meant to enable and disable hardware breakpoints. As previously mentioned, this module will exclusively focus on the Global Breakpoint Enable Flags (G0-3) as they provide more control over the state of the breakpoint than the local flags do (L0-3).

As per the image of the Dr7 register, the Global Breakpoint Enable Flags are at the following bit positions:

  • G0 Bit 1
  • G1 Bit 3
  • G2 Bit 5
  • G3 Bit 7

Depending on the breakpoint's position in the Dr0-3 registers, the G0-3 flags will be set to 1 to enable the breakpoint. For example, to enable a hardware breakpoint that's saved in the Dr0 register, the G0 flag should be set to 1. The same concept applies to the other Dr registers where enabling the breakpoint saved in Dr1 is done via the G1 flag, Dr2 is enabled through G2, and Dr3 is enabled through G3.

Disabling a hardware breakpoint follows the same concept as enabling hardware breakpoints with the difference being that the G0-3 flags are set to 0 instead of 1.

Hardware Breakpoints Algorithm

Having acquired knowledge about how hardware breakpoints are set and removed, the second step will be establishing the groundwork for code implementation. Below are several key considerations to be aware of regarding implementing hardware breakpoints.

  • Hardware breakpoints are not global breakpoints among all threads, instead, they only work for the thread that installs them. That is a thread with populated Dr0-3 and Dr7 registers.
  • Since hardware breakpoints must be saved in one of the Dr0-3 registers, each thread can install a maximum of 4 hardware breakpoints at the same time. Installing and uninstalling breakpoints will be done using the GetThreadContext and SetThreadContext WinAPIs. Where the Dr0-3 and Dr7 values of the calling thread can be altered.
  • Critical section objects, although optional, will be utilized to ensure thread safety and synchronization when handling hardware breakpoints. The following WinAPIs functions are the ones used to work with critical object sections:
  • InitializeCriticalSection Initializes a critical section object by populating a CRITICAL_SECTION structure.
  • EnterCriticalSection Enters a critical section, indicating that the calling thread wants to access a shared resource protected by the critical section. LeaveCriticalSection Releases a critical section, indicating that the calling thread has finished accessing the shared resource.
  • DeleteCriticalSection Deletes a critical section object, freeing the associated resources.
  • As mentioned earlier when code execution reaches a hardware breakpoint, an EXCEPTION_SINGLE_STEP exception is raised. This exception will be handled using a Vectored Exception Handler which is set using the following WinAPIs:
  • AddVectoredExceptionHandler Registers a Vectored Exception Handler, allowing the specified exception handler function to be called when an exception occurs in the process.
  • RemoveVectoredExceptionHandler Removes a previously registered Vectored Exception Handler from the process, preventing the associated exception handler function from being called for future exceptions.

How Hardware Breakpoint Hooks Work

If a hardware breakpoint is set at the beginning of a function and that function is called, it will not execute immediately. Instead, an exception will be triggered and intercepted by our handler which then executes the detour function. Therefore, rather than the detour function being directly called when the hardware breakpoint is hit, the handler will be the one calling the detour function by simulating an exception-handling routine, as shown the image below.

Utilizing Hardware Breakpoints For Hooking (1) figure

The detour function takes on the responsibility of resuming execution by setting the Resume Flag (RF) in the EFLAGS register, thereby allowing the original code of the hooked function to be executed.

Hooking Multiple Functions

The VEH function executes detour functions by using their function pointers. As a result, it is necessary to have a function pointer for each detour function with the same data types and parameters. However, accomplishing this requires more complex code and can potentially lead to performance issues. This is because the VEH function needs to execute each detour function based on its predefined function pointer, which is stored somewhere in the implementation.

Therefore, the current module introduces a simple, yet effective solution, which consists of a single universal function pointer that can work with all functions. The detour function in this module will be designed to be flexible and adaptable, allowing it to intercept multiple functions without the need for predetermined function pointers.

Code Implementation

This module will demonstrate the installation of hardware breakpoint hooks on a single thread. The goal is to provide a straightforward implementation for improved understanding and clarity.

Altering The Dr7 Register Value

As mentioned earlier, the Dr7 register will be responsible for enabling the installed hardware breakpoints via the G0 through G3 flags. Therefore the SetDr7Bits function, shown below, will be used to enable or disable an installed breakpoint.

SetDr7Bits takes the following parameters:

  • CurrentDr7Register The current Dr7 register value.
  • StartingBitPosition The starting bit position. In other words, the position at which the bit modification will start.
  • NmbrOfBitsToModify The number of bits in CurrentDr7Register starting from StartingBitPosition position to modify.
  • NewBitValue The new value of the specified bit/s to be set.

SetDr7Bits returns the new value of the Dr7 register after the bit modification.

CPP
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;
}

Initializing The Address of The Breakpoint

To set up a breakpoint, one should initialize one of the Dr0-3 registers with the address of the breakpoint, and populate one of the G0-3 flags accordingly. The DRX enumeration will be used to determine which register or flag position is to be populated.

ASM
typedef enum _DRX{

    Dr0,
    Dr1,
    Dr2,
    Dr3

} DRX, * PDRX;

The next step is to construct two functions, one that installs and enables the breakpoint and the other removes it. These functions are called SetHardwareBreakingPnt and RemoveHardwareBreakingPnt respectively.

Installing The Breakpoint

The SetHardwareBreakingPnt function performs the task of assigning the value of pAddress to one of the local thread's Dr0-3 registers based on the provided Drx parameter. This is accomplished by utilizing the WinAPI functions GetThreadContext and SetThreadContext with the pseudo handle (-2) representing the local thread.

The function SetHardwareBreakingPnt accepts three parameters:

  • PVOID pAddress A pointer where the hardware breakpoint should be set.
  • PVOID fnHookFunc A pointer to the detour function.
  • DRX Drx An enumeration of type DRX, this value determines what register to populate.
CPP
BOOL SetHardwareBreakingPnt(IN PVOID pAddress, IN PVOID fnHookFunc, IN enum DRX Drx) {

    if (!pAddress || !fnHookFunc)
        return FALSE;

    CONTEXT ThreadCtx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

    // Get local thread context
    if (!GetThreadContext((HANDLE)-2, &ThreadCtx))
        return ReportError(TEXT("GetThreadContext"), NULL);

    // Sets the value of the Dr0-3 registers 
    switch (Drx) {
        case Dr0: {
            if (!ThreadCtx.Dr0)
                ThreadCtx.Dr0 = pAddress;
            break;
        }
        case Dr1: {
            if (!ThreadCtx.Dr1)
                ThreadCtx.Dr1 = pAddress;
            break;
        }
        case Dr2: {
            if (!ThreadCtx.Dr2)
                ThreadCtx.Dr2 = pAddress;
            break;
        }
        case Dr3: {
            if (!ThreadCtx.Dr3)
                ThreadCtx.Dr3 = pAddress;
            break;
        }
        default:
            return FALSE;
    }

    // Set the thread context
    if (!SetThreadContext((HANDLE)-2, &ThreadCtx))
        return ReportError(TEXT("SetThreadContext"), NULL);

    return TRUE;
}

Enabling The Breakpoint

Remember, the SetHardwareBreakingPnt function simply installs the hardware breakpoint but does not enable it on the determined register. To do so, the SetDr7Bits will be used.

CPP
// For reference
// SetDr7Bits(unsigned long long CurrentDr7Register, int StartingBitPosition, int NmbrOfBitsToModify, unsigned long long NewBitValue);

ThreadCtx.Dr7 = SetDr7Bits(ThreadCtx.Dr7, (Drx * 2), 1, 1);

The line of code above does the following:

  • If Drx is 0, the starting bit position will be (0 * 2) = 0. Thus, the first bit from the significant bit (bit position 1 G0) of DR7 will be modified (set to 1 . If Drx is 1, the starting bit position will be (1 * 2) = 2. Thus, the third bit from the least significant bit (bit position 3 G1) of DR7 will be modified (set to 1 . If Drx is 2, the starting bit position will be (2 * 2) = 4. Thus, the fifth bit from the least significant bit (bit position 5 G2) of DR7 will be modified (set to 1 . If Drx is 3, the starting bit position will be (3 * 2) = 6. Thus, the seventh bit from the least significant bit (bit position 7 G3) of DR7 will be modified (set to 1 .

Detour Function Pointer

Although the detour function pointer (fnHookFunc) will not be executed here, fnHookFunc must be saved in accordance with the position of the hooked function pointer (pAddress) in the Dr0-3 registers. To handle this, a global array named g_DetourFuncs will be defined. This array can accommodate a maximum of four function pointers, which corresponds to the highest number of hardware breakpoints that can be installed in a thread. These pointers will be retrieved from the VEH at a later stage and executed there.

The SetHardwareBreakingPnt function is now complete, and the following is its complete version

CPP
// Array of detour function pointers
PVOID       g_DetourFuncs[4]= { 0 }; // Maximum 4 hardware breakpoints 
CPP
BOOL SetHardwareBreakingPnt(IN PVOID pAddress, IN PVOID fnHookFunc, IN enum DRX Drx) {

    if (!pAddress || !fnHookFunc)
        return FALSE;

    CONTEXT ThreadCtx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

    // Get local thread context
    if (!GetThreadContext((HANDLE)-2, &ThreadCtx))
        return ReportError(TEXT("GetThreadContext"), NULL);

    // Sets the value of the Dr0-3 registers 
    switch (Drx) {
        case Dr0: {
            if (!ThreadCtx.Dr0)
                ThreadCtx.Dr0 = pAddress;
            break;
        }
        case Dr1: {
            if (!ThreadCtx.Dr1)
                ThreadCtx.Dr1 = pAddress;
            break;
        }
        case Dr2: {
            if (!ThreadCtx.Dr2)
                ThreadCtx.Dr2 = pAddress;
            break;
        }
        case Dr3: {
            if (!ThreadCtx.Dr3)
                ThreadCtx.Dr3 = pAddress;
            break;
        }
        default:
            return FALSE;
    }

    // Saves the address of the detour function at index 'Drx' in 'g_DetourFuncs'
    g_DetourFuncs[Drx] = fnHookFunc;

    // Enable the breakpoint: Populate the G0-3 flags depending on the saved breakpoint position in the Dr0-3 registers
    ThreadCtx.Dr7 = SetDr7Bits(ThreadCtx.Dr7, (Drx * 2), 1, 1);

    // Set the thread context after editing it
    if (!SetThreadContext((HANDLE)-2, &ThreadCtx))
        return ReportError(TEXT("SetThreadContext"), NULL);

    return TRUE;
}

RemoveHardwareBreakingPnt Function

Finally, the RemoveHardwareBreakingPnt function removes the specified breakpoint by eliminating it from the context of the local thread, specifically from the Dr0-3 registers, and disabling its corresponding flag. As done previously when installing the hardware breakpoint, RemoveHardwareBreakingPnt uses the GetThreadContext and the SetThreadContext WinAPIs, in addition to the helper function SetDr7Bits to nullify the target Global Breakpoint Enable Flag.

The RemoveHardwareBreakingPnt requires one parameter which is the Drx enumeration which determines what register to unset.

CPP
BOOL RemoveHardwareBreakingPnt(IN enum DRX Drx) {

    CONTEXT ThreadCtx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

    if (!GetThreadContext((HANDLE)-2, &ThreadCtx))
        return ReportError(TEXT("GetThreadContext"), NULL);

    // Remove the address of the hooked function from the thread context
    switch (Drx) {
        case Dr0: {
            ThreadCtx.Dr0 = 0x00;
            break;
        }
        case Dr1: {
            ThreadCtx.Dr1 = 0x00;
            break;
        }
        case Dr2: {
            ThreadCtx.Dr2 = 0x00;
            break;
        }
        case Dr3: {
            ThreadCtx.Dr3 = 0x00;
            break;
        }
        default:
            return FALSE;
    }

    // Disabling the hardware breakpoint by setting the target G0-3 flag to zero 
    ThreadCtx.Dr7 = SetDr7Bits(ThreadCtx.Dr7, (Drx * 2), 1, 0);

    if (!SetThreadContext((HANDLE)-2, &ThreadCtx))
        return ReportError(TEXT("SetThreadContext"), NULL);

    return TRUE;
}

Setting Up The VEH Function

As previously mentioned, it is necessary to construct a VEH function to handle the EXCEPTION_SINGLE_STEP exception raised and redirect execution to the detour function. Furthermore, to create a universal function that works with all hooked functions, it is possible to define a single function pointer with one parameter of type PCONTEXT. This allows the detour function to retrieve and manipulate the parameters of the hooked function by utilizing thread context registers.

Initializing The Exception Handler

Setting a hardware breakpoint using the SetHardwareBreakingPnt function without an initialized exception handler will cause the program to crash shortly after the execution reaches the breakpoint. This program would crash because an unhandled exception was raised. To solve this problem, one must first set up a VEH, which is registered via the AddVectoredExceptionHandler WinAPI.

If AddVectoredExceptionHandler succeeds, it returns a handle to the exception handler.

CPP
PVOID AddVectoredExceptionHandler(
  ULONG                       First,     // The order in which the handler should be called. Should be set to '1' so that the handler will be the f
irst handler to be called.
  PVECTORED_EXCEPTION_HANDLER Handler        // A pointer to the handler to be called (pointer to the handler function).
);

PVECTORED_EXCEPTION_HANDLER Structure

According to Microsoft's documentation, the Handler parameter is of type PVECTORED_EXCEPTION_HANDLER which defines how the handler function will look like. The handler function is a callback function that will get executed whenever an exception is raised. Where PVECTORED_EXCEPTION_HANDLER is a function pointer that is shown below.

CPP
typedef LONG (NTAPI *PVECTORED_EXCEPTION_HANDLER)(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    );

EXCEPTION_POINTERS Structure

The VEH function will receive a pointer to an EXCEPTION_POINTERS structure. This structure is intended to assist the handler in evaluating the situation and taking appropriate actions to resolve the raised exception, allowing the program's execution to continue. The EXCEPTION_POINTERS structure is defined as the following

CPP
typedef struct _EXCEPTION_POINTERS {
    PEXCEPTION_RECORD ExceptionRecord;
    PCONTEXT ContextRecord;          // The thread context of the thread that raised the exception
} EXCEPTION_POINTERS, *PEXCEPTION_POINTERS;

When the detour function is executed, it must receive the PEXCEPTION_POINTERS->ContextRecord element as an argument.

EXCEPTION_RECORD Structure

The EXCEPTION_RECORD structure located within EXCEPTION_POINTERS contains information about the raised exception. Inside EXCEPTION_RECORD, the only elements of interest are ExceptionCode and ExceptionAddress which contain the exception code raised, and the address of where the exception occurred, respectively.

CPP
typedef struct _EXCEPTION_RECORD {
   DWORD       ExceptionCode;        // Code that identifies the specific type of exception raised.
   DWORD       ExceptionFlags;
   struct      _EXCEPTION_RECORD *ExceptionRecord;
   PVOID       ExceptionAddress; // Address where the exception occurred
   DWORD       NumberParameters;
   ULONG_PTR   ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD;

Handling The Hardware Breakpoint Exception

Upon reaching a hardware breakpoint, the exception code raised is EXCEPTION_SINGLE_STEP, represented as 0x80000004 in hexadecimal. In the VEH function, it is crucial to note that PEXCEPTION_POINTERS->PEXCEPTION_RECORD->ExceptionCode should always be EXCEPTION_SINGLE_STEP. This determination allows us to know whether the exception originated from our installed breakpoints, as opposed to handling other exceptions such as EXCEPTION_DIVIDED_BY_ZERO and EXCEPTION_STACK_OVERFLOW, that can be caused by code bugs in the program.

Furthermore, the PEXCEPTION_POINTERS->PEXCEPTION_RECORD->ExceptionAddress element should always be equal to one of the Dr0-3 debug registers. This is because ExceptionAddress is the address where the exception occurred, and the exception will come from our breakpoint which was previously set to one of the Dr0-3 registers (recall the SetHardwareBreakingPnt function). With all of this in mind, two checks must be done:

1. Ensure that the exception is indeed raised from a breakpoint by checking the exception's code.

2.Ensure that the exception's address is a hardware breakpoint by checking if it's equal to one of the Dr0-3 debug registers.

VectorHandler Function

The VectorHandler function shown below, performs the necessary checks mentioned.

CPP
LONG WINAPI VectorHandler(PEXCEPTION_POINTERS pExceptionInfo) {

    // If the exception is 'EXCEPTION_SINGLE_STEP' then its caused by a breakpoint and we should handle it
    if (pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {

        // Verify if the breakpoint is a hardware breakpoint we installed
        if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr0 ||
            pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr1 ||
            pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr2 ||
            pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr3) {

            /*
                The Hook Implementation
            */

            // Continue the execution - The exception is handled
            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }

    // The exception is not handled:                                             \
    - Not from the hardware breakpoints  !(Dr0-3)                     \
    - The exception code is not 'EXCEPTION_SINGLE_STEP'

    return EXCEPTION_CONTINUE_SEARCH;
}

The Hook Implementation

In order to create an API hooking scenario from the VEH using the populated g_DetourFuncs array, one can cast each pointer within the array to a function pointer definition that only accepts a PCONTEXT parameter. Subsequently, execution can proceed by invoking these function pointers. The challenging aspect lies in retrieving the correct pointer from the array.

Back to the SetHardwareBreakingPnt function, each detour function pointer was saved into the g_DetourFuncs array according to the Drx enumeration parameter. For example, if Drx was Dr1, which is 1, the index of where the detour function pointer will be saved is then 1. The same logic can be used in the VEH, if the detected exception address was equal to that of the Dr1 register, then the correct function pointer to fetch from the g_DetourFuncs array is index 1.

Infinite Loop & Workaround

An important scenario to consider is the hooked function being called from within its detour version. This would result in an infinite loop (recall the API Hooking Detours Library module). This situation arises because the hooked function will invoke its detour version, and the detour function, in turn, calls the original hooked function, resulting in an infinite loop.

To avoid this issue, one can disable the hardware breakpoint before executing the detour function pointer and then re-enable it when the detour function is executed. To do so, RemoveHardwareBreakingPnt and SetHardwareBreakingPnt will be called respectively in the VEH, and the detour function execution will occur in between, as shown in the following updated version of the VectorHandler function.

CPP
LONG WINAPI VectorHandler(PEXCEPTION_POINTERS pExceptionInfo) {

    // If the exception is 'EXCEPTION_SINGLE_STEP'; then its caused by a breakpoint and we should handle it
    if (pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {

        // Verify if the breakpoint is a hardware breakpoint we installed
        if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr0 ||
            pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr1 ||
            pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr2 ||
            pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr3) {

            enum DRX dwDrx = -1;
            // Defining a function pointer that accepts one parameter of type 'PCONTEXT'
            VOID (*fnHookFunc)(PCONTEXT) = NULL;

            // Detect the hw bp register (Dr0-3)
            if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr0)
                dwDrx = Dr0;
            if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr1)
                dwDrx = Dr1;
            if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr2)
                dwDrx = Dr2;
            if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr3)
                dwDrx = Dr3;

            // Disable hw breakpoint to allow execution the hooked function from the detour function 
            RemoveHardwareBreakingPnt(dwDrx);

            // Execute the callback (detour function)
            fnHookFunc = g_DetourFuncs[dwDrx];
            fnHookFunc(pExceptionInfo->ContextRecord);

            // Enable the hw breakpoint again
            SetHardwareBreakingPnt(pExceptionInfo->ExceptionRecord->ExceptionAddress, g_DetourFuncs[dwDrx], dwDrx);

            // Continue the execution - The exception is handled
            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }

    // The exception is not handled:                 \
    - Not from the hardware breakpoints  !(Dr0-3)            \
    - The exception code is not 'EXCEPTION_SINGLE_STEP'

    return EXCEPTION_CONTINUE_SEARCH;
}

Fetching And Modifying The Hooked Function's Parameters

As mentioned earlier, all of the detour functions have the same function declaration, accepting one parameter, PCONTEXT, and are of type VOID. Using the PCONTEXT parameter on 64-bit systems, one can fetch and alter the first four parameters of the hooked function through the Rcx, Rdx, r8, and r9 registers located in the context structure.

If the hooked function requires more than four parameters, the Rsp register can be utilized for altering the stack parameters since all additional parameters are pushed to the stack. Recall the Introduction To MASM Assembly module, where this matter was discussed in more detail. On the other hand, on 32-bit systems, all parameters are pushed on the stack, therefore utilizing the Esp register is enough to fetch all the hooked function's parameters.

Furthermore, modifying these parameters depends upon their type, whether they are register parameters or stack parameters (the first through fourth parameters are register parameters). Once the type of the parameter is determined, one can proceed to modify the parameter's value accordingly, either by editing the registers or stack.

GetFunctionArgument Function

The GetFunctionArgument is used to fetch a hooked function's arguments. The function takes two parameters:

  • pThreadCtx The thread context pointer that's passed to the detour function from our VEH.
  • dwParmIndex The index of the parameter to fetch.

The return value is a pointer to an argument of the hooked function.

CPP
PBYTE GetFunctionArgument(IN PCONTEXT pThreadCtx, IN DWORD dwParmIndex) {

#ifdef _WIN64
    // 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)));
#else
    return *(DWORD_PTR*)(pThreadCtx->Esp + (dwParmIndex * sizeof(PVOID)));
#endif // _WIN64

}

Retrieving the stack parameters requires multiplying dwParmIndex by the size of the PVOID data type. On 64-bit systems, the PVOID data type occupies 8 bytes, while on 32-bit systems, it occupies 4 bytes. This multiplication helps determine the offset of the parameter from the stack pointer register. Subsequently, the calculated offset is added to the Rsp register (in the case of x64 systems) or the Esp register (in the case of x32 systems).

SetFunctionArgument Function

The SetFunctionArgument function is used to set the hooked function's arguments. The function SetFunctionArgument takes the following parameters:

  • pThreadCtx Thread context pointer, that's passed to the detour function from our VEH.
  • uValue The new parameter value to be set.
  • dwParmIndex The index of the parameter to edit.
CPP
VOID SetFunctionArgument(IN PCONTEXT pThreadCtx, IN ULONG_PTR uValue, IN DWORD dwParmIndex) {

#ifdef _WIN64

    // 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;
#else
    *(DWORD_PTR*)(pThreadCtx->Esp + (dwParmIndex * sizeof(PVOID))) = uValue;
#endif // _WIN64

}

Get & Set Macros

The functions GetFunctionArgument and SetFunctionArgument will exclusively be invoked from the detour function. Therefore, in order to simplify the retrieval and modification of the hooked function's parameters, both functions will be accessed via macros that enhance their efficiency and ease of use.

The GetFunctionArgument function will be called through the GETPARM_X macros, where X represents the index of the parameter to fetch. GETPARM_X takes one parameter, CTX, representing a pointer to the thread's context to pass to the GetFunctionArgument function.

CPP
#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))

On the other hand, the function SetFunctionArgument will be called through the macros SETPARM_X, where X represents the index of the parameter to modify. SETPARM_1 takes two parameters, CTX and VALUE, representing a pointer to the thread's context, and the parameter's new value to set, respectively.

CPP
#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))

Critical Sections

As previously mentioned, the use of critical sections is not mandatory but understanding this concept is important. Critical sections serve the purpose of preventing race conditions, which arise when multiple threads or processes simultaneously attempt to access and modify the same shared resource. In this module, the shared resource in question is the global array g_DetourFuncs. Consequently, any function that interacts with g_DetourFuncs should do so through critical sections. The following points explain the usage of the critical section WinAPIs. It has been broken up into points for simplification.

  • The initialization of critical sections requires the usage of the InitializeCriticalSection WinAPI. This function is invoked once to populate the CRITICAL_SECTION structure, which is subsequently utilized by other WinAPIs.
  • The CRITICAL_SECTION structure remains unaltered after initialization and is used in the EnterCriticalSection and LeaveCriticalSection WinAPIs. The purpose of the EnterCriticalSection function is to enter the critical section before accessing the shared resource, namely g_DetourFuncs. Conversely, the LeaveCriticalSection function is used to exit the critical section after accessing the shared resource.
  • Upon completion of using critical sections, a program can delete the initialized object by invoking the DeleteCriticalSection WinAPI.
  • All of the previously mentioned critical section WinAPIs accept a single parameter, PCRITICAL_SECTION, which represents a pointer to the previously initialized CRITICAL_SECTION structure.

In the implementation, g_DetourFuncs was accessed twice, once in SetHardwareBreakingPnt and the other in the VEH function, VectorHandler. Therefore, these will be the only functions that will use the EnterCriticalSection and LeaveCriticalSection WinAPIs.

Initialization And Cleanup

In order to establish the VEH and the critical section object, it is necessary to create a new function that handles the creation and initialization of the required objects. Therefore, the InitializeHardwareBPVariables function, which is shown below, will be used to handle the creation and initialization of the previously mentioned objects.

CPP
PVOID               g_VectorHandler         = NULL;      // VEH exception handle
CRITICAL_SECTION    g_CriticalSection       = { 0 }; // Crtitcal section
PVOID               g_DetourFuncs[4]        = { 0 };     // Array of detour function pointers

BOOL InitializeHardwareBPVariables() {

    RtlSecureZeroMemory(&g_CriticalSection, sizeof(CRITICAL_SECTION));
    RtlSecureZeroMemory(&g_DetourFuncs, sizeof(g_DetourFuncs));

    // If 'g_CriticalSection' is not yet initialized
    if (g_CriticalSection.DebugInfo == NULL) {
        InitializeCriticalSection(&g_CriticalSection);
    }

    // If 'g_VectorHandler' is not yet initialized
    if (!g_VectorHandler) {
        // Add 'VectorHandler' as the VEH function
        if ((g_VectorHandler = AddVectoredExceptionHandler(1, (PVECTORED_EXCEPTION_HANDLER)&VectorHandler)) == NULL) 
            return ReportError(TEXT("AddVectoredExceptionHandler"), NULL);
    }

    return (g_VectorHandler && g_CriticalSection.DebugInfo);
}

On the other hand, it is recommended to have a dedicated function responsible for cleaning up the initialized objects. UnintializeHardwareBPVariables will invoke DeleteCriticalSection to delete the critical section object, and RemoveVectoredExceptionHandler to unregister the VEH. Additionally, the function will call RemoveHardwareBreakingPnt for all possible values of the enum DRX, to delete all installed breakpoints. The UnintializeHardwareBPVariables function is shown below.

CPP
VOID UnintializeHardwareBPVariables() {

    // Remove breakpoints
    for (int i = 0; i < 4; i++)
        RemoveHardwareBreakingPnt(i);
    // If the critical section is initialized, delete it
    if (g_CriticalSection.DebugInfo)
        DeleteCriticalSection(&g_CriticalSection);
    // If VEH is registered, remove it
    if (g_VectorHandler)
        RemoveVectoredExceptionHandler(g_VectorHandler);

    // Cleanup the global variables
    RtlSecureZeroMemory(&g_CriticalSection, sizeof(CRITICAL_SECTION));
    RtlSecureZeroMemory(&g_DetourFuncs, sizeof(g_DetourFuncs));
    g_VectorHandler = NULL;
}

Constructing The Detour Function

As previously stated, a single detour function's definition is designed to handle all hooked functions. This function accepts a single parameter of type PCONTEXT, which is fetched from the EXCEPTION_POINTERS structure within the handler function. For example, the detour function for both CreateFileA and MessageBoxW WinAPIs will have the same definition that's shown below.

CPP
VOID DetourFunctionName(IN PCONTEXT pThreadCtx){
    // Detour function logic
}

The detour functions must also share the same exit routine. The detour function's exit routine must include common logic that can be used with any function. This is discussed in the upcoming sections.

Resuming Execution

After redirecting the execution flow of the hooked function to the VEH function, the detour function is executed, but the original execution path is not resumed. To address this issue, it is necessary to set the "Resume Flag" located at bit 16 in the EFLAGS register. The provided CONTINUE_EXECUTION macro accepts a pointer to the thread context of the detour function and performs a bitwise OR operation on the EFlags element with a value generated by shifting 1 16 bits to the left. This operation effectively sets the "Resume Flag" to 1, allowing the execution to continue.

CPP
#define CONTINUE_EXECUTION(CTX)(CTX->EFlags = CTX->EFlags | (1 << 16))

The CONTINUE_EXECUTION macro must be called within every detour function constructed.

Terminating The Original Function

Once a detour function finishes executing, the program resumes execution at the hooked function. If the hooked function is called from within its detour version, it will be executed twice: once from the detour function and again upon resuming code execution, which is a problem that must be addressed.

To address this issue, one can modify the behavior by setting the Rip register, also known as the "next instruction pointer register" to point to a ret instruction. By doing so, instead of the Rip register pointing back to the hooked function for execution, it will be redirected to a ret instruction that effectively terminates the execution of the hooked function.

The BLOCK_REAL function is used when the hooked function is called from within its detour version. However, it can also be used in situations where the objective of hooking is to effectively terminate the execution of the hooked function, thereby preventing it from being executed. A more detailed explanation of this particular case will be provided in subsequent modules that dive into the topic of Event Tracing for Windows ETW . Utilizing the BLOCK_REAL function will result in the following execution flow:

Utilizing Hardware Breakpoints For Hooking (1) figure

The BLOCK_REAL function, shown below, takes a pointer to the thread context of the detour function and modifies the value of the Rip register (on 64-bit systems) or the Eip register (on 32-bit systems) to point to a ret instruction. The ret instruction is defined as a variable in the .text section of the implementation (recall the Payload Placement - .text Section module).

CPP
#pragma section(".text")
__declspec(allocate(".text")) const unsigned char ucRet[] = { 0xC3 };

// Called in the detour function to block the execution of the original hooked function
VOID BLOCK_REAL(IN PCONTEXT pThreadCtx) {
#ifdef _WIN64
    pThreadCtx->Rip = (ULONG_PTR)&ucRet;
#elif _WIN32
    pThreadCtx->Eip = (DWORD)&ucRet;
#endif // _WIN64
}

Modifying The Return Value

In certain hooking scenarios, there may be a requirement to modify the return value of the hooked function to a value different from its original value. This situation may occur when, for instance, hooking a memory scanning API and wanting to force its output to indicate a failure in detecting malicious code. This can be achieved by altering the value of the Rax register (on 64-bit systems) or the Eax register (on 32-bit systems).

Recall from the Introduction To MASM Assembly module, a function's return value is saved in the Rax or Eax register. Therefore, upon editing these registers, one can alter the return value of the hooked API. The RETURN_VALUE macro implements the same approach described.

RETURN_VALUE takes two parameters, CTX and VALUE, representing a pointer to the thread's context, and the new return value to set, respectively.

CPP
#ifdef _WIN64
#define RETURN_VALUE(CTX, VALUE)((ULONG_PTR)CTX->Rax = (ULONG_PTR)VALUE)
#elif _WIN32
#define RETURN_VALUE(CTX, VALUE)((ULONG_PTR)CTX->Eax = (ULONG_PTR)VALUE)
#endif // _WIN64

Hooking Example (1)

Now that the hardware breakpoint implementation is finalized, let's consider an example of hooking the MessageBoxA WinAPI. In this case, the detour function of MessageBox will solely modify its original parameters utilizing the SETPARM_X macros. The MessageBoxADetour function below is MessageBox's detour function.

CPP
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));

    SETPARM_2(pThreadCtx, "This Is The Hook");
    SETPARM_3(pThreadCtx, "MessageBoxADetour");
    SETPARM_4(pThreadCtx, (MB_OK | MB_ICONEXCLAMATION));

    CONTINUE_EXECUTION(pThreadCtx);
}

After modifying the hooked function's parameters in the MessageBoxADetour function, the CONTINUE_EXECUTION macro is called to proceed with the execution past the breakpoint. Hooking the MessageBox WinAPI is done via the following main function.

CPP
int main() {

    // Initialize 
    if (!InitializeHardwareBPVariables())
        return -1;

    // [ NOT HOOKED ]
    MessageBoxA(NULL, "This Is A Normal MsgBoxA Call (0)", "Normal", MB_OK);

    printf("[i] Installing Hooks ... ");
    // Hook 'MessageBoxA' to call 'MessageBoxADetour' instead - using the Dr0 register
    if (!SetHardwareBreakingPnt(MessageBoxA, MessageBoxADetour, Dr0))
        return -1;
    printf("[+] DONE \n");

    // [ HOOKED ]
    MessageBoxA(NULL, "This Wont Execute", "Will it ?", MB_OK);

    // Unhooking the installed hook on 'Dr0'
    printf("[i] Uninstalling Hooks ... ");
    if (!RemoveHardwareBreakingPnt(Dr0)) 
        return -1;
    printf("[+] DONE \n");

    // [ NOT HOOKED ]
    MessageBoxA(NULL, "This Is A Normal MsgBoxA Call (1)", "Normal", MB_OK);

    // Clean up
    UnintializeHardwareBPVariables();
    printf("[#] Press <Enter> To Quit ... ");
    getchar();
    return 0;
}

Executing this example program will result in the following output:

1.The first MessageBoxA call, before installing the hook.

Utilizing Hardware Breakpoints For Hooking (1) figure

2.The second MessageBoxA call, where the MessageBoxADetour function is executed instead.

Utilizing Hardware Breakpoints For Hooking (1) figure

3.The third MessageBoxA call, after removing the hook.

Utilizing Hardware Breakpoints For Hooking (1) figure

Hooking Example (2)

In this example, an attempt will be made to hook two WinAPI functions while utilizing the BLOCK_REAL and RETURN_VALUE functions. The detour function MessageBoxADetour shown below serves as the detour function for MessageBoxA. Unlike the earlier implementation, this function does not modify the original function parameters. Instead, MessageBoxADetour directly invokes the MessageBoxA WinAPI with different parameters. The function also utilizes the RETURN_VALUE macro to return the value obtained from the new MessageBoxA call as the output of the original function. Furthermore, the BLOCK_REAL function is employed to terminate the execution of the original hooked MessageBoxA call, causing it to execute a ret instruction instead.

CPP
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));
CPP
    RETURN_VALUE(pThreadCtx, MessageBoxA(NULL, "This is the hook", "MessageBoxADetour", MB_OK | MB_ICONEXCLAMATION));
    BLOCK_REAL(pThreadCtx);

    CONTINUE_EXECUTION(pThreadCtx);
}

This implementation will hook another function, Sleep, where its detour version, SleepDetour, is shown below. The function simply terminates the execution of the hooked Sleep function. As a result, the Sleep function will appear as if it was never called within the implementation.

CPP
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);
}

The main function is shown below which incorporates both hooks, making use of the previously mentioned detour functions.

CSHARP
int main() {

    // Initialize 
    if (!InitializeHardwareBPVariables())
        return -1;
CPP
    // NOT HOOKED
    MessageBoxA(NULL, "This Is A Normal MsgBoxA Call (0)", "Normal", MB_OK);
POWERSHELL
    printf("[i] Installing Hooks ... ");
    // Hook 'MessageBoxA' to call 'MessageBoxADetour' instead - using the Dr0 register
    if (!SetHardwareBreakingPnt(MessageBoxA, MessageBoxADetour, Dr0))
        return -1;

    // Hook 'Sleep' to call 'SleepDetour' instead - using the Dr1 register
    if (!SetHardwareBreakingPnt(Sleep, SleepDetour, Dr1))
        return -1;
    printf("[+] DONE \n");
CPP
    // HOOKED
    MessageBoxA(NULL, "This Wont Execute", "Will it ?", MB_OK);
    // HOOKED
    Sleep(-1);
CPP
    // Unhooking the installed hook on 'Dr0'
    printf("[i] Uninstalling Hooks ... ");
    if (!RemoveHardwareBreakingPnt(Dr0)) 
        return -1;
    printf("[+] DONE \n");
CPP
    // NOT HOOKED
    MessageBoxA(NULL, "This Is A Normal MsgBoxA Call (1)", "Normal", MB_OK);
    // HOOKED
    Sleep(-1);
CPP
    // Clean up
    UnintializeHardwareBPVariables();
    printf("[#] Press <Enter> To Quit ... ");
    getchar();
    return 0;
}

The above program will result in the following output:

1.The first MessageBoxA call, before installing the hook.

Utilizing Hardware Breakpoints For Hooking (1) figure

2.The second MessageBoxA call, where the MessageBoxADetour function is executed instead.

Utilizing Hardware Breakpoints For Hooking (1) figure

3.The hooked Sleep function, where the infinite sleep call is terminated. In addition to that, the Dr0 register (MessageBoxA) breakpoint is removed.

Utilizing Hardware Breakpoints For Hooking (1) figure

4.Another infinite sleep call while being terminated.

Utilizing Hardware Breakpoints For Hooking (1) figure

Video Demo

Utilizing Hardware Breakpoints For Hooking (1) figure
Diagram

Companion Project & Source Code

6 readable source/config files extracted directly from the archive

Download Module 9 - HardwareBPsHook.zip
10.8 KB
#include <Windows.h>
#include <stdio.h>

#include "HardwareHooking.h"

//---------------------------------------------------------------------------------------------------------------------------------------------------------
// "Ret" Shellcode - Used to terminate original function execution

#pragma section(".text")
__declspec(allocate(".text")) const unsigned char ucRet[] = { 0xC3 };

// Called in the detour function to block the execution of the original hooked function
VOID BLOCK_REAL(IN PCONTEXT pThreadCtx) {
#ifdef _WIN64
	pThreadCtx->Rip = (ULONG_PTR)&ucRet;
#elif _WIN32
	pThreadCtx->Eip = (DWORD)&ucRet;
#endif // _WIN64
}


//-------------------------------------------------------------------------------------------------------------------------------------------------------------
//	Global Variables

PVOID				g_VectorHandler		= NULL;
CRITICAL_SECTION	g_CriticalSection	= { 0 };

// Array of detour function pointers
PVOID				g_DetourFuncs[4]	= { 0 }; // Maximum 4 hardware breakpoints 

//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Privat Function - Used to print error messages

#define ERROR_BUF_SIZE	1024

BOOL ReportError(IN PCWSTR szApiFuncName, IN OPTIONAL ULONGLONG uError) {

	CHAR cBuffer[ERROR_BUF_SIZE];
	if (_snprintf_s(cBuffer, ERROR_BUF_SIZE, _TRUNCATE, "[!] %ws Failed With Error %s\n", szApiFuncName, uError != NULL ? "0x%0.8X" : "%d") == -1)
		printf("[!] _snprintf_s : String Exceed The Buffer Size [ %d ] \n", ERROR_BUF_SIZE);
	else
		printf(cBuffer, uError != NULL ? uError : GetLastError());

	return FALSE;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/*
	Used to modify the Dr7 register's flags
*/
unsigned long long SetDr7Bits(unsigned long long CurrentDr7Register, int StartingBitPosition, int NmbrOfBitsToModify, unsigned long long NewBitValue) {
	unsigned long long mask				= (1UL << NmbrOfBitsToModify) - 1UL;
	unsigned long long NewDr7Register	= (CurrentDr7Register & ~(mask << StartingBitPosition)) | (NewBitValue << StartingBitPosition);

	return NewDr7Register;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/*
	Returns the hooked function's parameters from its thread context; called through the 'GETPARM_X' macro
*/
PBYTE GetFunctionArgument(IN PCONTEXT pThreadCtx, IN DWORD dwParmIndex) {

#ifdef _WIN64

	// 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)));
#else
	return *(DWORD_PTR*)(pThreadCtx->Esp + (dwParmIndex * sizeof(PVOID)));
#endif // _WIN64

}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/*
	Edits the hooked function's parameters and set it to a custom value; called through the 'SETPARM_X' macro
*/

VOID SetFunctionArgument(IN PCONTEXT pThreadCtx, IN ULONG_PTR uValue, IN DWORD dwParmIndex) {

#ifdef _WIN64

	// 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;
#else
	*(DWORD_PTR*)(pThreadCtx->Esp + (dwParmIndex * sizeof(PVOID))) = uValue;
#endif // _WIN64

}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/*
	Used to install a hardware breakpoint on the local thread
		* pAddress			= Hardware breakpoint address (where to install)					 
		* fnHookFunc		= Pointer to the detour function 									 
		* Drx				= Can be Dr0->Dr3
*/

BOOL SetHardwareBreakingPnt(IN PVOID pAddress, IN PVOID fnHookFunc, IN enum DRX Drx) {

	// Check if not initialized
	if (!g_VectorHandler)
		return FALSE;

	if (!pAddress || !fnHookFunc)
		return FALSE;

	CONTEXT ThreadCtx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

	// Get local thread context
	if (!GetThreadContext((HANDLE)-2, &ThreadCtx))
		return ReportError(TEXT("GetThreadContext"), NULL);

	// Sets the value of the Dr0-3 registers 
	switch (Drx) {
	case Dr0: {
		if (!ThreadCtx.Dr0)
			ThreadCtx.Dr0 = pAddress;
		break;
	}
	case Dr1: {
		if (!ThreadCtx.Dr1)
			ThreadCtx.Dr1 = pAddress;
		break;
	}
	case Dr2: {
		if (!ThreadCtx.Dr2)
			ThreadCtx.Dr2 = pAddress;
		break;
	}
	case Dr3: {
		if (!ThreadCtx.Dr3)
			ThreadCtx.Dr3 = pAddress;
		break;
	}
	default:
		return FALSE;
	}

	EnterCriticalSection(&g_CriticalSection);

	// Saves the address of the detour function at index 'Drx' in 'g_DetourFuncs'
	g_DetourFuncs[Drx] = fnHookFunc;

	LeaveCriticalSection(&g_CriticalSection);

	// Enable the breakpoint: Populate the G0-3 flags depending on the saved breakpoint position in the Dr0-3 registers
	ThreadCtx.Dr7 = SetDr7Bits(ThreadCtx.Dr7, (Drx * 2), 1, 1);

	// Set the thread context after editing it
	if (!SetThreadContext((HANDLE)-2, &ThreadCtx))
		return ReportError(TEXT("SetThreadContext"), NULL);

	return TRUE;
}


//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/*
	Remove hook on a specified register														
		* Drx				= Can be Dr0->Dr3
*/
BOOL RemoveHardwareBreakingPnt(IN enum DRX Drx) {

	// Check if not initialized
	if (!g_VectorHandler)
		return FALSE;

	CONTEXT ThreadCtx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

	if (!GetThreadContext((HANDLE)-2, &ThreadCtx))
		return ReportError(TEXT("GetThreadContext"), NULL);


	// Remove the address of the hooked function from the thread context
	switch (Drx) {
		case Dr0: {
			ThreadCtx.Dr0 = 0x00;
			break;
		}
		case Dr1: {
			ThreadCtx.Dr1 = 0x00;
			break;
		}
		case Dr2: {
			ThreadCtx.Dr2 = 0x00;
			break;
		}
		case Dr3: {
			ThreadCtx.Dr3 = 0x00;
			break;
		}
		default:
			return FALSE;
	}

	// Disabling the hardware breakpoint by setting the target G0-3 flag to zero
	ThreadCtx.Dr7 = SetDr7Bits(ThreadCtx.Dr7, (Drx * 2), 1, 0);

	if (!SetThreadContext((HANDLE)-2, &ThreadCtx))
		return ReportError(TEXT("SetThreadContext"), NULL);

	return TRUE;
}


//-------------------------------------------------------------------------------------------------------------------------------------------------------------

LONG WINAPI VectorHandler(PEXCEPTION_POINTERS pExceptionInfo) {

	// If the exception is 'EXCEPTION_SINGLE_STEP', then its caused by a breakpoint and we should handle it
	if (pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {

		// Verfiy if the breakpoint is a hardware breakpoint we installed
		if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr0 ||
			pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr1 ||
			pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr2 ||
			pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr3) {

			enum  DRX		dwDrx								= -1;
			VOID			(*fnHookFunc)(PCONTEXT)				= NULL;

			EnterCriticalSection(&g_CriticalSection);

			// Detect the hw bp register (Dr0-3)
			if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr0)
				dwDrx = Dr0;
			if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr1)
				dwDrx = Dr1;
			if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr2)
				dwDrx = Dr2;
			if (pExceptionInfo->ExceptionRecord->ExceptionAddress == pExceptionInfo->ContextRecord->Dr3)
				dwDrx = Dr3;

			// Disable hw breakpoint to allow executing the hooked function from the detour function 
			RemoveHardwareBreakingPnt(dwDrx);

			// Execute the callback (detour function)
			fnHookFunc = g_DetourFuncs[dwDrx];
			fnHookFunc(pExceptionInfo->ContextRecord);

			// Enable the hw breakpoint again
			SetHardwareBreakingPnt(pExceptionInfo->ExceptionRecord->ExceptionAddress, g_DetourFuncs[dwDrx], dwDrx);

			LeaveCriticalSection(&g_CriticalSection);

			// Continue the execution - The exception is handled
			return EXCEPTION_CONTINUE_EXECUTION;
		}
	}

	// The exception is not handled:							\
	- Not from the hardware breakpoints	!(Dr0-3)			\
	- The exception code is not 'EXCEPTION_SINGLE_STEP'

	return EXCEPTION_CONTINUE_SEARCH;
}


//-------------------------------------------------------------------------------------------------------------------------------------------------------------

BOOL InitializeHardwareBPVariables() {

	RtlSecureZeroMemory(&g_CriticalSection, sizeof(CRITICAL_SECTION));
	RtlSecureZeroMemory(&g_DetourFuncs, sizeof(g_DetourFuncs));

	// If 'g_CriticalSection' is not yet initialized
	if (g_CriticalSection.DebugInfo == NULL) {
		InitializeCriticalSection(&g_CriticalSection);
	}

	// If 'g_VectorHandler' is not yet initialized
	if (!g_VectorHandler) {
		// Add 'VectorHandler' as the VEH handler function
		if ((g_VectorHandler = AddVectoredExceptionHandler(1, (PVECTORED_EXCEPTION_HANDLER)&VectorHandler)) == NULL) 
			return ReportError(TEXT("AddVectoredExceptionHandler"), NULL);
	}

	return (g_VectorHandler && g_CriticalSection.DebugInfo);
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

VOID UnintializeHardwareBPVariables() {

	// Remove breakpoints
	for (int i = 0; i < 4; i++)
		RemoveHardwareBreakingPnt(i);
	// If critical section is initialized, delete it
	if (g_CriticalSection.DebugInfo)
		DeleteCriticalSection(&g_CriticalSection);
	// If VEH handler is registered, remove it
	if (g_VectorHandler)
		RemoveVectoredExceptionHandler(g_VectorHandler);

	// Cleanup the global variables
	RtlSecureZeroMemory(&g_CriticalSection, sizeof(CRITICAL_SECTION));
	RtlSecureZeroMemory(&g_DetourFuncs, sizeof(g_DetourFuncs));
	g_VectorHandler = NULL;
}
Full Archive Manifest (7 files inside .zip)
  • HardwareBPsHook/HardwareBPsHook.sln
  • HardwareBPsHook/HardwareBPsHook/HardwareBPsHook.vcxproj
  • HardwareBPsHook/HardwareBPsHook/HardwareBPsHook.vcxproj.filters
  • HardwareBPsHook/HardwareBPsHook/HardwareBPsHook.vcxproj.user
  • HardwareBPsHook/HardwareBPsHook/HardwareHooking.c
  • HardwareBPsHook/HardwareBPsHook/HardwareHooking.h
  • HardwareBPsHook/HardwareBPsHook/main.c

Search all modules and companion code

No matching modules or source files found for “”.
    Covers all 91 Core + 38 Advanced modules + source archives

    Reader Settings & Progress

    Color Theme

    Reading Font Size

    Study Progress & Cross-Device Backup

    0/129
    Completed
    0
    Bookmarked
    0
    Module Notes

    Progress is saved locally in your browser. Export a JSON backup to move your progress between laptop and phone.