hook api 檢測(hookapi)

導讀 大家好,小晉來為大家解答以上問題,hook api 檢測,hookapi很多人還不知道,現在讓我們一起來看看吧!2、新建一個DoInjectionMain c(不

大家好,小晉來為大家解答以上問題,hook api 檢測,hookapi很多人還不知道,現在讓我們一起來看看吧!

2、新建一個DoInjectionMain.c(不是CPP),代碼如下:#包含窗口。h #包含stdio。h #包含TL幫助32。h包括tchar。h #包括' do注入。h ' # pragma comment(lib,' th32.lib')#pragma comment(lib,' Advapi32.lib') //這個路徑很有意思,這個路徑是相對于目標進程的,而不是自身進程。//所以要嘛寫成絕對路徑,要嘛寫成相對于目標進程的相對路徑。//如果寫成相對于自身的路徑就要麻煩了,本程序就找不到動態鏈接庫文件了const char * pcDllName=' mfchookapi。dll ';//DLL文件的路徑HANDLE hSnap=0,hThreadHandle=0,hRemoteProcess32=0,hTokenHandle=0;程序輸入32程序輸入32;BOOL bNext=FALSE,bWrittenResult=FALSE token _ PRIVILEGES令牌權;標識符路德鮑爾;LP void pRemoteBuf=NULLFARPROC fndllkernel 32 size _ t size written=0;DWORD dwThreadId=0;char * pcproessname=' dowin 32測試。exe ';//要注入的進程名(目標進程名)int main(){ isvisatorlayer();SetPrivilege(SE_DEBUG_NAME,TRUE);//注入進程();InjectCreateProcess();getchar();返回0;} BOOL set privilege(LPCTSTR lpsz privilege,BOOL be nable privilege){ TOKEN _ PRIVILEGES TP;處理hTokenLUID流體;如果(!OpenProcessToken(GetCurrentProcess(),TOKEN _ ADJUST _ PRIVILEGES | TOKEN _ QUERY,hToken)){ _ tprintf(' OpenProcessToken error :% u \ r \ n ',GetLastError());返回FALSE}如果(!LookupPrivilegeValue(NULL,lpszPrivilege,luid)){ _ tprintf(' LookupPrivilegeValue error :% u \ r \ n ',GetLastError());返回FALSE} tp .PrivilegeCount=1;tp .權限[0]。標識符

4、MfcHookApi.cpp代碼如下:// MfcHookApi.cpp : Defines the initialization routines for the DLL.// #include "stdafx.h"#include "MfcHookApi.h"#include <TlHelp32.h>#include <stdio.h>#include <Shlwapi.h> #pragma comment(lib,"shlwapi.lib")#pragma comment(lib,"th32.lib") #ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#endif //// Note!//// If this DLL is dynamically linked against the MFC// DLLs,any functions exported from this DLL which// call into MFC must have the AFX_MANAGE_STATE macro// added at the very beginning of the function.//// For example://// extern "C" BOOL PASCAL EXPORT ExportedFunction()// {// AFX_MANAGE_STATE(AfxGetStaticModuleState());// // normal function body here// }//// It is very important that this macro appear in each// function,prior to any calls into MFC. This means that// it must appear as the first statement within the // function,even before any object variable declarations// as their constructors may generate calls into the MFC// DLL.//// Please see MFC Technical Notes 33 and 58 for additional// details.// /////////////////////////////////////////////////////////////////////////////// CMfcHookApiApp BEGIN_MESSAGE_MAP(CMfcHookApiApp,CWinApp) //{{AFX_MSG_MAP(CMfcHookApiApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAPEND_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////////// CMfcHookApiApp construction CMfcHookApiApp::CMfcHookApiApp(){ // TODO: add construction code here, // Place all significant initialization in InitInstance} /////////////////////////////////////////////////////////////////////////////// The one and only CMfcHookApiApp object CMfcHookApiApp theApp; HHOOK hHook=0;HINSTANCE hinstDll=0;DWORD dwCurrentPid=0;DWORD TargetPid=0;BOOL bApiHook=false; FARPROC fpApiAddrA=NULL,fpApiAddrW=NULL;BYTE btOldCodeA[5]={0,0,0,0,0};BYTE btNewCodeA[5]={0,0,0,0,0};BYTE btOldCodeW[5]={0,0,0,0,0};BYTE btNewCodeW[5]={0,0,0,0,0};DWORD dwProtect=0;HANDLE hRemoteProcess32=0,hSnap=0;//#pragma data_seg()//#pragma comment(linker,"/SECTION:YuKai,rws")int nHookCount=0; char* pcProsessName="DoWin32Test.exe"; //---------------------------------------------------------------------------// 空的鉤子函數LRESULT WINAPI HookProc(int nCode,WPARAM wParam,LPARAM lParam){ return CallNextHookEx(hHook,nCode,wParam,lParam);} extern "C" __declspec(dllexport) void ActiveHook(){ AFX_MANAGE_STATE(AfxGetStaticModuleState());} //---------------------------------------------------------------------------//本函數一定要用WINAPI(即__stdcall),表示本函數自己平衡堆棧(和win32 API一致)int WINAPI HookMessageBoxA(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType) { nHookCount++; printf("HookMessageBoxA hook Success......%d\r\n",nHookCount); return 1; //return ((PfnMessageBox)(addrMsgBoxA))(NULL,"HOOK成功","HOOK成功",MB_ICONINFORMATION);} //---------------------------------------------------------------------------//本函數一定要用WINAPI(即__stdcall),表示本函數自己平衡堆棧(和win32 API一致)int WINAPI HookMessageBoxW(HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType) { nHookCount++; printf("HookMessageBoxW hook Success......%d\r\n",nHookCount); return 1; //return ((PfnMessageBox)(addrMsgBoxW))(NULL,"HOOK成功","HOOK成功",MB_ICONINFORMATION);} //---------------------------------------------------------------------------// 安裝卸載空鉤子(ProcessID=NULL:卸載)extern "C" __declspec(dllexport) void InstallHook4Api(HWND hwnd){ AFX_MANAGE_STATE(AfxGetStaticModuleState()); //GetWindowThreadProcessId(hwnd,&TargetPid); //只hook窗口句柄為hwnd的線程 if(hwnd) hHook=SetWindowsHookEx(WH_GETMESSAGE,(HOOKPROC)HookProc,hinstDll,GetWindowThreadProcessId(hwnd,&TargetPid)); else { if(hHook) UnhookWindowsHookEx(hHook); }} void SetHookMessageBox(HMODULE hModule){ HMODULE hModuleUser32=0; char cArrDllName[256]; hinstDll=(HINSTANCE)hModule; BOOL bNext=FALSE; PROCESSENTRY32 procEntry32; //獲取目標進程句柄。 procEntry32.dwSize=sizeof(PROCESSENTRY32); hSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); bNext=Process32First(hSnap,&procEntry32); while(bNext) { if(!stricmp(procEntry32.szExeFile,pcProsessName)) //--->> { hRemoteProcess32=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_VM_WRITE|PROCESS_VM_OPERATION,1,procEntry32.th32ProcessID); break; } bNext=Process32Next(hSnap,&procEntry32); } CloseHandle(hSnap); dwCurrentPid=procEntry32.th32ProcessID; //載入需要HOOK的DLL并保存原始ESP hModuleUser32=LoadLibrary("user32.dll"); fpApiAddrA=GetProcAddress(hModuleUser32,"MessageBoxA"); if(fpApiAddrA==NULL) return; _asm { pushad lea edi,btOldCodeA mov esi,fpApiAddrA cld movsd movsb popad } btNewCodeA[0]=0xe9; _asm { lea eax,HookMessageBoxA mov ebx,fpApiAddrA sub eax,ebx sub eax,5 mov dword ptr [btNewCodeA+1],eax } //修改ESP VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrA,btNewCodeA,5,0); VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,dwProtect,&dwProtect); //載入需要HOOK的DLL并保存原始ESP fpApiAddrW=GetProcAddress(hModuleUser32,"MessageBoxW"); if(fpApiAddrW==NULL) return; _asm { pushad lea edi,btOldCodeW mov esi,fpApiAddrW cld movsd movsb popad } btNewCodeW[0]=0xe9; _asm { lea eax,HookMessageBoxW mov ebx,fpApiAddrW sub eax,ebx sub eax,5 mov dword ptr [btNewCodeW+1],eax } //修改ESP VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrW,btNewCodeW,5,0); VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,dwProtect,&dwProtect); bApiHook=true; //增加引用次數后立即卸鉤(目的:卸鉤后保留該dll存在于目標進程中) GetModuleFileName((HINSTANCE)hModule,cArrDllName,256); LoadLibrary(cArrDllName); //只能由目標程序卸鉤,否則目標程序有可能來不及加載Hook進來的dll if(hHook && (dwCurrentPid==TargetPid)) UnhookWindowsHookEx(hHook); } void SetHookDispatchMessage(HMODULE hModule){ HMODULE hModuleUser32=0; char cArrDllName[256]; hinstDll=(HINSTANCE)hModule; BOOL bNext=FALSE; PROCESSENTRY32 procEntry32; //獲取目標進程句柄。 procEntry32.dwSize=sizeof(PROCESSENTRY32); hSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); bNext=Process32First(hSnap,&procEntry32); while(bNext) { if(!stricmp(procEntry32.szExeFile,pcProsessName)) { hRemoteProcess32=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_VM_WRITE|PROCESS_VM_OPERATION,1,procEntry32.th32ProcessID); break; } bNext=Process32Next(hSnap,&procEntry32); } CloseHandle(hSnap); dwCurrentPid=procEntry32.th32ProcessID; //載入需要HOOK的DLL并保存原始ESP hModuleUser32=LoadLibrary("user32.dll"); fpApiAddrA=GetProcAddress(hModuleUser32,"DispatchMessageA"); if(fpApiAddrA==NULL) return; _asm { pushad lea edi,btOldCodeA mov esi,fpApiAddrA cld movsd movsb popad } btNewCodeA[0]=0xe9; _asm { lea eax,HookDispatchMessageA mov ebx,fpApiAddrA sub eax,ebx sub eax,5 mov dword ptr [btNewCodeA+1],eax } //修改ESP VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrA,btNewCodeA,5,0); VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,dwProtect,&dwProtect); //載入需要HOOK的DLL并保存原始ESP fpApiAddrW=GetProcAddress(hModuleUser32,"DispatchMessageW"); if(fpApiAddrA==NULL) return; _asm { pushad lea edi,btOldCodeW mov esi,fpApiAddrW cld movsd movsb popad } btNewCodeW[0]=0xe9; _asm { lea eax,HookDispatchMessageW mov ebx,fpApiAddrW sub eax,ebx sub eax,5 mov dword ptr [btNewCodeW+1],eax } //修改ESP VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrW,btNewCodeW,5,0); VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,dwProtect,&dwProtect); bApiHook=true; //增加引用次數后立即卸鉤(目的:卸鉤后保留該dll存在于目標進程中) GetModuleFileName((HINSTANCE)hModule,cArrDllName,256); LoadLibrary(cArrDllName); //只能由目標程序卸鉤,否則目標程序有可能來不及加載Hook進來的dll if(hHook && (dwCurrentPid==TargetPid)) UnhookWindowsHookEx(hHook); } LRESULT WINAPI HookDispatchMessageA(MSG* msg){ CString szFormat=""; CString szLog=""; CTime time; CString szFileName=""; DWORD dwFlag=0; RECT rc; TCHAR szCaption[128]; //HMODULE hDll=0; //DLLDISPATCHMESSAGE dispatch; LRESULT lr=0; //hDll=LoadLibrary("user32.dll"); //if (hDll) //{ // dispatch=(DLLDISPATCHMESSAGE)GetProcAddress(hDll,"DispatchMessageA"); // if (dispatch) // { // lr=(dispatch)(msg); // } //} VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrA,btOldCodeA,5,0); VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,dwProtect,&dwProtect); lr=DispatchMessageA(msg); //寫日志 szFormat="%-16X%-16X%-16X%-16X%-16d%-16d%-16X%-16d%-16d%-128s\r\n"; memset(szCaption,0,128); if (IsWindow(msg->hwnd)) { GetWindowRect(msg->hwnd,&rc); GetWindowText(msg->hwnd,szCaption,128); szLog.Format(szFormat,msg->hwnd,msg->message,msg->wParam,msg->wParam,msg->pt.x,msg->pt.y,msg->time,rc.right,rc.bottom,szCaption); } else { szLog.Format(szFormat,msg->hwnd,msg->message,msg->wParam,msg->wParam,msg->pt.x,msg->pt.y,msg->time,-1,-1,szCaption); } time=CTime::GetCurrentTime(); szFileName=time.Format("%Y%m%d%H"); szFileName.Insert(0,"C:\\DM"); szFileName+=".log"; dwFlag=CFile::modeReadWrite|CFile::shareDenyRead; if (!PathFileExists(szFileName)) { dwFlag|=CFile::modeCreate; } CFile fileLog(szFileName,dwFlag); fileLog.SeekToEnd(); fileLog.Write(szLog,szLog.GetLength()); fileLog.Flush(); fileLog.Close(); //重新HOOK以便寫日志 VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrA,btNewCodeA, 5, 0); VirtualProtectEx(hRemoteProcess32,fpApiAddrA,5,dwProtect,&dwProtect); return lr;} LRESULT WINAPI HookDispatchMessageW(MSG* msg){ CString szFormat=""; CString szLog=""; CTime time; CString szFileName=""; DWORD dwFlag=0; RECT rc; DWORD dwThreadId=0; TCHAR szCaption[128]; //HMODULE hDll=0; //DLLDISPATCHMESSAGE dispatch; LRESULT lr=0; //hDll=LoadLibrary("user32.dll"); //if (hDll) //{ // dispatch=(DLLDISPATCHMESSAGE)GetProcAddress(hDll,"DispatchMessageW"); // if (dispatch) // { // lr=(dispatch)(msg); // } //} //恢復HOOK VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrW,btOldCodeW,5,0); VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,dwProtect,&dwProtect); lr=DispatchMessageW(msg); szFormat="%-16X%-16X%-16X%-16X%-16d%-16d%-16X%-16d%-16d%-16d%-128s\r\n"; memset(szCaption,0,128); dwThreadId=GetCurrentThreadId(); if (IsWindow(msg->hwnd)) { GetWindowRect(msg->hwnd,&rc); GetWindowText(msg->hwnd,szCaption,128); szLog.Format(szFormat,msg->hwnd,msg->message,msg->wParam,msg->wParam,msg->pt.x,msg->pt.y,msg->time,rc.right,rc.bottom,dwThreadId,szCaption); } else { szLog.Format(szFormat,msg->hwnd,msg->message,msg->wParam,msg->wParam,msg->pt.x,msg->pt.y,msg->time,-1,-1,dwThreadId,szCaption); } time=CTime::GetCurrentTime(); szFileName=time.Format("%Y%m%d%H"); szFileName.Insert(0,"C:\\DM"); szFileName+=".log"; dwFlag=CFile::modeReadWrite|CFile::shareDenyRead; if (!PathFileExists(szFileName)) { dwFlag|=CFile::modeCreate; } CFile fileLog(szFileName,dwFlag); fileLog.SeekToEnd(); fileLog.Write(szLog,szLog.GetLength()); fileLog.Flush(); fileLog.Close(); //重新HOOK以便寫日志 VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,PAGE_READWRITE,&dwProtect); WriteProcessMemory(hRemoteProcess32,fpApiAddrW,btNewCodeW, 5, 0); VirtualProtectEx(hRemoteProcess32,fpApiAddrW,5,dwProtect,&dwProtect); return lr;} BOOL CMfcHookApiApp::InitInstance() { // TODO: Add your specialized code here and/or call the base class SetHookDispatchMessage(GetModuleHandle(NULL)); //SetHookMessageBox(GetModuleHandle(NULL)); CString szFormat=""; CString szLog=""; CTime time; CString szFileName=""; DWORD dwFlag=0; szFormat="%-16s%-16s%-16s%-16s%-16s%-16s%-16s%-16s%-16s%-16s%-128s\r\n"; szLog.Format(szFormat,"hwnd","message","wparam","lparam","mouse.x","mouse.y","message.time","client.width","client.height","thread id","window.caption"); time=CTime::GetCurrentTime(); szFileName=time.Format("%Y%m%d%H"); szFileName.Insert(0,"C:\\DM"); szFileName+=".log"; dwFlag=CFile::modeReadWrite|CFile::shareDenyRead; if (!PathFileExists(szFileName)) { dwFlag|=CFile::modeCreate; } CFile fileLog(szFileName,dwFlag); fileLog.SeekToEnd(); fileLog.Write(szLog,szLog.GetLength()); fileLog.Flush(); fileLog.Close(); return CWinApp::InitInstance();}5、新建一個測試程序:WIN32項目,取名為:DoWin32Test,代碼如下:// DoWin32Test.cpp : Defines the entry point for the application.// #include "stdafx.h"#include "resource.h" #define MAX_LOADSTRING 100 // Global Variables:HINSTANCE hInst; // current instanceTCHAR szTitle[MAX_LOADSTRING]; // The title bar textTCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text // Foward declarations of functions included in this code module:ATOM MyRegisterClass(HINSTANCE hInstance);BOOL InitInstance(HINSTANCE, int);LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){ // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_DOWIN32TEST, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_DOWIN32TEST); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam;} //// FUNCTION: MyRegisterClass()//// PURPOSE: Registers the window class.//// COMMENTS://// This function and its usage is only necessary if you want this code// to be compatible with Win32 systems prior to the 'RegisterClassEx'// function that was added to Windows 95. It is important to call this function// so that the application will get 'well formed' small icons associated// with it.//ATOM MyRegisterClass(HINSTANCE hInstance){ WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_DOWIN32TEST); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = (LPCSTR)IDC_DOWIN32TEST; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL); return RegisterClassEx(&wcex);} //// FUNCTION: InitInstance(HANDLE, int)//// PURPOSE: Saves instance handle and creates main window//// COMMENTS://// In this function, we save the instance handle in a global variable and// create and display the main program window.//BOOL InitInstance(HINSTANCE hInstance, int nCmdShow){ HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE;} //// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)//// PURPOSE: Processes messages for the main window.//// WM_COMMAND - process the application menu// WM_PAINT - Paint the main window// WM_DESTROY - post a quit message and return////LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){ int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; TCHAR szHello[MAX_LOADSTRING]; LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... RECT rt; GetClientRect(hWnd, &rt); DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0;} // Mesage handler for about box.LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam){ switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE;}最后,記得修改所有項目的生成目錄,令所有項目生成到一個目錄。我設置的方法是直接在默認生成目錄前加“..\”。祝你成功。

本文到此結束,希望對大家有所幫助。

免責聲明:本文由用戶上傳,如有侵權請聯系刪除!