Detours简介

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 拦截技术的使用方法

先贴一个例子:

  1. #include <windows.h> 
  2. #include <detours.h> 
  3.  
  4. // Target pointer for the uninstrumented Sleep API. 
  5. static VOID (WINAPI * TrueSleep)(DWORD dwMilliseconds) = Sleep; 
  6. // Detour function that replaces the Sleep API. 
  7. VOID WINAPI TimedSleep(DWORD dwMilliseconds) 
  8.     TrueSleep(dwMilliseconds); 
  9. // DllMain function attaches and detaches the TimedSleep detour to the 
  10. // Sleep target function.  The Sleep target function is referred to 
  11. // through the TrueSleep target pointer. 
  12. BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved) 
  13.     if (dwReason == DLL_PROCESS_ATTACH) { 
  14.         DetourTransactionBegin(); 
  15.         DetourUpdateThread(GetCurrentThread()); 
  16.         DetourAttach(&(PVOID&)TrueSleep, TimedSleep); 
  17.         DetourTransactionCommit(); 
  18.     } 
  19.     else if (dwReason == DLL_PROCESS_DETACH) { 
  20.         DetourTransactionBegin(); 
  21.         DetourUpdateThread(GetCurrentThread()); 
  22.         DetourDetach(&(PVOID&)TrueSleep, TimedSleep); 
  23.         DetourTransactionCommit(); 
  24.     } 
  25.     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文件的方法。本人没有用过,就不讲了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值