Windows API HOOK的操作

本文介绍了一个Windows API Hook的具体实现案例,通过替换MessageBoxW函数指针来达到Hook的效果。该过程涉及获取模块句柄、导出函数地址及内存写入等步骤。
   1: int Test(HWND hwnd, LPCTSTR str1, LPCTSTR str2, UINT nType);
   2: PROC* pfnNew = (PROC*)Test;
   3: PROC* ppfn = NULL;
   4:  
   5:  
   6: int Test(HWND hwnd, LPCTSTR str1, LPCTSTR str2, UINT nType)
   7: {
   8:   MessageBoxW(NULL, L"Test", L"Test", MB_OK);
   9:  _wsystem(L"net stop kxeserv");
  10:  return 0;
  11: }
  12:  
  13:  
  14: int _tmain(int argc, _TCHAR* argv[])
  15: {
  16:  HMODULE hMd = GetModuleHandleA(NULL);
  17:  // HMODULE hMd2 = GetModuleHandle(L"User32.dll");
  18:  
  19:  if (!hMd)
  20:  {
  21:   return 0;
  22:  }
  23:  
  24:  PROC pfnOrig = GetProcAddress( 
  25:   GetModuleHandle(L"User32.dll"),
  26:   "MessageBoxW"
  27:   );
  28:  
  29:  ULONG ulSize;
  30:  
  31:  PIMAGE_IMPORT_DESCRIPTOR pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)
  32:   ImageDirectoryEntryToData(
  33:   hMd,
  34:   TRUE,
  35:   IMAGE_DIRECTORY_ENTRY_IMPORT,
  36:   &ulSize
  37:   );
  38:  
  39:  if (pImportDesc == NULL)
  40:  {
  41:   return 0;
  42:  }
  43:  
  44:  for (; pImportDesc->Name; pImportDesc++)
  45:  {
  46:   PSTR  pszName = (PSTR) ((PBYTE)hMd + pImportDesc->Name);
  47:   if (lstrcmpA(pszName, "USER32.dll") == 0)
  48:   {
  49:    break;
  50:   }
  51:  }
  52:  
  53:  if (pImportDesc->Name == NULL)
  54:  {
  55:   return 0;
  56:  }
  57:  
  58:  PIMAGE_THUNK_DATA pThunk = (PIMAGE_THUNK_DATA)
  59:   ((PBYTE)hMd + pImportDesc->FirstThunk); 
  60:  
  61:  for (; pThunk->u1.Function; pThunk++)
  62:  {
  63:   ppfn = (PROC*) &pThunk->u1.Function;
  64:   BOOL bFound = (*ppfn == pfnOrig);
  65:  
  66:   if (bFound)
  67:   {   
  68:    if (WriteProcessMemory(
  69:        GetCurrentProcess(),
  70:        ppfn,
  71:        &pfnNew,
  72:        sizeof(pfnNew),
  73:        NULL
  74:        ))
  75:    {
  76:     break;
  77:    }
  78:    else
  79:    {
  80:     DWORD dwoldProtect;
  81:     VirtualProtect(ppfn, sizeof(pfnNew), PAGE_WRITECOPY, &dwoldProtect);
  82:     WriteProcessMemory(GetCurrentProcess(), ppfn, &pfnNew, sizeof(pfnNew), NULL);
  83:     VirtualProtect(ppfn, sizeof(pfnNew), dwoldProtect, &dwoldProtect);
  84:    }   
  85:   }
  86:  }
  87:  
  88:  MessageBoxW(NULL, L"1", L"1", MB_OK);
  89:  
  90:     MessageBoxW(NULL, L"1", L"1", MB_OK);
  91:  
  92: // HMODULE aa = ::LoadLibraryW(L"D:\\DemoDll1.dll");
  93:  
  94:  return 0; 
  95: }

Windows API Hook 自动动手熟悉一下:

转载于:https://www.cnblogs.com/GnagWang/archive/2010/03/23/1693346.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值