HookApi.h

#pragma once

#include <detours.h>
#pragma comment(lib, "detours.lib")

class CHookApi
{
public:
	CHookApi();
	~CHookApi();
public:
	void Hook();
	void UnHook();
};

HookApi.cpp

#include "stdafx.h"
#include "HookApi.h"

//---------------------------------------------
CStringA ToHex(const char* buf, int len)
{
	CStringA csText,csTmp;
	for (int i = 0; i < len;i++)
	{
		csTmp.Format("%02X ", buf[i] & 0xFF);
		csText += csTmp;
	}

	return csText;
}

#include <Winsock2.h>
#pragma comment(lib, "Ws2_32.lib")

int (WINAPI *pSend)(SOCKET s, const char* buf, int len, int flags) = send;
int (WINAPI *pRecv)(SOCKET s, char* buf, int len, int flags) = recv;

int WINAPI MySend(SOCKET s, const char* buf, int len, int flags)
{
	FILE* pSendLogFile = NULL;
	fopen_s(&pSendLogFile, "C:\\SendLog.txt", "a+");
	fprintf(pSendLogFile, "%d:%s\n", s,(LPCSTR)ToHex(buf, len));
	fclose(pSendLogFile);
	return pSend(s, buf, len, flags);
}

int WINAPI MyRecv(SOCKET s, char* buf, int len, int flags)
{
	FILE* pRecvLogFile = NULL;
	fopen_s(&pRecvLogFile, "C:\\RecvLog.txt", "a+");
	fprintf(pRecvLogFile, "%d:%s\n", s,(LPCSTR)ToHex(buf, len));
	fclose(pRecvLogFile);
	return pRecv(s, buf, len, flags);
}
//---------------------------------------------

CHookApi::CHookApi()
{
}

CHookApi::~CHookApi()
{
}

void CHookApi::Hook()
{
	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourAttach(&(PVOID&)pSend, MySend);
	if (DetourTransactionCommit() == NO_ERROR)
	{
		OutputDebugString(L"send() detoured successfully");
	}

	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourAttach(&(PVOID&)pRecv, MyRecv);
	if (DetourTransactionCommit() == NO_ERROR)
	{
		OutputDebugString(L"recv() detoured successfully");
	}
}

void CHookApi::UnHook()
{
	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourDetach(&(PVOID&)pSend, MySend);
	DetourTransactionCommit();

	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourDetach(&(PVOID&)pRecv, MyRecv);
	DetourTransactionCommit();
}

使用方法:

// 在 DllMain 中
#include "HookApi.h"
CHookApi hook;

// DLL_PROCESS_ATTACH
hook.Hook();

// DLL_PROCESS_DETACH
hook.UnHook();

将这些代码所在的DLL注入到指定进程即可。


本文链接地址: API HOOK库Detours的基本使用方法
http://qingfengju.com/index.asp?id=371

分类:Win32/C++ 查看次数:5270 发布时间:2014-5-6 18:22:27