hook api的一例子 C+/VC

 hook api的一例子 C+/VC
[ 2008-7-30 22:33:00 | 发表者 : zihe ]

帮同学写了个hook api的例子程序,顺便post到这儿,免得将来到处找.
一个简单的console工程,vc6,vc7在win2k pro,server上调试通过.
#include <stdio.h>
#include <windows.h>
#include <dbghelp.h>
#pragma comment(lib,"dbghelp.lib")
#pragma comment(lib,"user32.lib")
typedef int (__stdcall *old_messagebox)( hwnd hwnd, lpctstr lptext, lpctstr lpcaption,uint utype );
old_messagebox g_procoldmessagebox = null;
int __stdcall hook_messagebox( hwnd hwnd, lpctstr lptext, lpctstr lpcaption,uint utype)
{
 printf("%s/t%d/r/n",__function__,__line__);
 if (null != g_procoldmessagebox)
  return g_procoldmessagebox(hwnd,lptext,"不好意思,hook到了!",utype); 
 else
  return messagebox(hwnd,lptext,lpcaption,utype); ;
}

int replace_iat(const char *pdllname,const char *papiname,bool breplace)
{
 handle hprocess = ::getmodulehandle (null);
 dword dwsize = 0;
 pimage_import_descriptor pimageimport = (pimage_import_descriptor)imagedirectoryentrytodata(hprocess,true,
  image_directory_entry_import,&dwsize);
 if (null == pimageimport)
  return 1;
 pimage_import_by_name pimageimportbyname = null;
 pimage_thunk_data  pimagethunkoriginal = null;
 pimage_thunk_data  pimagethunkreal  = null;
 while (pimageimport->name)
 {
  if (0 == strcmpi((char*)((pbyte)hprocess+pimageimport->name),pdllname))
  {
   break;
  }
  ++pimageimport;
 }
 if (! pimageimport->name)
  return 2;
 pimagethunkoriginal = (pimage_thunk_data)((pbyte)hprocess+pimageimport->originalfirstthunk  );
 pimagethunkreal = (pimage_thunk_data)((pbyte)hprocess+pimageimport->firstthunk   );
 while (pimagethunkoriginal->u1.function)
 {
  if ((pimagethunkoriginal->u1 .ordinal & image_ordinal_flag) != image_ordinal_flag)
  {
   pimageimportbyname = (pimage_import_by_name)((pbyte)hprocess+pimagethunkoriginal->u1 .addressofdata );
   if (0 == strcmpi(papiname,(char*)pimageimportbyname->name))
   {
    memory_basic_information mbi_thunk;
    virtualquery(pimagethunkreal, &mbi_thunk, sizeof(memory_basic_information)); 
    virtualprotect(mbi_thunk.baseaddress,mbi_thunk.regionsize, page_readwrite, &mbi_thunk.protect); 
    if (true == breplace)
    {
     g_procoldmessagebox =(old_messagebox) pimagethunkreal->u1.function; 
     pimagethunkreal->u1.function = (dword)hook_messagebox;
    }
    else
     pimagethunkreal->u1.function = (dword)g_procoldmessagebox;
    dword dwoldprotect; 
    virtualprotect(mbi_thunk.baseaddress, mbi_thunk.regionsize, mbi_thunk.protect, &dwoldprotect);
    break;
   }
  }
  ++pimagethunkoriginal;
  ++pimagethunkreal;
 }
 return 0;
}
int main()
{
 replace_iat("user32.dll","messageboxa",true);
 messagebox(null,"enumiat user32.dll messageboxa true;","",mb_ok);
 replace_iat("user32.dll","messageboxa",false);
 messagebox(null,"enumiat user32.dll messageboxa false;","",mb_ok);
 return getchar();
}

你可能感兴趣的:(c,api,null,import,hook,Descriptor)