Implementing the undetected unhooking hooked dlls in c++
Unhooking a hooked DLL in C++ can be a complex and challenging task, especially if the hook has been designed to evade detection by security software. In general, the process involves scanning the process's memory for the hook code, locating the original system function, and then modifying the memory to redirect calls to the original function. Here is an example method for unhooking a DLL that has been hooked using the detours library:
```cpp
#include <Windows.h>
#include <stdio.h>
#include "detours.h"
// Define the function pointer to the original function for later use
typedef void (*PFNORIGINALFUNCTION)(void);
// The address of the original function, which we will locate and call later
PFNORIGINALFUNCTION pfnOriginalFunction = NULL;
// The hook function, which will replace the original function
void HookFunction(void)
{
printf("Hooked function was called.\n");
// Do not call the original function here since we are unhooking it
}
// Unhook the function and restore the original code
BOOL UnhookFunction(PVOID pFunction)
{
LONG status = ERROR_SUCCESS;
printf("Attempting to unhook function at address 0x%p.\n", pFunction);
// Disable global security checks for the process
DetourRestoreAfterWith();
// Remove the hook and retrieve the original function pointer
status = DetourDetach(&(PVOID&)pFunction, HookFunction);
// If successful, restore the original function code
if (status == ERROR_SUCCESS) {
DWORD dwOldProtect = 0;
// Restore the original function code and make it executable
if (VirtualProtect(pFunction, sizeof(PVOID), PAGE_EXECUTE_READWRITE, &dwOldProtect)) {
memcpy(pFunction, &pfnOriginalFunction, sizeof(PVOID));
VirtualProtect(pFunction, sizeof(PVOID), dwOldProtect, &dwOldProtect);
}
}
return (status == ERROR_SUCCESS);
}
int main()
{
// Locate the address of the hooked function and retrieve its original code
HMODULE hModule = LoadLibrary("hooked.dll");
PVOID pHookedFunction = GetProcAddress(hModule, "HookedFunction");
if (pHookedFunction != NULL) {
pfnOriginalFunction = (PFNORIGINALFUNCTION)pHookedFunction;
printf("Original function pointer located at address 0x%p.\n", pfnOriginalFunction);
// Attempt to unhook the function
if (UnhookFunction(pHookedFunction)) {
printf("Function successfully unhooked.\n");
}
else {
printf("Failed to unhook function!\n");
}
}
else {
printf("Failed to locate hooked function!\n");
}
// Close the hooked DLL and exit the application
FreeLibrary(hModule);
return 0;
}
```
This code uses Detours to scan the process's memory for the hook code and remove it. It then locates the original function pointer and restores the original code. Note that this is just an example, and hooking and unhooking code for specific hooks may be different depending on the hooking library and the hook itself. It's important to have a good understanding of the hook in question and the target system to perform effective unhooking.