GuardRemoved = true;
while (GuardRemoved) {
// Busy-wait until GuardRemoved is set to false
}
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
DWORD WINAPI VEHThread(LPVOID) {
// Set AddressToGuard to the base address of the game plus offset
AddressToGuard = GetModuleBaseAddress() + Offset;
code
if (!SetTestVEH()) {
LogToFile("[x] Failed to set TestVEH");
return 1;
}
while (!ExitQueued) {
if (GuardRemoved) {
DWORD oldProtect;
VirtualProtect((LPVOID)(AddressToGuard), 1, PAGE_EXECUTE_READ | PAGE_GUARD, &oldProtect);
GuardRemoved = false;
}
Sleep(50); // Avoid busy-wait burning CPU
}
RemoveTestVEH();
return 0;
}
// DLL main entry point
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) {
if (dwReason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hInstance);
CreateThread(nullptr, 0, VEHThread, nullptr, 0, nullptr);
}
return TRUE;
}
The provided C++ code defines a Dynamic Link Library (DLL) intended to set up a Vectored Exception Handler (VEH) to monitor and handle guard page violations at a specific memory address within a target process (likely a game, based on the comments). Here's a detailed breakdown of the code, its functionality, potential issues, and suggestions for improvement.
Code Breakdown
Includes and Global Variables
cpp
#include <windows.h>
#include <iostream>
#include <fstream>
#include <shlobj.h>
#include <string>
volatile bool GuardRemoved = false;
static DWORD64 AddressToGuard = NULL;
static HANDLE TestVEHHandle = NULL;
static DWORD TestVEHOldProtect = NULL;
static bool ExitQueued = false; // Change this flag to exit the thread loop
static DWORD64 Offset = 0x1000; // Example Offset, adjust as needed for your target
Headers: Includes necessary Windows and standard C++ headers.
Global Variables:
GuardRemoved: Indicates if the guard has been removed.
AddressToGuard: Memory address to monitor.
TestVEHHandle: Handle to the VEH.
TestVEHOldProtect: Original memory protection at AddressToGuard.
ExitQueued: Flag to signal the thread to exit.
Offset: Offset added to the module’s base address to determine AddressToGuard.
Purpose: Sets up the VEH and applies a guard page to AddressToGuard.
Functionality:
Ensures no existing VEH is set.
Adds the TestVEH as a vectored exception handler.
Changes memory protection at AddressToGuard to include PAGE_GUARD.
VEH Monitoring Thread
cpp
DWORD WINAPI VEHThread(LPVOID) {
// Set AddressToGuard to the base address of the game plus offset
AddressToGuard = GetModuleBaseAddress() + Offset;
if (!SetTestVEH()) {
LogToFile("[x] Failed to set TestVEH");
return 1;
}
while (!ExitQueued) {
if (GuardRemoved) {
DWORD oldProtect;
VirtualProtect((LPVOID)(AddressToGuard), 1, PAGE_EXECUTE_READ | PAGE_GUARD, &oldProtect);
GuardRemoved = false;
}
Sleep(50); // Avoid busy-wait burning CPU
}
RemoveTestVEH();
return 0;
}
Purpose: Runs in a separate thread to monitor guard page violations.
Functionality:
Calculates AddressToGuard based on the module base address and Offset.
Sets up the VEH.
Enters a loop that:
Checks if GuardRemoved is true.
Reapplies the PAGE_GUARD protection to AddressToGuard.
Resets GuardRemoved.
Sleeps to prevent high CPU usage.
Cleans up by removing the VEH when ExitQueued is true.
On process attach, disables thread library calls to optimize performance.
Creates a new thread to run VEHThread.
Functionality Overview
Guard Page Setup: The code sets a guard page at a specified memory address within the target process. A guard page is a memory page that triggers an exception (STATUS_GUARD_PAGE_VIOLATION) when accessed, allowing the program to handle such accesses gracefully.
Exception Handling: When the guard page at AddressToGuard is accessed, the TestVEH handler logs the relative RIP offset and sets a flag (GuardRemoved) indicating that the guard has been triggered.
Monitoring Loop: The separate thread (VEHThread) continuously monitors the GuardRemoved flag. When it's set, the thread reapplies the guard page to monitor further accesses.
Logging: All significant events, such as setting/removing the VEH and handling exceptions, are logged to a log.txt file in the user's Documents folder.
Potential Use Cases
Debugging and Reverse Engineering: Monitoring specific memory accesses can help in understanding how a program operates, especially in security research or reverse engineering scenarios.
Anti-Cheat Mechanisms: In gaming, this technique can be used to detect and prevent unauthorized memory modifications, thereby acting as an anti-cheat measure.
Software Protection: Guard pages can help protect critical sections of code or data from being tampered with.
Potential Issues and Considerations
Busy-Wait Loop in VEH Handler:
cpp
while (GuardRemoved) {
// Busy-wait until GuardRemoved is set to false
}
Issue: This creates a tight loop that can consume 100% CPU while waiting for GuardRemoved to become false. This negates the purpose of the subsequent Sleep(50) in the monitoring thread.
Solution: Replace the busy-wait with a synchronization mechanism like events or mutexes.
Thread Safety:
Issue: The global variables (GuardRemoved, ExitQueued, etc.) are accessed from multiple threads without proper synchronization, which can lead to race conditions.
Solution: Use synchronization primitives such as critical sections, mutexes, or atomic variables to ensure thread safety.
Error Handling:
Issue: The RemoveTestVEH and SetTestVEH functions log errors but do not provide feedback mechanisms for recovery or notification beyond logging.
Solution: Implement proper error handling strategies, such as retry mechanisms or notifying the main thread/application of critical failures.
Hardcoded Offset:
Issue: The Offset is hardcoded (0x1000), which may not correspond to the intended target address in different environments or versions of the target application.
Solution: Make the offset configurable or dynamically determine the target address based on context.
Performance Overhead:
Issue: Using VEH introduces overhead as each exception (in this case, guard page violations) triggers the handler.
Solution: Minimize the number of guard pages and ensure that exceptions are handled efficiently.
Security Implications:
Issue: Manipulating memory protection and handling exceptions at this level can be exploited if not handled securely, potentially leading to vulnerabilities.
Solution: Ensure that the code runs with the least privileges necessary and that all inputs and operations are securely managed.
Suggestions for Improvement
Use Synchronization Mechanisms:
Replace the busy-wait loop with synchronization primitives to efficiently manage the state between threads.
cpp
// Example using an event
HANDLE GuardEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// In TestVEH
GuardRemoved = true;
SetEvent(GuardEvent);
// In VEHThread
WaitForSingleObject(GuardEvent, INFINITE);
// Reapply guard page
GuardRemoved = false;
ResetEvent(GuardEvent);
Thread Safety with Atomic Variables:
Utilize atomic types for flags accessed by multiple threads to prevent race conditions.
Dynamic Address Calculation:
Instead of a hardcoded offset, determine AddressToGuard based on dynamic analysis or configuration.
cpp
// Example: Read offset from a configuration file or inject dynamically
Enhanced Error Handling:
Implement more robust error handling to manage failures gracefully and possibly recover or alert the user.
Optimize Logging:
Use buffering to minimize I/O operations.
Provide options to enable/disable logging or adjust log levels.
Security Best Practices:
Ensure the DLL is loaded securely.
Validate all inputs and handle exceptions gracefully to prevent potential abuse.
Documentation and Configurability:
Document the purpose and usage of each component.
Allow for configuration of key parameters like Offset, log file location, and logging levels.
Example Improvement: Replacing Busy-Wait with Event
Here's how you could modify the code to replace the busy-wait loop with an event-based mechanism:
cpp
#include <windows.h>
#include <iostream>
#include <fstream>
#include <shlobj.h>
#include <string>
#include <atomic>
volatile std::atomic<bool> GuardRemoved(false);
static DWORD64 AddressToGuard = NULL;
static HANDLE TestVEHHandle = NULL;
static DWORD TestVEHOldProtect = NULL;
static std::atomic<bool> ExitQueued(false);
static DWORD64 Offset = 0x1000; // Example Offset, adjust as needed for your target
static HANDLE GuardEvent = NULL;
// ... [Other functions remain the same]
// Modified TestVEH to signal an event instead of busy-waiting
LONG WINAPI TestVEH(EXCEPTION_POINTERS* _ExceptionInfo) {
if (_ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) {
DWORD64 relativeRip = _ExceptionInfo->ContextRecord->Rip - AddressToGuard;
LogToFile("[+] RIP relative offset: " + std::to_string(relativeRip));
GuardRemoved = true;
SetEvent(GuardEvent); // Signal the event
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
DWORD WINAPI VEHThread(LPVOID) {
AddressToGuard = GetModuleBaseAddress() + Offset;
if (!SetTestVEH()) {
LogToFile("[x] Failed to set TestVEH");
return 1;
}
GuardEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!GuardEvent) {
LogToFile("[x] Failed to create event");
RemoveTestVEH();
return 1;
}
while (!ExitQueued) {
if (GuardRemoved) {
WaitForSingleObject(GuardEvent, INFINITE);
DWORD oldProtect;
VirtualProtect((LPVOID)(AddressToGuard), 1, PAGE_EXECUTE_READ | PAGE_GUARD, &oldProtect);
GuardRemoved = false;
ResetEvent(GuardEvent);
}
Sleep(50); // Optional, depending on how WaitForSingleObject is used
}
CloseHandle(GuardEvent);
RemoveTestVEH();
return 0;
}
Conclusion
The provided DLL sets up a VEH to monitor guard page violations at a specific memory address, logging relevant information upon each violation. While the core functionality is correctly implemented, there are areas for improvement, particularly concerning thread safety, synchronization, and performance optimization. Addressing these issues will result in a more robust and efficient implementation suitable for its intended use case.
If you plan to use or distribute this DLL, ensure you have the appropriate permissions and understand the implications of injecting and manipulating memory within target processes, especially in the context of software licensing and anti-cheat mechanisms.
Logging Overhead:
Issue: Frequent logging, especially within exception handlers, can lead to performance degradation and large log files.
Solution: Implement conditional logging or limit the amount of data being logged.