使用detours实现劫持

第一步:下载detours3.0,安装detours
第二步:构建库文件,nmake编译
这里写图片描述
第三步:包含库文件和头文件
#include “detours.h” //载入头文件
#pragma comment(lib,”detours.lib”) //表明要使用静态库
第四步:定义旧函数指针指向原来的函数
static int (oldsystem)(const char _Command)=system;
第五步:声明一个和原函数参数相同的新函数
int newsystemA( char * _Command)
{
char *p=strstr(_Command,”tasklist”);
if(p==NULL)
{
oldsystem(_Command);
}
else
{
printf(“%s”,_Command); //找到了,禁止执行
return 0;
}
return 0;
}

第六步:开始拦截
//开始拦截
void Hook()
{

DetourRestoreAfterWith();//恢复原来状态,
DetourTransactionBegin();//拦截开始
DetourUpdateThread(GetCurrentThread());//刷新当前线程
//这里可以连续多次调用DetourAttach,表明HOOK多个函数

DetourAttach((void **)&oldsystem, newsystemA);//实现函数拦截

DetourTransactionCommit();//拦截生效

}
第七步:取消拦截
//取消拦截
void UnHook()
{

DetourTransactionBegin();//拦截开始
DetourUpdateThread(GetCurrentThread());//刷新当前线程
//这里可以连续多次调用DetourDetach,表明撤销多个函数HOOK
DetourDetach((void **)&oldsystem, newsystemA); //撤销拦截函数
DetourTransactionCommit();//拦截生效

}

第八步:main函数运行,大功告成
void main()
{
system(“calc”);
Hook();
system(“calc”);
system(“tasklist”);
//UnHook();
getchar();
}

注意:一定要在realse模式,而不是在debug模式下运行,不然得不到想要的结果。

原文地址:https://www.cnblogs.com/jjx2013/p/6223769.html