图解Detours实例

一 MFC程序中Hook MessageBox

新建如下的两个工程;

主对话框代码:

// HookMessageBookDlg.cpp : implementation file
//

#include "stdafx.h"
#include "HookMessageBook.h"
#include "HookMessageBookDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CHookMessageBookDlg dialog

CHookMessageBookDlg::CHookMessageBookDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CHookMessageBookDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CHookMessageBookDlg)
	m_strDllPath = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CHookMessageBookDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CHookMessageBookDlg)
	DDX_Control(pDX, IDC_BTN_LOAD, m_btnLoad);
	DDX_Text(pDX, IDC_EDIT_DLL, m_strDllPath);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CHookMessageBookDlg, CDialog)
	//{{AFX_MSG_MAP(CHookMessageBookDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_LOAD, OnBtnLoad)
	ON_BN_CLICKED(IDC_BUTTON_OPEN_DLL, OnButtonOpenDll)
	ON_BN_CLICKED(IDC_BTN_UNLOAD, OnBtnUnload)
	ON_BN_CLICKED(IDC_BTN_MSG, OnBtnMsg)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CHookMessageBookDlg message handlers

BOOL CHookMessageBookDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	GetDlgItem(IDC_BTN_LOAD)->EnableWindow(TRUE);
	GetDlgItem(IDC_BTN_UNLOAD)->EnableWindow(FALSE);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CHookMessageBookDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CHookMessageBookDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CRect   rect;  
		CPaintDC   dc(this);  
		GetClientRect(rect);  
		dc.FillSolidRect(rect,RGB(0,255,0)); 
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CHookMessageBookDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CHookMessageBookDlg::OnBtnLoad() 
{
	// TODO: Add your control notification handler code here
	hModule = LoadLibraryA(m_strDllPath);
	if (hModule == NULL)
	{
		CString str_err = "";
		str_err.Format("加载DLL失败,错误号为:%d",GetLastError());
		MessageBox(str_err);
	}
	else
	{
		GetDlgItem(IDC_BTN_LOAD)->EnableWindow(FALSE);
		GetDlgItem(IDC_BTN_UNLOAD)->EnableWindow(TRUE);
	}
}

void CHookMessageBookDlg::OnButtonOpenDll() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	CString lpzFilter = "Dll(*.dll)|*.dll";
	CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,lpzFilter);
    
	if (dlg.DoModal()==IDOK)
	{
		m_strDllPath = dlg.GetPathName();
		UpdateData(FALSE);
	}
}

void CHookMessageBookDlg::OnBtnUnload() 
{
	// TODO: Add your control notification handler code here
	FreeLibrary(hModule);
	GetDlgItem(IDC_BTN_LOAD)->EnableWindow(TRUE);
	GetDlgItem(IDC_BTN_UNLOAD)->EnableWindow(FALSE);
}

void CHookMessageBookDlg::OnBtnMsg() 
{
	// TODO: Add your control notification handler code here
	MessageBox (m_strDllPath);
}

dll代码:

// HookDll.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include <windows.h>
#include <detours.h>



static int (WINAPI* TrueMessageBox)(HWND hWnd , LPCSTR lpText, LPCSTR lpCaption, UINT uType)=MessageBoxA; 


int WINAPI NEW_MessageBoxA(HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType)  
{  
	
	//修改输入参数,调用原函数  
	int ret=TrueMessageBox(hWnd,"该函数已经被Hook","[测试]",uType);  
	return ret;  
}  

VOID Hook()  
{  
	DetourRestoreAfterWith();  
	DetourTransactionBegin();  
	DetourUpdateThread(GetCurrentThread());  
	
	//这里可以连续多次调用DetourAttach,表明HOOK多个函数  
	DetourAttach(&(PVOID&)TrueMessageBox,NEW_MessageBoxA);  
	
	DetourTransactionCommit();  
	OutputDebugString("Hook Success!\n");
}  

VOID UnHook()  
{  
	DetourTransactionBegin();  
	DetourUpdateThread(GetCurrentThread());  
	
	//这里可以连续多次调用DetourDetach,表明撤销多个函数HOOK  
	DetourDetach(&(PVOID&)TrueMessageBox,NEW_MessageBoxA);  
	
	DetourTransactionCommit();  
	OutputDebugString("UnHook Success!\n");	
}

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
	if (ul_reason_for_call == DLL_PROCESS_ATTACH)
	{
		OutputDebugString("DLL_PROCESS_ATTACH\n");
		Hook();
	}
	else if (ul_reason_for_call == DLL_PROCESS_DETACH)
	{
		OutputDebugString("DLL_PROCESS_DETACH\n");
		UnHook();
	}
    return TRUE;
}


 
 
<pre name="code" class="cpp">DLL_PROCESS_ATTACH
 当dll映射到进程地址空间时hook,当dll从进程地址空间解除映射时unhook; 
 
图解Detours实例_第1张图片

库模块中加入detour的lib;

图解Detours实例_第2张图片


运行程序并且用dbgview观察;


图解Detours实例_第3张图片


图解Detours实例_第4张图片

代码中用OutputDebugString输出的内容,可在dbgview中显示;

图解Detours实例_第5张图片

需要在dbgview的capture菜单选中如下项;

图解Detours实例_第6张图片



Detour 参考

http://blog.csdn.net/bcbobo21cn/article/details/51331093

工程和dbgview下载:

http://pan.baidu.com/s/1o7OEMc6

DetourHook.rar


你可能感兴趣的:(api,mfc,hook,detour)