Windows下的函数hook技术[6]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

// The common epilog part that can be shared between the stdcall and
// cdecl hook functions.
#define EPILOG_COMMON()                                                \
    {                                                                  \
        __asm MOV   ESI , [dwESI]       /* Restore ESI.              */\
        __asm ADD   ESP , __LOCAL_SIZE  /* Take away local var space */\
        __asm MOV   ESP, EBP            /* Restore standard frame.   */\
        __asm POP   EBP                                                \
    }


#define COPY_CODE_LENGTH 5

BYTE g_abOriCode[COPY_CODE_LENGTH];
BYTE g_abJmpCode[COPY_CODE_LENGTH];
PROC g_oriTextout;

BOOL g_blHooked = FALSE;

LRESULT WINAPI InstallTextoutHook()
{
 if (g_blHooked)
  return TRUE;

 //Get TextOutA's address.
 HMODULE hGdi32 = ::LoadLibrary(_T("Gdi32.dll"));
 g_oriTextout = GetProcAddress(hGdi32, _T("TextOutA"));
 if (NULL == g_oriTextout)
  return FALSE;

 //Get the hook'a address.
 HMODULE hModule = GetModuleHandle(_T("HookDLL.dll"));
 if (NULL == hModule)
  return FALSE;
 DWORD dwHookAddr = NULL;
 __asm
 {
  mov esi, offset HookLabel;
  mov edi, 0x10000000;//0x10000000 is the dll's base address.
  sub esi, edi;
  add esi, hModule;
  mov [dwHookAddr], esi;
 }

 //Get the NOP's address.
 DWORD dwNOPAddr = NULL;
 __asm
 {
  mov esi, offset NOPLabel;
  mov edi, 0x10000000;//0x10000000 is the dll's base address.
  sub esi, edi;
  add esi, hModule;
  mov [dwNOPAddr], esi;
 }

 //Save the first 5 byte of TextOutA to g_abOriCode
 __asm
 {
  mov esi, g_oriTextout;
  lea edi, g_abOriCode;
  cld;
  movsd;
  movsb;
 }

 //Generate the jmp Hook function.
 g_abJmpCode[0] = 0xe9;
 __asm
 {
  mov eax, dwHookAddr;
  mov ebx, g_oriTextout;
  add ebx, 5;
  sub eax, ebx;
  mov dword ptr[g_abJmpCode+1], eax;
 }

 //Write the jump instruction to the textoutA.
 DWORD dwProcessId = GetCurrentProcessId();
 HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS,
                    FALSE, dwProcessId);
 if (NULL == hProcess)
  return FALSE;
 DWORD dwOldFlag;
 VirtualProtectEx(hProcess, g_oriTextout, 5, PAGE_READWRITE, &dwOldFlag);
 WriteProcessMemory(hProcess, g_oriTextout, g_abJmpCode, sizeof(g_abJmpCode), NULL);
 VirtualProtectEx(hProcess, g_oriTextout, 5, dwOldFlag, NULL);

本文关键:Windows下的函数hook技术
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top