Certainly! I'll help you modify your C++ code so that it logs address violation information and base addresses to a log file located in the user's Documents folder. Here's a step-by-step guide along with the updated code.
Overview of Changes
-
Logging to File:
- Replace the existing
LOG function, which currently uses printf, with one that writes to a log file.
- Ensure thread-safe access to the log file using a mutex.
-
Determining the Documents Folder Path:
- Utilize the Windows API to retrieve the path to the current user's Documents folder.
-
Initializing the Log File:
- Open the log file at the start of the application and ensure it's properly closed upon exiting.
-
Logging Additional Information:
- Include both the violation information and the base addresses in the log entries.
Below is the updated code with detailed comments explaining each change.
Updated Code
#include <windows.h>
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>
#include <mutex>
#include <iomanip>
#include <fstream> // For file operations
#include <ShlObj.h> // For SHGetKnownFolderPath
#include <combaseapi.h> // For CoTaskMemFree
// ------------------ Configuration and Globals ------------------ //
// Define the base address (`Exe`) and the offset (`Offset`).
// For demonstration purposes, we'll use the address of a dummy variable.
DWORD64 Exe = (DWORD64)&Exe; // Base address (using the address of Exe itself)
DWORD Offset = sizeof(Exe); // Offset (size of Exe)
// Address to guard
DWORD64 AddressToGuard = 0;
// Handle for the Vectored Exception Handler
HANDLE TestVEHHandle = NULL;
// Original memory protection of the guarded address
DWORD TestVEHOldProtect = 0;
// Flag to signal exit
std::atomic<bool> ExitQueued(false);
// Flag to indicate guard removal
volatile bool GuardRemoved = false;
// Mutex for thread-safe logging
std::mutex logMutex;
// Global log file stream
std::ofstream logFile;
// ------------------ Utility Functions ------------------ //
// Initialize the log file in the user's Documents folder
bool InitializeLogFile()
{
HRESULT hr;
PWSTR path = NULL;
// Get the path to the Documents folder
hr = SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &path);
if (FAILED(hr))
{
std::cerr << "[x] Failed to get Documents folder path. Error: " << hr << "\n";
return false;
}
// Convert PWSTR to std::wstring
std::wstring documentsPath(path);
// Free the memory allocated for the path
CoTaskMemFree(path);
// Construct the full path to the log file
std::wstring logFilePath = documentsPath + L"\\AddressViolationsLog.txt";
// Open the log file in append mode
logFile.open(logFilePath, std::ios::out | std::ios::app);
if (!logFile.is_open())
{
std::cerr << "[x] Failed to open log file at " << std::string(logFilePath.begin(), logFilePath.end()) << "\n";
return false;
}
// Optionally, write a header or timestamp
logFile << "----- Address Violations Log Started -----\n";
return true;
}
// Close the log file
void CloseLogFile()
{
if (logFile.is_open())
{
logFile << "----- Address Violations Log Ended -----\n";
logFile.close();
}
}
// Thread-safe logging function that writes to the log file
void LOG(const char* format, ...)
{
std::lock_guard<std::mutex> lock(logMutex);
if (!logFile.is_open())
{
// If log file isn't open, fallback to console
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
return;
}
char buffer[1024];
va_list args;
va_start(args, format);
vsnprintf_s(buffer, sizeof(buffer), _TRUNCATE, format, args);
va_end(args);
// Get the current time for timestamp
SYSTEMTIME st;
GetLocalTime(&st);
char timeBuffer[100];
snprintf(timeBuffer, sizeof(timeBuffer), "[%04d-%02d-%02d %02d:%02d:%02d.%03d] ",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
// Write timestamp and log message to the file
logFile << timeBuffer << buffer;
// Optionally, also print to console
printf("%s%s", timeBuffer, buffer);
}
// Dummy function to simulate adding to an address list
bool AddToAddressList(DWORD64 address)
{
// For demonstration, we'll simply return true
// In a real scenario, you might store the address or perform additional checks
return true;
}
// ------------------ Vectored Exception Handler ------------------ //
LONG WINAPI TestVEH(EXCEPTION_POINTERS* ExceptionInfo)
{
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)
{
// Extract the instruction pointer (RIP) from the context
#ifdef _WIN64
DWORD64 rip = ExceptionInfo->ContextRecord->Rip;
#else
DWORD64 rip = ExceptionInfo->ContextRecord->Eip;
#endif
if (AddToAddressList(rip))
{
LOG("[+] Guard Page Violation detected.\n");
LOG(" RIP: 0x%016llX\n", rip);
LOG(" Base Address: 0x%016llX\n", Exe);
LOG(" Offset: 0x%X\n", Offset);
LOG(" Violated Address: 0x%016llX\n", AddressToGuard);
}
GuardRemoved = true; // Signal that the guard page has been removed
// Pause execution until the guard is re-applied
while (GuardRemoved && !ExitQueued)
{
Sleep(10); // Sleep briefly to prevent tight looping
}
// Continue execution
return EXCEPTION_CONTINUE_EXECUTION;
}
// For other exceptions, continue searching
return EXCEPTION_CONTINUE_SEARCH;
}
// ------------------ VEH Management Functions ------------------ //
// Function to remove the Vectored Exception Handler and restore memory protection
void RemoveTestVEH()
{
if (!TestVEHHandle)
{
LOG("[x] (!TestVEHHandle)\n");
return;
}
// Restore the original memory protection
DWORD buffer;
if (!VirtualProtect((LPVOID)(AddressToGuard), 1, TestVEHOldProtect, &buffer))
{
LOG("[x] Failed to restore memory protection. Error: %lu\n", GetLastError());
return;
}
// Remove the VEH handler
if (!RemoveVectoredExceptionHandler(TestVEHHandle))
{
LOG("[x] Failed to remove Vectored Exception Handler. Error: %lu\n", GetLastError());
return;
}
LOG("[+] Vectored Exception Handler removed and memory protection restored.\n");
TestVEHHandle = NULL;
TestVEHOldProtect = 0;
}
// Function to set up the VEH and apply the initial guard page
bool SetTestVEH()
{
if (TestVEHHandle)
{
LOG("[x] VEH already set.\n");
return false;
}
// Add the Vectored Exception Handler
TestVEHHandle = AddVectoredExceptionHandler(1, TestVEH);
if (!TestVEHHandle)
{
LOG("[x] Failed to add Vectored Exception Handler. Error: %lu\n", GetLastError());
return false;
}
// Apply the guard page to the specified address
DWORD oldProtect;
if (!VirtualProtect((LPVOID)(AddressToGuard), 1, PAGE_EXECUTE_READ | PAGE_GUARD, &oldProtect))
{
LOG("[x] Failed to set guard page. Error: %lu\n", GetLastError());
RemoveVectoredExceptionHandler(TestVEHHandle);
TestVEHHandle = NULL;
return false;
}
TestVEHOldProtect = oldProtect;
LOG("[+] Vectored Exception Handler added and guard page set.\n");
LOG(" Guard Page Address: 0x%016llX\n", AddressToGuard);
return true;
}
// ------------------ Monitoring Thread ------------------ //
void VEHThread()
{
// Set the address to guard (base + offset)
AddressToGuard = Exe + Offset;
LOG("[*] VEHThread started.\n");
LOG(" Monitoring Address: 0x%016llX\n", AddressToGuard);
if (!SetTestVEH())
{
LOG("[x] Failed to set up VEH. Exiting VEHThread.\n");
return;
}
while (!ExitQueued)
{
if (GuardRemoved)
{
// Re-apply the guard page
DWORD oldProtect;
if (!VirtualProtect((LPVOID)(AddressToGuard), 1, PAGE_EXECUTE_READ | PAGE_GUARD, &oldProtect))
{
LOG("[x] Failed to re-apply guard page. Error: %lu\n", GetLastError());
// Decide whether to continue or exit
}
else
{
LOG("[+] Guard page re-applied at address: 0x%016llX\n", AddressToGuard);
GuardRemoved = false; // Reset the flag
}
}
Sleep(100); // Sleep to reduce CPU usage
}
RemoveTestVEH();
LOG("[*] VEHThread exiting.\n");
}
// ------------------ Test Function to Trigger Guard Page Violation ------------------ //
// Function to access the guarded address, causing a guard page violation
void AccessGuardedAddress()
{
volatile char* ptr = (volatile char*)AddressToGuard;
for (int i = 0; i < 5; ++i)
{
LOG("[*] Accessing guarded address: 0x%016llX\n", (DWORD64)ptr);
char value = *ptr; // Accessing the address
LOG("[*] Read value: 0x%02X\n", static_cast<unsigned char>(value));
Sleep(500); // Wait before next access
}
}
// ------------------ Main Function ------------------ //
int main()
{
// Initialize the log file
if (!InitializeLogFile())
{
std::cerr << "[x] Unable to initialize log file. Exiting.\n";
return 1;
}
LOG("[*] Application started.\n");
// Start the VEH monitoring thread
std::thread monitorThread(VEHThread);
// Give some time for the VEH to be set up
Sleep(1000);
// Start the test function in the main thread
AccessGuardedAddress();
// Signal the monitoring thread to exit
ExitQueued = true;
// Wait for the monitoring thread to finish
if (monitorThread.joinable())
monitorThread.join();
LOG("[*] Application exiting.\n");
// Close the log file
CloseLogFile();
return 0;
}
Detailed Explanation of Changes
-
Include Necessary Headers:
- Added
<fstream> for file operations.
- Added
<ShlObj.h> and <combaseapi.h> for retrieving the Documents folder path using SHGetKnownFolderPath.
-
Global Log File Stream:
- Introduced a global
std::ofstream logFile to handle log file operations.
-
InitializeLogFile Function:
- Retrieves the path to the current user's Documents folder using
SHGetKnownFolderPath.
- Constructs the full path to the log file (
AddressViolationsLog.txt) within the Documents folder.
- Opens the log file in append mode to preserve previous logs.
- Writes a header to indicate the start of logging.
-
CloseLogFile Function:
- Ensures that a footer is written to the log file upon application exit.
- Closes the log file stream properly.
-
Modified LOG Function:
- Acquires a lock using
std::lock_guard<std::mutex> to ensure thread-safe access to the log file.
- Checks if the log file is open. If not, falls back to printing to the console using
printf.
- Formats the log message using
vsnprintf_s to handle variadic arguments safely.
- Includes a timestamp for each log entry by fetching the current local time.
- Writes the timestamp and the formatted message to both the log file and the console for immediate feedback.
-
Enhanced Logging in VEH Handler:
- When a guard page violation is detected, logs detailed information including:
- The Instruction Pointer (RIP/EIP) where the violation occurred.
- The base address (
Exe).
- The offset used.
- The specific address that was guarded and violated.
-
Logging Guard Page Setup and Removal:
- Logs when the VEH is set up and which address is being monitored.
- Logs any errors encountered while setting or removing the guard page or VEH.
- Logs when the guard page is re-applied after a violation.
-
Application Start and Exit Logs:
Compilation Notes
Final Remarks
With these changes, your application will now log all guard page violations along with relevant address information to a file named AddressViolationsLog.txt located in the user's Documents folder. Additionally, it will still print log messages to the console for real-time monitoring. This setup ensures that all critical information is persistently stored for later analysis.
Feel free to further customize the logging format or add additional information as needed for your specific use case.