Detours的作用和实例(hook、钩子)
Detours 可以用來攔截Win32的API函數,從而讓程序按照我們自定義的方式進行處理,而不是Windows默認的。
Detours 也是通過Dll的方式,攔截Api函數。
為什么是修改API的前5個字節?
? 現在NewCode[]里的指令相當于Jmp MyMessageBoxW
? 既然已經獲取到了Jmp MyMessageBoxW
? 現在該是將Jmp MyMessageBoxW寫入原API入口前5個字節的時候了
? //知道為什么是5個字節嗎?
? //Jmp指令相當于0xe9,占一個字節的內存空間
? //MyMessageBoxW是一個地址,其實是一個整數,占4個字節的內存空間
? //int n=0x123; ? n占4個字節和MyMessageBoxW占4個字節是一樣的
? //1+4=5,知道為什么是5個字節了吧
例:攔截Win32的MessageBoxA()函數
1.先新建一個Dll工程
#include "detours.h" #pragma comment(lib,"detours.lib") //導入detours.h和detours.lib文件//static BOOL (WINAPI* Real_Messagebox)(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)=MessageBoxA; int (WINAPI *Real_Messagebox)(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)= MessageBoxA; //注意是MessageBoxA函數 extern "C" _declspec(dllexport) BOOL WINAPI MessageBox_Mine(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) {CString temp= lpText;temp+="該MessageBox已被Detours截獲!";return Real_Messagebox(hWnd,temp,lpCaption,uType); }//dll入口函數 BOOL WINAPI DllMain(HINSTANCE hInstDll, DWORD fdwReason, LPVOID lpvReserved) {if (DLL_PROCESS_ATTACH == fdwReason){DetourTransactionBegin();DetourUpdateThread(GetCurrentThread()); //當前線程DetourAttach(&(PVOID&)Real_Messagebox,MessageBox_Mine); //設置detourDetourTransactionCommit();}else if (DLL_PROCESS_DETACH == fdwReason){DetourTransactionBegin();DetourUpdateThread(GetCurrentThread());DetourDetach(&(PVOID&)Real_Messagebox,MessageBox_Mine);//卸載detourDetourTransactionCommit();}return TRUE;}特別要注意的就是MessageBox和MessageBoxA是不同的,我剛開始以為detours不會把它們區分,結果一直無法攔截成功。
2.新建一個MFC工程(在按扭響應函數中添加 MessageBoxA())
在其OnInitDialog()函數中 添加::LoadLibrary(L"messageDll.dll"); //注意路徑問題
然后在按鈕響應函數中添加?::MessageBoxA(NULL,"4444443","23",0);
這樣當成功后 點擊按鈕就可以攔截到MessageBox函數
效果如圖:
總結
以上是生活随笔為你收集整理的Detours的作用和实例(hook、钩子)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: USACO-Section2.1 Hea
- 下一篇: windows下nc(netcat)的安