项目简介
Microsoft Detours 是微软官方出品的 Windows API 拦截库。它通过重写目标函数前几个字节(即「Detour」技术),实现对任意 Win32 函数的 Hook。Detours 最初于 1999 年发布,2015 年开源(v3),2023 年发布重构后的 v4 版本,是 Windows 生态下最成熟的 API 拦截方案。
GitHub 仓库位于 github.com/microsoft/Detours,由微软官方维护,广泛应用于 Windows 平台的调试、性能分析和安全监控领域。
GitHub 数据
| 指标 | 数据 |
|---|---|
| Stars | 6,281 |
| License | MIT |
| 主要语言 | C / C++ |
| 最新版本 | v4.0.1(2026-05 更新) |
| 创建时间 | 2015 年(原始版 1999 年) |
核心功能
- API 拦截(Hook):对任意 Win32 函数进行 detour,可插入前置/后置回调
- DLL 注入:将 DLL 注入到目标进程并自动应用 detour
- 函数追踪:完整记录函数调用链路及参数
- 进程创建与修改:
DetourCreateProcessWithDll/DetourCreateProcessWithDlls可在进程启动时注入 - 二进制编辑:原地修改 PE 文件中的字节码
- 导入表编辑:修改 PE 导入表,实现模块级别的重定向
- 模块列举:枚举进程已加载模块信息
- 64 位支持:v4+ 完整支持 x64 架构的 Detour 操作
技术栈
| 层次 | 技术 |
|---|---|
| 核心实现 | C / C++ |
| 汇编指令 | x86 / x64 汇编(手动 trampoline 拼接) |
| 平台依赖 | Windows SDK |
安装与使用
方式一:从 GitHub 克隆并编译
git clone https://github.com/microsoft/Detours.git
cd Detours
nmake
方式二:通过 vcpkg 安装
vcpkg install detours
基本使用示例:
#include <detours.h>
// 原始函数指针
static int (WINAPI *Real_MessageBoxW)(HWND, LPCWSTR, LPCWSTR, UINT) = MessageBoxW;
// 自定义 Hook 函数
int WINAPI Hook_MessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType) {
lpText = L"Hooked!";
return Real_MessageBoxW(hWnd, lpText, lpCaption, uType);
}
// 开始 Hook
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)Real_MessageBoxW, Hook_MessageBoxW);
DetourTransactionCommit();
// 恢复 Hook
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)Real_MessageBoxW, Hook_MessageBoxW);
DetourTransactionCommit();
适用场景
- 软件调试与 Bug 定位
- 运行时性能分析(Profiling)
- 安全监控与异常检测
- 兼容性修复(旧软件在新系统运行)
- 反病毒引擎的 API 监控层
- 游戏 Mod / 外挂防御研究
竞品对比
| 竞品 | 特点 | 优势 | 局限 |
|---|---|---|---|
| MinHook | 轻量开源 Hook 库 | 代码精简易用 | 社区维护,非官方 |
| EasyHook | 托管 C# Hook 库 | .NET 友好 | 性能开销较大 |
| mhook | 轻量 Hook 库 | 代码量极少 | 已归档,不再维护 |
| NtHookEngine | 内核级 Hook 引擎 | 内核态能力 | 复杂度高,门槛高 |
核心优势:
- 微软官方开发与维护,质量有保障
- 从 Windows XP 到 Windows 11 全版本兼容
- 提供 5 种 Detour 事务类型(Attach / Detach / Set / Commit / Abort),精细控制 Hook 生命周期
- 数十年的生产环境验证,在 Microsoft Office、Windows 本身均有应用
参考资料
- GitHub 仓库:https://github.com/microsoft/Detours
- 微软文档:https://www.microsoft.com/en-us/research/project/detours/
- Detours v4 变更日志:https://github.com/microsoft/Detours/releases
文档信息
- 本文作者:zhupite
- 本文链接:https://zhupite.com/sec/detours.html
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)