Detours 是Microsoft开发一个库,下载地址http://research.microsoft.com/en-us/projects/detours/,它具有两方面的功能:
1 拦截x86机器上的任意的win32 API函数。
2 插入任意的数据段到PE文件中,修改DDL文件的导入表。
Detours库可以拦截任意的API调用,拦截代码是在动态运行时加载的。Detours替换目标API最前面的几条指令,使其无条件的跳转到用户提供的拦截函数。被替换的API函数的前几条指令被保存到trampoline 函数(就是内存中一个数据结构)中. trampoline保存了被替换的目标API的前几条指令和一个无条件转移,转移到目标API余下的指令。
当执行到目标API时,直接跳到用户提供的拦截函数中执行,这时拦截函数就可以执行自己的代码了。当然拦截函数可以直接返回,也可以调用trampoline函数,trampoline函数将调用被拦截的目标API,目标API调用结束后又会放回到拦截函数。下图就是Detours API拦截的逻辑流程:
Detours API 拦截原理:在汇编层改变目标API出口和入口的一些汇编指令。这里略过。
Detours API 拦截技术的使用方法
先贴一个例子:
- #include <windows.h>
- #include <detours.h>
- // Target pointer for the uninstrumented Sleep API.
- static VOID (WINAPI * TrueSleep)(DWORD dwMilliseconds) = Sleep;
- // Detour function that replaces the Sleep API.
- VOID WINAPI TimedSleep(DWORD dwMilliseconds)
- {
- TrueSleep(dwMilliseconds);
- }
- // DllMain function attaches and detaches the TimedSleep detour to the
- // Sleep target function. The Sleep target function is referred to
- // through the TrueSleep target pointer.
- BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
- {
- if (dwReason == DLL_PROCESS_ATTACH) {
- DetourTransactionBegin();
- DetourUpdateThread(GetCurrentThread());
- DetourAttach(&(PVOID&)TrueSleep, TimedSleep);
- DetourTransactionCommit();
- }
- else if (dwReason == DLL_PROCESS_DETACH) {
- DetourTransactionBegin();
- DetourUpdateThread(GetCurrentThread());
- DetourDetach(&(PVOID&)TrueSleep, TimedSleep);
- DetourTransactionCommit();
- }
- return TRUE;
- }
大家都知道,API HOOK都是写到DLL中的,Detours也不例外。这个例子是要hook Sleep函数,首先用TrueSleep这个函数指针保持真正的Sleep的地址。然定义一个自己的伪Sleep函数叫做TimedSleep,在这个函数中你可以做任意你想做的事情。在这个DLL被加载的时候,即DLL_PROCESS_ATTACH的时候,调用Detours函数DetourAttach(&(PVOID&)TrueSleep, TimedSleep)使用TimedSleep替换了TrueSleep。DetourTransactionBegin(),DetourUpdateThread()在Attach和Dettach之前都要调用这个函数,就是套路。最后在DLL_PROCESS_DETACH的时候解除对Sleep的hook。就是unhook。
Detours 修改PE文件的方法。本人没有用过,就不讲了。