This article describes the implementation of C + + to modify the function code hook packaging method, share for everyone to reference. The implementation methods are as follows:
First, the external interface is as follows:
1. Hook to function when class is initialized
2. Cancellation of hooks:
void Unhook ();
3. Re-linking:
void Rehook ();
The code to hook at initialization time:
Copy Code code as follows:
* (dword*) (m_btnewbytes+1) = (DWORD) Pfnhook;
8-byte code address 0XB8, 0x00, 0x00,0x40,0x00,0xff,0xe0,0x00 as long as the second and third bits of data are changed to the address of the function, the original function will be called to the custom function execution.
Second, the realization method:
. h header documents are as follows:
Copy Code code as follows:
#ifndef _ulhook_h__
#define _ulhook_h__
#include <Windows.h>
#pragma once
Class Culhook
{
Public
Culhook (LPSTR lpszmodname, LPSTR lpszfuncnme, PROC pfnhook);
~culhook (void);
Cancel Hook
void Unhook ();
Re-hook
void Rehook ();
Protected
PROC M_pfnorig;
BYTE M_btnewbytes[8];
BYTE M_btoldbytes[8];
Hmodule M_hmodule;
};
#endif
The. CPP source files are as follows:
Copy Code code as follows:
#include "ULHook.h"
Culhook::culhook (LPSTR lpszmodname, LPSTR lpszfuncnme, PROC Pfnhook)
{
BYTE btnewbytes[] = {0xb8, 0x00, 0x00,0x40,0x00,0xff,0xe0,0x00};
memcpy (M_btnewbytes, btnewbytes, 8);
* (dword*) (m_btnewbytes+1) = (DWORD) Pfnhook;
M_hmodule =:: LoadLibraryA (Lpszmodname);
if (NULL = = M_hmodule)
{
M_pfnorig = NULL;
Return
}
M_pfnorig = (PROC):: GetProcAddress (M_hmodule, Lpszfuncnme);
if (NULL!= m_pfnorig)
{
Memory_basic_information MBI = {0};
DWORD Dwoldprotect;
:: VirtualQuery (M_pfnorig, &mbi, sizeof (MBI));
:: VirtualProtect (M_pfnorig, 8, Page_readwrite, &dwoldprotect);
memcpy (M_btoldbytes, M_pfnorig, 8);
:: WriteProcessMemory (GetCurrentProcess (), (void*) M_pfnorig, M_btnewbytes, 8, NULL);
:: VirtualProtect (M_pfnorig, 8, Dwoldprotect, NULL);
}
}
Culhook::~culhook (void)
{
Unhook ();
if (m_hmodule!=null)
{
:: FreeLibrary (M_hmodule);
}
}
void Culhook::unhook ()
{
if (M_pfnorig!= NULL)
{
Memory_basic_information MBI = {0};
DWORD Dwoldprotect;
:: VirtualQuery (M_pfnorig, &mbi, sizeof (MBI));
:: VirtualProtect (M_pfnorig, 8, Page_readwrite, &dwoldprotect);
:: WriteProcessMemory (GetCurrentProcess (), (void*) M_pfnorig, M_btoldbytes, 8, NULL);
:: VirtualProtect (M_pfnorig, 8, Dwoldprotect, NULL);
}
}
void Culhook::rehook ()
{
if (M_pfnorig!= NULL)
{
Memory_basic_information MBI = {0};
DWORD Dwoldprotect;
:: VirtualQuery (M_pfnorig, &mbi, sizeof (MBI));
:: VirtualProtect (M_pfnorig, 8, Page_readwrite, &dwoldprotect);
:: WriteProcessMemory (GetCurrentProcess (), (void*) M_pfnorig, M_btnewbytes, 8, NULL);
:: VirtualProtect (M_pfnorig, 8, Dwoldprotect, NULL);
}
}
I hope this article will help you with the C + + program design.