彩钢板安装方法:Detours的简单使用说明

来源:百度文库 编辑:中财网 时间:2024/04/28 02:07:18
Detours是微软开发的一个函数库(源代码可在http://research.microsoft.com/sn/detours 免费获得), 用于修改运行中的程序在内存中的影像。具体用途是: 拦截Win32 API调用,将其引导到自己的子程序,从而实现Win32 API的定制。
Detours的原理 ----1. Win32进程的内存管理 ----众所周知,Windows NT实现了虚拟存储器,每一个Win32 进程拥有4GB的虚存空间, 关于Win32进程的虚存结构及其操作的具体细节请参阅 Win32 API手册, 以下仅指出与Detours相关的几点: 
进程要执行的指令也放在虚存空间中。 可以使用QueryProtectEx函数把存放指令的页面的权限更改为可读可写可执行,再改写其内容,从而修改正在运行的程序。 可以使用VirtualAllocEx从一个进程为另一正运行的进程分配虚存,再使用 QueryProtectEx函数把页面的权限更改为可读可写可执行,并把要执行的指令以二进制机器码的形式写入,从而为一个正在运行的进程注入任意的代码。----2. 拦截Win32 API的原理 
----Detours定义了三个概念: 
Target函数:要拦截的函数,通常为Windows的API。 Trampoline函数:Target函数的复制品。因为Detours将会改写Target函数,所以先把 Target函数复制保存好,一方面仍然保存Target函数的过程调用语义,另一方面便于以后的恢复。 Detours 函数:用来替代Target函数的函数。---- Detours在Target函数的开头加入JMP Address_of_ Detour_ Function指令(共5个字节)把对Target函数的调用引导到自己的Detours函数, 把 Target函数的开头的5个字节加上JMP Address_of_ Target _ Function+5作为Trampoline 函数。例子如下: 
    拦截前:Target _ Function: ;Target函数入口,      以下为假想的常见的子程序入口代码 push ebp mov ebp, esp push eax push ebx Trampoline: ;以下是Target函数的继续部分        ......
    拦截后:Target _ Function: jmp Detour_Function  Trampoline: ;以下是Target函数的继续部分 ......
 Trampoline_Function: ; Trampoline函数入口, 开头的5个字节与          Target函数相同 push ebp mov ebp, esp push eax push ebx ;跳回去继续执行Target函数 jmp Target_Function+5


使用Detours需要有detours.lib和detours.h,这个可以从网上下载
具体使用例子:用TP_PathFileExists来拦截系统消息PathFileExists
DETOUR_TRAMPOLINE(BOOL  WINAPI Detour_PathFileExists  (LPCTSTR pszPath), PathFileExists);
extern "C" BOOL  WINAPI TP_PathFileExists  (LPCTSTR pszPath) { if( Detour_PathFileExists( pszPath)) return TRUE; if(lstrlen(pszPath) <1) return FALSE; if(pszPath[0] == '\\') { HANDLE  hFile;   hFile = CreateFile(pszPath ,GENERIC_READ ,FILE_SHARE_READ|FILE_SHARE_WRITE ,NULL ,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL ,NULL);
if(INVALID_HANDLE_VALUE == hFile) return FALSE; else { CloseHandle(hFile); return TRUE; } } else { WIN32_FIND_DATA lpFindFileData; HANDLE hFind = FindFirstFile( pszPath,&lpFindFileData); if( INVALID_HANDLE_VALUE == hFind) return FALSE; else {FindClose(hFind);return TRUE;} } }

BOOL TP_InitSysHook(){ DWORD dwVersion = GetVersion(); if(dwVersion < 0x80000000) { DetourFunctionWithTrampoline((PBYTE)Detour_PathFileExists,    (PBYTE)TP_PathFileExists); return TRUE; } return TRUE;}
BOOL TP_ReleaseSysHook(){ DWORD dwVersion = GetVersion(); if(dwVersion < 0x80000000) { DetourRemove((PBYTE)Detour_PathFileExists,     (PBYTE)TP_PathFileExists); return TRUE; } return TRUE;}