C++实现修改函数代码HOOK的封装方法

时间:2021-12-31 21:57:35

一、对外的接口如下:

1. 类初始化时对函数HOOK
2. 取消挂钩:
void UnHook();
3. 重新挂钩:
void ReHook();

在初始化时HOOK的代码:

复制代码 代码如下: *(DWORD*)(m_btNewBytes+1) = (DWORD)pfnHook;

8个字节的代码地址 0xB8, 0x00, 0x00,0x40,0x00,0xFF,0xE0,0x00  只要把第二位和第三位的数据改成函数的地址,调用原先的函数时就会调到自定义的函数执行.

二、实现方法:

.h头文件如下:

复制代码 代码如下: #ifndef  _ULHOOK_H__ 
#define _ULHOOK_H__ 
 
#include <Windows.h> 
#pragma once 
class CULHook 

public: 
    CULHook(LPSTR lpszModName, LPSTR lpszFuncNme, PROC pfnHook); 
    ~CULHook(void); 
 
    //取消挂钩 
    void UnHook(); 
    //重新挂钩 
    void ReHook(); 
protected: 
    PROC m_pfnOrig; 
    BYTE m_btNewBytes[8]; 
    BYTE m_btOldBytes[8]; 
    HMODULE m_hModule; 
}; 
 
#endif

.cpp源文件如下:

复制代码 代码如下: #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); 
    } 
}