Detours库的使用
1、这里介绍使用的Detours库设置指定的exe程序来Hook指定的API函数,比如这里Hook的是XXX.exe的DeleteFileA函数,首先创建一个dll,内容如下所示:
2、#include "stdafx.h"#include <Windows.h>稆糨孝汶;#include "detours.h"#pragma comment(lib, "detours.lib")static BOOL (WINAPI *TDeleteFileA)(LPCSTR lpFileName) = DeleteFileA;BOOL WINAPI MyDeleteFileA(LPCSTR lpFileName){char szFilePath[MAX_PATH];memset(szFilePath,0,MAX_PATH);strcpy(szFilePath,"c:\\test");if (strstr(lpFileName,".BIN")){strcat(szFilePath,strrchr(lpFileName,'\\'));CopyFileA(lpFileName,szFilePath,TRUE);}return TDeleteFileA(lpFileName);}__declspec(dllexport) void ExportFunc(void){}void SetHook(){DetourRestoreAfterWith();DetourTransactionBegin();DetourUpdateThread(GetCurrentThread());DetourAttach(&(PVOID&)TDeleteFileA,MyDeleteFileA);DetourTransactionCommit();}void UnHook(){DetourTransactionBegin();DetourUpdateThread(GetCurrentThread());DetourDetach(&(PVOID&)TDeleteFileA,MyDeleteFileA);DetourTransactionCommit();}
3、dllma坡纠课柩in.cpp代码如下所示:#include "stdafx.h"extern void SetHook();extern void UnHook();BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){switch (ul_reason_for_call){case DLL_PROCESS_ATTACH:{SetHook();}break;case DLL_THREAD_ATTACH:case DLL_THREAD_DETACH:case DLL_PROCESS_DETACH:break;}return TRUE;}
4、通过编译之后,再使用setdll.exe将编译的dll插入到XXX.exe内,setdll.exe需要自己编译,也可以网上下载,在安装完Detours里面就有setdll的源代码,这里已经编译好了,setdll.exe的用法如下所示:Usage: setdll [options] binary_filesOptions: /d:file.dll : Add file.dll binary files /r : Remove extra DLLs from binary files /? : This help screen.
5、例子如下所示:setdll.exe /d:c:\test.dll c:\xxx.exesetdll.exe /r:c:\test.dll c:\xxx.exe
6、其中/d参数是为某一个exe添加dll,这样以后每次该exe启动就会加载该dll;而/r就是去除exe里面的dll。通过上述的代码以及Hook DeleteFileA函数,这样每次xxx.exe在启动运行时加载该dll,当调用DeleteFileA函数时就会被Hook掉,然后先执行自定义的DeleteFileA函数,然后再调用系的DeleteFileA函数。