C language Implementation Simple inline hook (Windows API)

Source: Internet
Author: User
Tags function prototype

My first essay, a brief introduction to the classic inline hook technology.

Hook-and-take (hooking) is a technique for intercepting information, changing the flow of a program, and adding new features. Hook-and-take technology is diverse, with the hook-and-Win32 API technology known as API Hook-and-take. It is commonly used in user mode (RING3) with message hooks. Here I take messageboxw this simple API as an example, to achieve a simple program itself inline hook.

MessageBoxW function Prototypes:

1 MessageBoxW (2     _in_opt_ hwnd hwnd,            //  parent window handle 3     _in_opt_ LPCW STR Lptext,       //  text 4     _in_opt_ lpcwstr lpcaption,//      title  5     _in_ UINT utype);              // Key type combinations

The so-called inline hook is to modify the first 5 bytes of the API code to the JMP xxxxxxxx directive to hook up the API. When the call executes the hooked API, the (modified) JMP xxxxxxxx instruction is executed, turning to the control hooking function.

Start of the API code before the hook

  

Start of API code after hook

  

It can be seen that after the hook, when the user calls the API, will jump directly to the hook handler function, in the hook processing function, you can do other operations, but need to ensure that the function prototype and parameters consistent, to ensure the stack balance. If you want to call the original API function inside the hooking function, you need to do "decoupling" before the call, otherwise if you call directly, the API begins with a jump instruction, will fall into a dead loop. After the call after the hook, convenient next time, the above is the approximate flow of hooks.

The detailed code is as follows:

#include <windows.h>#include<stdio.h>BYTE g_porgmsgboxw[5] = {0, };//5 bytes to store the beginning of the API//hooking function prototypes to ensure consistency with the original API (MessageBoxW)intWINAPI Newmessageboxw (HWND hwnd, LPCWSTR Lptext, Lpcwstr lpcaption, UINT utype);//function Pointerstypedefint(WINAPI *Pfmessageboxw) (HWND hwnd, LPCWSTR Lptext, Lpcwstr lpcaption, UINT utype); BOOL Inlinehook (LPCSTR szdllname, LPCSTR szfuncname, PROC pfnnew, pbyte porgbytes) {hmodule hmodule=NULL; Farproc PFunc= NULL;//API function PointersBYTE pbuf[5] = {0, };//5-byte code that forms a jump instructionPbyte pbyte =NULL; DWORD Dwoldprotect=0; DWORD Dwjmpoffset=0;//The offset value of the jump (= new function address-(original function address + 5))//get the target module handle (user32.dll)    if(! (hmodule =Getmodulehandlea (szdllname))) {printf ("Getmodulehandlea Error:%d\n", GetLastError ()); returnFALSE; }    //get the API address to hook up    if(! (PFunc =GetProcAddress (hmodule, Szfuncname))) {printf ("GetProcAddress Error:%d\n", GetLastError ()); returnFALSE; }    //Modify the memory properties, because this way you want to modify the in-Memory code dataVirtualProtect (LPVOID) PFunc,5, Page_readwrite, &dwoldprotect); //if it has been hook, it failsPbyte =(pbyte) PFunc; if(pbyte[0] ==0xe9)    {        returnFALSE; } memcpy (Porgbytes, PFunc,5);//Save the original codepbuf[0] =0xe9;//the first byte of the JMP xxxxxxxx directive is 0xe9Dwjmpoffset = (DWORD) pfnnew-((DWORD) PFunc +5);//calculate the offset value of a jumpmemcpy (&pbuf[1], &dwjmpoffset,4); memcpy (PFunc, PBuf,5);//Modify the code at the original API addressVirtualProtect (LPVOID) PFunc,5, Dwoldprotect, &dwoldprotect); returnTRUE;} BOOL unhook (LPCSTR szdllname, LPCSTR szfuncname, pbyte porgbytes) {hmodule hmodule=NULL; Farproc PFunc=NULL; Pbyte pbyte=NULL; DWORD Dwoldprotect=0; if(! (hmodule =Getmodulehandlea (szdllname))) {printf ("Getmodulehandlea Error:%d\n", GetLastError ()); returnFALSE; }    if(! (PFunc =GetProcAddress (hmodule, Szfuncname))) {printf ("GetProcAddress Error:%d\n", GetLastError ()); returnFALSE; } virtualprotect (LPVOID) PFunc,5, Page_readwrite, &dwoldprotect); //failure if not hookPbyte =(pbyte) PFunc; if(pbyte[0] !=0xe9)    {        returnFALSE; } memcpy (PFunc, Porgbytes,5);//Restore the code of the original APIVirtualProtect (LPVOID) PFunc,5, Dwoldprotect, &dwoldprotect); returnTRUE;}intWINAPI Newmessageboxw (HWND hwnd, LPCWSTR Lptext, Lpcwstr lpcaption, UINT utype) {intIRet =0; Farproc PFunc=NULL; //To invoke the original API, "decoupling" is required hereUnhook ("user32.dll","MessageBoxW", G_porgmsgboxw); if(! (PFunc = GetProcAddress (Getmodulehandlea ("user32.dll"),"MessageBoxW")) {printf ("GetProcAddress Error:%d\n", GetLastError ()); returnFALSE; }    //calling the original APIIRet = ((PFMESSAGEBOXW) pFunc) (HWnd, L"you're a hook!", Lpcaption, Utype); //Hook again to facilitate the nextInlinehook ("user32.dll","MessageBoxW", (PROC) Newmessageboxw, G_porgmsgboxw); returnIRet;}intMain () {Inlinehook ("user32.dll","MessageBoxW", (PROC) Newmessageboxw, G_porgmsgboxw); MessageBoxW (NULL, L"this is normal.", L"Tips", MB_OK); Unhook ("user32.dll","MessageBoxW", G_porgmsgboxw); MessageBoxW (NULL, L"this is normal.", L"Tips", MB_OK); return 0;}

Operation Result:

This is just the program itself hook, no use of DLL injection technology, will be written later.

C language Implementation Simple inline hook (Windows API)

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.