APIHOOK instance analysis

zhaozj2021-02-16  44

APIHOOK instance analysis

There are a lot of basic knowledge of APIHOOK, such as DLL's related knowledge, Hook's related knowledge, contact between system processes and threads. Specifically you can see another article: "My DLL (Dynamic Link Library) Learning Notes" and "My Hook Learning Notes". :) The following is the focus of this article, and analyzes APIHOOK according to the APIHOK source code. First, the APIHOOK DLL section APIHOOK_DLL.CPP // Rivershan is written in 2002.9.23 /////

#include "stdafx.h" #include "apihook_dll.h"

#include #include

#pragma comment (lib, "imagehlp") // Define global shared data segment

#pragma data_seg ("shared") hmodule hmoddll = null; hHOOK hHOOK = NULL;

#pragma data_seg ()

#pragma Comment (Linker, "/ Section: Shared, RWS") // Setting the properties of the global shared data segment

/ DllMain function /// dll entry point BOOL APIENTRY DllMain (HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {switch (ul_reason_for_call) {case DLL_PROCESS_ATTACH: // if (sHook) case DLL_PROCESS_DETACH: UnInstallHook (); break;} hmodDll = HModule; Return True;

/ HookoneAPI function /// Make IAT conversion key functions, its parameter meanings: // pszcalleemodulename: Module name // pfNoriginapiadDress: Hook's address // pfndummyfuncaddress: need hook's module name required for HOOK / / hmodcallermodule: The name of the module we have to find, if not assigned, // will be assigned to the programs all called modules

Void WinAPI HookoneApi (LPCTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSZCALLEMODULENAME, PROC PFNORIGINAPIADDRESS, PROC PFNDUMMYFuncaddress, HModule Hmodcallermodule] {Ulong Size

/ / Get pointers in the image_directory_descriptor array in the Import to the IMPORT in the PE file

PIMAGE_IMPORT_DESCRIPTOR PIMPORTDESC = (PIMAGE_IMPORT_DESCRIPTOR) ImageDirectoryEntryTodata (hmodcallermodule, true, image_directory_entry_import, & size);

IF (pimportDesc == null) return;

/ / Find records to see if there is any DLL we want

for (; pImportDesc-> Name; pImportDesc ) {LPSTR pszDllName = (LPSTR) ((PBYTE) hModCallerModule pImportDesc-> Name); if (lstrcmpiA (pszDllName, pszCalleeModuleName) == 0) break;} if (pImportDesc-> Name == null) {return;}

// Looking for the functions we want

PIMAGE_THUNK_DATA PTHUNK = (PIMAGE_THUNK_DATA) (PBYTE) HMODCALLERMODULE PIMPORTDESC-> firstthunk); // Iat for (; pthunk-> u1.function; pthunk ) {// PPFN records the address corresponding to the IAT entry

Proc * PPFN = (Proc *) & pthunk-> u1.function; if (* ppfn == pfnoriginapiaddress) {// If the address is the same, that is, the function we want, rewrite, point to us to define function

WriteProcessMemory (GetCurrentProcess (), PPFN, & (PfndummyFuncaddress), Sizeof (PfndummyFuncaddress), NULL;}}}

/ / Find the DLL module applied by the hook

BOOL WINAPI HookAllAPI (LPCTSTR pszCalleeModuleName, PROC pfnOriginApiAddress, PROC pfnDummyFuncAddress, HMODULE hModCallerModule) {if (pszCalleeModuleName == NULL) {return FALSE;} if (pfnOriginApiAddress == NULL) {return FALSE;} // if not passed in to hook Module name, enumerate all referenced modules of the hook process, // and find the corresponding function name for these modules to find if (hmodcallermodule == null) {MEMORY_BASIC_INFORMATION Minfo; HModule HModHookDll; HModule Hsnapshot; ModuleTry32 me = { SIZEOF (ModuleEntry32)}; // moduleEntry32: Describes the structure of the module applied by the specified process

VirtualQuery (HookOneAPI, & mInfo, sizeof (mInfo)); hModHookDLL = (HMODULE) mInfo.AllocationBase; hSnapshot = CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, 0); BOOL bOk = Module32First (hSnapshot, & me); while (bOk) {if (me.hModule ! = hModHookDLL) {hModCallerModule = me.hModule; // assignment //me.hModule: HookOneAPI this point each module is linked to the process (pszCalleeModuleName, pfnOriginApiAddress, pfnDummyFuncAddress, hModCallerModule);} bOk = Module32Next (hSnapshot, & me); } return TRUE;} // if the passed in, to find else {HookOneAPI (pszCalleeModuleName, pfnOriginApiAddress, pfnDummyFuncAddress, hModCallerModule); return TRUE;} return FALSE;} UnhookAllAPIHooks /// function and method by pfnDummyFuncAddress equal pfnOriginApiAddress, canceled modification of the IAT BOOL WINAPI UnhookAllAPIHooks (LPCTSTR pszCalleeModuleName, PROC pfnOriginApiAddress, PROC pfnDummyFuncAddress, HMODULE hModCallerModule) {PROC temp; temp = pfnOriginApiAddress; pfnOriginApiAddress = pfnDummyFuncAddress; pfnDummyFuncAddress = temp; return HookAllAPI (pszCalleeModuleName, pf Noriginapiaddress, Pfndummyfuncaddress, HMODCALLERMODULE);

// getMSGProc function // hook subsidiary. With other hooks, there is no meaningful thing, continue to call the next hook subsidy, form a cycling LResult Callback GetMsgProc (int Cord, WParam WParam, LParam Lparam) {Return CallNexthookex (HHOOK, CODE, WPARAM, lparam;

InstallHook function /// Install or unload hooks, BOOL ISHOOK parameters are flag bits // Which API function is to be hooked to initialize // We are installing the hook type is wh_getMessagevoid __Declspec (dllexport) WinAPI Installhook (Bool Ishook, DWORD DWTHREADID) { if (IsHook) {hHook = SetWindowsHookEx (WH_GETMESSAGE, (HOOKPROC) GetMsgProc, hmodDll, dwThreadId); //GetProcAddress(GetModuleHandle("GDI32.dll"),"ExtTextOutA "): to obtain the address of the function hook dll is located HookAllAPI ( "GDI32.dll", GetProcAddress (GetModuleHandle ( "GDI32.dll"), "TextOutW"), (PROC) & H_TextOutW, NULL); HookAllAPI ( "GDI32.dll", GetProcAddress (GetModuleHandle ( "GDI32.dll") , "TextOutA"), (PROC) & H_TextOutA, NULL);} else {UnInstallHook (); UnhookAllAPIHooks ( "GDI32.dll", GetProcAddress (GetModuleHandle ( "GDI32.dll"), "TextOutW"), (PROC) & H_TextOutW, NULL); UnhookAllAPIHooks ( "GDI32.dll", GetProcAddress (GetModuleHandle ( "GDI32.dll"), "TextOutA"), (PROC) & H_TextOutA, NULL);}} / UnInstallHook unloading hook function // BOOL WINAPI UnInstallHook () { UnHookWindowshookex (hHOOK); Return True;}

/ H_textouta function /// Our replacement function, can implement the features we have to do // here I do to display a dialog, indicate which function is replaced BOOL WINAPI H_TEXTOUTA (HDC HDC, Int NxStart, int NYStart , LPCSTR LPSTRING, INT CBSTRING {MessageBox (Null, "Textouta", "APIHOK_DLL --- Rivershan", MB_OK; Textouta (HDC, NXSTART, NYSTART, LPSTRING, CBSTRING); // Returns the original function to display characters Return True;}

/ H_TextOutW function /// supra BOOL WINAPI H_TextOutW (HDC hdc, int nXStart, int nYStart, LPCWSTR lpString, int cbString) {MessageBox (NULL, "TextOutW", "APIHook_Dll --- rivershan", MB_OK); TextOutW (hdc, NxStart, NYSTART, LPSTRING, CBSTRING; // Returns the original function to display character return true;}

*********************************************************** *********************************************************** *********************************************************** *************************************************************** APIHOK_DLL.H // Rivers Han is written in 2002.9.23 / //

// DLL header file for declaration functions

Void __declspec (DLLEXPORT) WinAPI Installhook (Bool, DWORD); BOOL WINAPI Uninstallhook (); LRESULT CALLBACK GETMSGPROC (Int Code, WPARAM WPARAM, LPARAM LPARAM);

void WINAPI HookOneAPI (LPCTSTR pszCalleeModuleName, PROC pfnOriginApiAddress, PROC pfnDummyFuncAddress, HMODULE hModCallerModule); BOOL WINAPI HookAllAPI (LPCTSTR pszCalleeModuleName, PROC pfnOriginApiAddress, PROC pfnDummyFuncAddress, HMODULE hModCallerModule); BOOL WINAPI UnhookAllAPIHooks (LPCTSTR pszCalleeModuleName, PROC pfnOriginApiAddress, PROC pfnDummyFuncAddress, HMODULE hModCallerModule) ;

Bool WinAPI H_TextOuta (HDC, INT, INT, LPCSTR, INT); Bool WinAPI H_TextOutw (HDC, INT, INT, LPCWSTR, INT); BOOL WINAPI H_EXTTEXTATA (HDC, INT, INT, UINT, Const Rect *, LPCSTR, UINT, Const Int *); BOOL WINAPI H_EXTTEXTOUTW (HDC, INT, INT, UINT, Const Rect *, LPCWSTR, UINT, Const Int *);

*********************************************************** *********************************************************** *********************************************************** ***********************************************

; APIHOK_DLL DEF file library APIHOOK_DLL.DLLEXPORT Installhook II, APIHOOK EXE section

Apihook_exedlg.cpp /// Rivershan written in 2002.9.23 ///

#include "stdafx.h" #include "apihook_exe.h" #include "APIHOK_EXEDLG.H" #include "apihook_dll.h"

#ifdef _debug # define new debug_new # undef this_filestatic char this_file [] = __file __; # endif // Capihook_exedlg Dialog

CAPIHook_EXEDlg :: CAPIHook_EXEDlg (CWnd * pParent / * = NULL * /): CDialog (CAPIHook_EXEDlg :: IDD, pParent) {// {{AFX_DATA_INIT (CAPIHook_EXEDlg) // NOTE: the ClassWizard will add member initialization here //}} AFX_DATA_INIT // Note That Loadicon Does Not Require A Subsequent Destroyicon in Win32 M_HICON = AFXGetApp () -> loadicon (iDR_mainframe);

void CAPIHook_EXEDlg :: DoDataExchange (CDataExchange * pDX) {CDialog :: DoDataExchange (pDX); // {{AFX_DATA_MAP (CAPIHook_EXEDlg) // DDX_Control (pDX, IDC_EDIT1, m_Edit); //}} AFX_DATA_MAP}

BEGIN_MESSAGE_MAP (CAPIHook_EXEDlg, CDialog) // {{AFX_MSG_MAP (CAPIHook_EXEDlg) ON_WM_PAINT () ON_WM_QUERYDRAGICON () ON_BN_CLICKED (IDC_BUTTON_OUT, OnButtonOut) ON_BN_CLICKED (IDC_BUTTON_BEGIN, OnButtonBegin) ON_BN_CLICKED (IDC_BUTTON_STOP, OnButtonStop) //}} AFX_MSG_MAPEND_MESSAGE_MAP ()

/// CapiHook_exedlg Message Handlers

BOOL CAPIHook_EXEDlg :: OnInitDialog () {CDialog :: OnInitDialog (); // Set the icon for this dialog The framework does this automatically // when the application's main window is not a dialog SetIcon (m_hIcon, TRUE);. // Set Big icon seticon (m_hicon, false); // set small icon // Todo: add extra initialization he Return true; // return true unless}

// if you add a minimize button to your dialog, you will need the code Below // to draw the icon. For mfc Applications Using the document / view model, // this is automaticly done for you by the framework.

void CAPIHook_EXEDlg :: OnPaint () {if (IsIconic ()) {CPaintDC dc (this); // device context for painting SendMessage (WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc (), 0); // Center icon in client rectangle INT cxicon = getSystemMetrics; int Cyicon = getSystemMetrics (sm_cyicon); CRECT RECT; getClientRect (& Re); int x = (Rect.width () - CXICON 1) / 2; int y = (Rect.height () - Cyicon 1) / 2; // Draw the icon dc.drawicon (x, y, m_hicon);} else {cdialog :: onpaint ();}} // the system calls this to obtain the cursor to display while the user drags // the minimized window.HCURSOR CAPIHook_EXEDlg :: OnQueryDragIcon () {return (HCURSOR) m_hIcon;} / OnButtonOut function //// use TextOut function void CAPIHook_EXEDlg :: OnButtonOut () {// TODO: Add your control notification handler Code Here HDC HDC = :: getdc () ;: Textouta (HDC, 0, 0, "APIHOK_EXE --- Rivershan, 30); UpdateWindow ();}

/ OnButtonBegin // start hook function, here we are linked to the program itself APIHook_EXE this void CAPIHook_EXEDlg :: OnButtonBegin () {DWORD dwThreadId = GetWindowThreadProcessId (m_hWnd, NULL); // get own process ID InstallHook (TRUE, dwThreadId);}

/ OnButtonStop function // Cancel hook void capihook_exedlg :: OnButtonStop () {Installhook (false, 0);}

Third, the integration of APIHOOK

1. Create a Win32 Dynamic-Link Library program with VC , named APIHOOK_DLL. Next, select the second A Simple DLL Project; 2. Newly built a file, named APIHOOK_DLL.H. Delete the original content in the APIHOOK_DLL.CPP file, then copy the contents of the above APIHOOK_DLL.CPP and APIHOOK_DLL.H files to the newly created .cpp and .h files; 3. Create a TEXT file, Named APIHOOK_DLL.DEF. Copy the contents of the DEF file above. 4. Compile; 5. New MFC AppWizard (EXE) program named APIHOK_EXE. Then select the third item, the program based on the dialog, other defaults; 6. Delete the control on the original dialog, then create three buttons IDs are: IDC_Button_Begin, IDC_Button_Stop, IDC_Button_out, Caption is: Bigin Hook, STOP HOOK, TEXT OUT. Do not let these three buttons are on the top of the dialog clip; 7. Copy the APIHOOK_DLL.H file to the APIHOOK_EXE program directory, then add it to the APIHOK_EXE's header folder. 8. Delete the original content in the project in the project, then copy the contents of the above APIHOOK_EXEDLG.CPP file to the newly built project. C.CPP file; 9. Open the Project-> Setting menu, select Fourth Item LINK, add the path to our DLL lib file in Object / library moduls: ../ APIHOOK_DLL / Debug / APIHOK_DLL.LIB; 10. Compile; 11. Place the APIHOOK_DLL.DLL file in the same one of the APIHOOK_DLL.EXE program In the folder; 12. Run the program, click the Bigin Hook button, start hook. Then click the Text Out button to jump out of the dialog and display the words you want to display in the program. Click on the Stop Hook and then there is no dialog box that click the Text Out button. Fourth, some explanation

1. This hookapi is an IAT of the Jeffrey Richter's overwriting program, or it can be implemented with the way of jump function entry points. This I didn't do research. :)

2, some of my experience:

The so-called hookaPi is the IAT of the rewrite program, then calls my own function to replace the original API function. In our own written API function, we can work we want. After that, you can pass the original function back, or you can't pass it, as long as you design it.

The so-called calling your own function is to pass the original function parameters to my replacement function. We can use these parameters to do things we want to do. And the system, I think the purpose of this hook set by Microsoft (I think so), so I will not check whether the replacement function is the original function, as long as the parameter, the return value meets the conditions, and will not be wrong. The return value of the replacement function is preferably the original function, otherwise it may be wrong.

When HOOKAPI, the effect of the exe program is to perform HOOK, injecting the DLL into the program to HOOK, and pass the ID or global hook to the process you want to hook, to query the IAT of the module you want to hook. If you don't inject it, the system will not let you query IAT. What DLL does is to determine which function to be hung and which DLL is in this DLL. Rivershan original in 2002-9-23

转载请注明原文地址:https://www.9cbs.com/read-26680.html

New Post(0)