Windows Hook Hook Example

Source: Internet
Author: User

1. First write a Win32 DLL project.

" stdafx.h "
int WINAPI Add (int A,int b) { return a +b;}
BOOL apientry DllMain (HANDLE hmodule, DWORD ul_reason_for_call, lpvoid lpreserved) { return TRUE;}

Add an explicit export to the DEF file: (No def file found to add)

" ADD LA " exports add  @1;

2. Write the main program calling this DLL new dialog-based MFC project

Add a declaration to the DLG header file:

#include <windef.h>publicint (WINAPI*ADDPROC) (int A,int b); Addproc add;

Write the load function at the program entrance:

if (hadddll==NULL)  hadddll=::loadlibrary ("add.dll"); Add= (Addproc):: GetProcAddress (Hadddll,"add");

Add a button function call:

int a=1int b=2int c=Add (A, b); CString temp; Temp. Format ("%d+%d=%d", A,b,c); AfxMessageBox (temp);

Run the main program here and you'll see. Pop-up window 1+2 = 3 results.

3. Write the hook DLL to create a new MFC DLL project.

In the InitInstance function, add:

hinst=:: AfxGetInstanceHandle (); DWORD dwpid=:: GetCurrentProcessId (); hprocess=openprocess (process_all_access,0, dwpid) ;   return CWinApp::InitInstance ();

All the statements:

#pragmaData_seg ("SHARED")StaticHhook Hhk=null;//Mouse Hook handleStaticHINSTANCE Hinst=null;//instance handle for this DLL (Hook.dll)#pragmaData_seg ()#pragmaComment (linker, "/SECTION:SHARED,RWS")CString temp;//temporary variable to display the errorBOOLbhook=false;//whether the function is hookBOOLM_binjected=false;//whether the API was hookBYTE oldcode[5];//the old system API entry codeBYTE newcode[5];//API code to jump to (jmp xxxx)typedefint(Winapi*addproc) (intAintb);//the Add function definition in Add.dllAddproc add;//the Add function in Add.dllHANDLE Hprocess=null;//handle to the process in which it is locatedFarproc Pfadd;//far pointer to the Add functionDWORD Dwpid;//The process ID://end of variable definition//function DefinitionvoidHookon ();voidHookoff ();//Close HooksLRESULT CALLBACK Mouseproc (intNcode,wparam Wparam,lparam LPARAM);//Mouse hook functionvoidInject ();//A function that specifically injects, replaces the entranceintWINAPI Myadd (intAintb);//The new Add () function that we defineBOOL Installhook ();//Install hook functionvoidUninstallhook ();//Unload hook function

Declare the implementation of the function:

LRESULT CALLBACK Mouseproc (intNcode,wparam Wparam,lparam LPARAM) {LRESULT RetVal=CallNextHookEx (Hhk,ncode,wparam,lparam); returnRetVal;} BOOL Installhook () {hhk=::setwindowshookex (Wh_mouse,mouseproc,hinst,0); return true;}voidUninstallhook () {:: UnhookWindowsHookEx (HHK);} voidInject () {if(m_binjected==false) {m_binjected=true; Hmodule Hmod=::loadlibrary ("Add.dll"); Add= (Addproc):: GetProcAddress (Hmod,"Add"); Pfadd=(FARPROC) add; if(pfadd==NULL) {AfxMessageBox ("cannot locate Add ()"); }    //Save the entry code in Add () into oldcode[]_asm {Lea Edi,oldcode mov esi,pfadd CLD movsd MOVSB } newcode[0]=0xe9;//Actually, 0xe9 is equivalent to the JMP Directive .//gets the relative address of the Myadd ()_asm {Lea Eax,myadd mov ebx,pfadd sub eax,ebx sub eax,5mov dword ptr [Newcode+1],eax}//filled, now newcode[] in the instruction equivalent of jmp MyaddHookon ();//You can open the hook. }}voidHookon () {ASSERT (hprocess!=NULL); DWORD dwtemp=0;    DWORD Dwoldprotect; //Change the memory protection mode to writable, old mode saved into DwoldprotectVirtualprotectex (Hprocess,pfadd,5,page_readwrite,&dwoldprotect); //Change the first 5 bytes of Add () in a owning process to jmp MyaddWriteProcessMemory (Hprocess,pfadd,newcode,5,0); //Change the memory protection mode back to DwoldprotectVirtualprotectex (Hprocess,pfadd,5,dwoldprotect,&dwtemp); Bhook=true; }voidHookoff ()//restores the entry code for Add () in the owning process{ASSERT (hprocess!=NULL); DWORD dwtemp=0;    DWORD Dwoldprotect; Virtualprotectex (Hprocess,pfadd,5,page_readwrite,&dwoldprotect); WriteProcessMemory (Hprocess,pfadd,oldcode,5,0); Virtualprotectex (Hprocess,pfadd,5,dwoldprotect,&dwtemp); Bhook=false; }intWINAPI Myadd (intAintb) {    //intercept the call to add (), we add 1 to a, Ba=a+1; b=b+1; Hookoff ();//Turn off the Myadd () hook to prevent a dead loop    intret; RET=Add (A, b); Hookon ();//Turn on the Myadd () Hook    returnret;}

To add an explicit export to a DEF file:

Installhook   

The hook DLL is complete.

4. Go back to the main program add 2 buttons one to inject an uninstall:

Injection:

Hinst=loadlibrary ("Hook.dll"); if(hinst==NULL) {AfxMessageBox ("No hook.dll!"); return; } typedef BOOL (CALLBACK*Inshook)  (); Inshook Insthook; Insthook=::getprocaddress (Hinst,"Installhook"); if(insthook==NULL) {AfxMessageBox ("func not found!"); return;

DWORD Pid=::getcurrentprocessid ();
BOOL Ret=insthook ();

Unloading:

typedef BOOL (CALLBACK *unhookproc) ();  Unhookproc Uninstallhook; Uninstallhook=::getprocaddress (hinst,"uninstallhook"if( uninstallhook==if (hinst!=null) {  if (hadddll!=null) {  :: FreeLibrary (Hadddll); } cdialog::oncancel ();

To run the main program:

Calculation: Display 1+2 =3

Injection: Display 1+2=5

Finish.

There's no place to understand. Welcome harassment: 0x7317af28

Windows Hook Hook Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.