[CPP] 用微软Detours拦截任意Win32任意API库

博客首页 » CPP 用微软Detours拦截任意Win32任意API库

发布于 28 Dec 2015 06:39
标签 blog
Microsoft开发了Detours库( http://research.microsoft.com/en-us/projects/detours/ )

它可以拦截x86机器上的任意的win32 API函数,也可以插入任意的数据段到PE文件中,修改DDL文件的导入表。

Detours库对于拦截任意的API调用,拦截代码是在动态运行时加载的。
它的原理是替换目标API最前面的几条指令,使其无条件的跳转到用户提供的拦截函数。被替换的API函数的前几条指令被保存到trampoline 函数(一个数据结构)中. trampoline保存了被替换的目标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文件的方法。


本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • CPP 用微软Detours拦截任意Win32任意API库

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment