如何使用Detour3.0来进行相应的API HOOK开发

来源:互联网 发布:腾讯云计算 编辑:程序博客网 时间:2024/05/29 14:21

1. 环境

    Detours3.0下载地址:http://download.csdn.net/detail/wangyong0921/4517308

    VS2008(以下例子都是在此环境下测试通过的)


2。编写测试程序

    使用VS2008新建一个MFC工具,这里只写重要的代码,后面会提供完整的事例下载!

  

// WinFormDlg.cpp : 实现文件//#include "stdafx.h"#include "WinForm.h"#include "WinFormDlg.h"#include "afxdialogex.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// 用于应用程序“关于”菜单项的 CAboutDlg 对话框class CAboutDlg : public CDialogEx{public:CAboutDlg();// 对话框数据enum { IDD = IDD_ABOUTBOX };protected:virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持// 实现protected:DECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD){}void CAboutDlg::DoDataExchange(CDataExchange* pDX){CDialogEx::DoDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)END_MESSAGE_MAP()// CWinFormDlg 对话框CWinFormDlg::CWinFormDlg(CWnd* pParent /*=NULL*/): CDialogEx(CWinFormDlg::IDD, pParent), m_username(_T("")), m_userpin(_T("")){m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CWinFormDlg::DoDataExchange(CDataExchange* pDX){CDialogEx::DoDataExchange(pDX);DDX_Text(pDX, IDC_EDIT1, m_username);DDX_Text(pDX, IDC_EDIT2, m_userpin);}BEGIN_MESSAGE_MAP(CWinFormDlg, CDialogEx)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDOK, &CWinFormDlg::OnBnClickedOk)END_MESSAGE_MAP()// CWinFormDlg 消息处理程序BOOL CWinFormDlg::OnInitDialog(){CDialogEx::OnInitDialog();// 将“关于...”菜单项添加到系统菜单中。// IDM_ABOUTBOX 必须在系统命令范围内。ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){BOOL bNameValid;CString strAboutMenu;bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);ASSERT(bNameValid);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动//  执行此操作SetIcon(m_hIcon, TRUE);// 设置大图标SetIcon(m_hIcon, FALSE);// 设置小图标// TODO: 在此添加额外的初始化代码return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE}void CWinFormDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialogEx::OnSysCommand(nID, lParam);}}// 如果向对话框添加最小化按钮,则需要下面的代码//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,//  这将由框架自动完成。void CWinFormDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // 用于绘制的设备上下文SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);// 使图标在工作区矩形中居中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;// 绘制图标dc.DrawIcon(x, y, m_hIcon);}else{CDialogEx::OnPaint();}}//当用户拖动最小化窗口时系统调用此函数取得光标//显示。HCURSOR CWinFormDlg::OnQueryDragIcon(){return static_cast<HCURSOR>(m_hIcon);}//登入系统void CWinFormDlg::OnBnClickedOk(){// TODO: 在此添加控件通知处理程序代码UpdateData(true);if (0 == m_username.Compare("wangyong")){if ( 0 == m_userpin.Compare("12345678")){MessageBoxA("登陆成功");}else{MessageBoxA("用户密码错误");return;}}else{MessageBoxA("用户名错误");return;}}

3。创建Hook Dll

// dllmain.cpp : 定义 DLL 应用程序的入口点。#include "stdafx.h"#include <windows.h>#include "detours.h"#pragma comment(lib, "detours.lib")//定义全局消息函数地址常量PVOID g_pOldMessageBoxA=NULL;PVOID g_pOldMessageBoxW=NULL;//定义消息处理函数typedef int (WINAPI *PfuncMessageBoxA)(HWND hWnd,LPCSTR lpText,LPCSTR lpCaption,UINT uType);typedef int (WINAPI *PfuncMessageBoxW)(HWND hWnd, LPCWSTR lpText,LPCWSTR lpCaption,UINT uType);//定义ANSCII的MessageBoxA的替代函数int WINAPI ZwNewMessageBoxA(HWND hWnd,LPCSTR lpText,LPCSTR lpCaption,UINT uType){return ((PfuncMessageBoxA)g_pOldMessageBoxA)(hWnd, "Hook This!","My hook",uType);}//定义UNICODE的MessageBoxW的替代函数int WINAPI ZwNewMessageBoxW(HWND hWnd, LPCWSTR lpText,LPCWSTR lpCaption,UINT uType){return ((PfuncMessageBoxW)g_pOldMessageBoxW)(hWnd,L"Hook This!",L"My hook",uType);}extern "C" _declspec(dllexport) BOOL APIENTRY SetHook(){DetourTransactionBegin();DetourUpdateThread(GetCurrentThread());//找到MEssageBoxA中的地址g_pOldMessageBoxA = DetourFindFunction("User32.dll","MessageBoxA");//找到MEssageBoxB中的地址g_pOldMessageBoxW = DetourFindFunction("User32.dll","MessageBoxW");//将替代函数连接DetourAttach(&g_pOldMessageBoxA,ZwNewMessageBoxA);//将替代函数连接DetourAttach(&g_pOldMessageBoxW,ZwNewMessageBoxW);LONG ret = DetourTransactionCommit();return ret == NO_ERROR;}extern "C" _declspec(dllexport) BOOL APIENTRY DropHook(){DetourTransactionBegin();DetourUpdateThread(GetCurrentThread());DetourDetach(&g_pOldMessageBoxA, ZwNewMessageBoxA);DetourDetach(&g_pOldMessageBoxW, ZwNewMessageBoxW);LONG ret=DetourTransactionCommit();return ret==NO_ERROR;}static HMODULE s_hDll;HMODULE WINAPI Detoured(){return s_hDll;}extern "C" BOOL APIENTRY DllMain( HMODULE hModule,  DWORD  ul_reason_for_call,  LPVOID lpReserved ){switch (ul_reason_for_call){case DLL_PROCESS_ATTACH: s_hDll = hModule; DisableThreadLibraryCalls(hModule); SetHook(); break;case DLL_THREAD_ATTACH: break;case DLL_THREAD_DETACH: break;case DLL_PROCESS_DETACH: DropHook(); break;}return TRUE;}

4. 设置EXE启动自动加载Hook Dll

// SetDLLToExe.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"//////////////////////////////////////////////////////////////////////////////////  Detours Test Program (setdll.cpp of setdll.exe)////  Microsoft Research Detours Package, Version 3.0.////  Copyright (c) Microsoft Corporation.  All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <shellapi.h>#include <detours.h>#pragma comment(lib, "detours.lib")////////////////////////////////////////////////////////////// Error Messages.//VOID AssertMessage(PCSTR szMsg, PCSTR szFile, DWORD nLine){    printf("ASSERT(%s) failed in %s, line %d.", szMsg, szFile, nLine);}#define ASSERT(x)   \do { if (!(x)) { AssertMessage(#x, __FILE__, __LINE__); DebugBreak(); }} while (0)    ;////////////////////////////////////////////////////////////////////////////////static BOOLEAN  s_fRemove = FALSE;static CHAR     s_szDllPath[MAX_PATH] = "";//////////////////////////////////////////////////////////////////////////////////  This code verifies that the named DLL has been configured correctly//  to be imported into the target process.  DLLs must export a function with//  ordinal #1 so that the import table touch-up magic works.//static BOOL CALLBACK ExportCallback(PVOID pContext,                                    ULONG nOrdinal,                                    PCHAR pszSymbol,                                    PVOID pbTarget){    (void)pContext;    (void)pbTarget;    (void)pszSymbol;    if (nOrdinal == 1) {        *((BOOL *)pContext) = TRUE;    }    return TRUE;}BOOL DoesDllExportOrdinal1(PCHAR pszDllPath){    HMODULE hDll = LoadLibraryEx(pszDllPath, NULL, DONT_RESOLVE_DLL_REFERENCES);    if (hDll == NULL) {        printf("setdll.exe: LoadLibraryEx(%s) failed with error %d.\n",               pszDllPath,               GetLastError());        return FALSE;    }    BOOL validFlag = FALSE;    DetourEnumerateExports(hDll, &validFlag, ExportCallback);    FreeLibrary(hDll);    return validFlag;}////////////////////////////////////////////////////////////////////////////////static BOOL CALLBACK ListBywayCallback(PVOID pContext,                                       PCHAR pszFile,                                       PCHAR *ppszOutFile){    (void)pContext;    *ppszOutFile = pszFile;    if (pszFile) {        printf("    %s\n", pszFile);    }    return TRUE;}static BOOL CALLBACK ListFileCallback(PVOID pContext,                                      PCHAR pszOrigFile,                                      PCHAR pszFile,                                      PCHAR *ppszOutFile){    (void)pContext;    *ppszOutFile = pszFile;    printf("    %s -> %s\n", pszOrigFile, pszFile);    return TRUE;}static BOOL CALLBACK AddBywayCallback(PVOID pContext,                                      PCHAR pszFile,                                      PCHAR *ppszOutFile){    PBOOL pbAddedDll = (PBOOL)pContext;    if (!pszFile && !*pbAddedDll) {                     // Add new byway.        *pbAddedDll = TRUE;        *ppszOutFile = s_szDllPath;    }    return TRUE;}BOOL SetFile(PCHAR pszPath){    BOOL bGood = TRUE;    HANDLE hOld = INVALID_HANDLE_VALUE;    HANDLE hNew = INVALID_HANDLE_VALUE;    PDETOUR_BINARY pBinary = NULL;    CHAR szOrg[MAX_PATH];    CHAR szNew[MAX_PATH];    CHAR szOld[MAX_PATH];    szOld[0] = '\0';    szNew[0] = '\0';#ifdef _CRT_INSECURE_DEPRECATE    strcpy_s(szOrg, sizeof(szOrg), pszPath);    strcpy_s(szNew, sizeof(szNew), szOrg);    strcat_s(szNew, sizeof(szNew), "#");    strcpy_s(szOld, sizeof(szOld), szOrg);    strcat_s(szOld, sizeof(szOld), "~");#else    strcpy(szOrg, pszPath);    strcpy(szNew, szOrg);    strcat(szNew, "#");    strcpy(szOld, szOrg);    strcat(szOld, "~");#endif    printf("  %s:\n", pszPath);    hOld = CreateFile(szOrg,                      GENERIC_READ,                      FILE_SHARE_READ,                      NULL,                      OPEN_EXISTING,                      FILE_ATTRIBUTE_NORMAL,                      NULL);    if (hOld == INVALID_HANDLE_VALUE) {        printf("Couldn't open input file: %s, error: %d\n",               szOrg, GetLastError());        bGood = FALSE;        goto end;    }    hNew = CreateFile(szNew,                      GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS,                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);    if (hNew == INVALID_HANDLE_VALUE) {        printf("Couldn't open output file: %s, error: %d\n",               szNew, GetLastError());        bGood = FALSE;        goto end;    }    if ((pBinary = DetourBinaryOpen(hOld)) == NULL) {        printf("DetourBinaryOpen failed: %d\n", GetLastError());        goto end;    }    if (hOld != INVALID_HANDLE_VALUE) {        CloseHandle(hOld);        hOld = INVALID_HANDLE_VALUE;    }    {        BOOL bAddedDll = FALSE;        DetourBinaryResetImports(pBinary);        if (!s_fRemove) {            if (!DetourBinaryEditImports(pBinary,                                         &bAddedDll,                                         AddBywayCallback, NULL, NULL, NULL)) {                printf("DetourBinaryEditImports failed: %d\n", GetLastError());            }        }        if (!DetourBinaryEditImports(pBinary, NULL,                                     ListBywayCallback, ListFileCallback,                                     NULL, NULL)) {            printf("DetourBinaryEditImports failed: %d\n", GetLastError());        }        if (!DetourBinaryWrite(pBinary, hNew)) {            printf("DetourBinaryWrite failed: %d\n", GetLastError());            bGood = FALSE;        }        DetourBinaryClose(pBinary);        pBinary = NULL;        if (hNew != INVALID_HANDLE_VALUE) {            CloseHandle(hNew);            hNew = INVALID_HANDLE_VALUE;        }        if (bGood) {            if (!DeleteFile(szOld)) {                DWORD dwError = GetLastError();                if (dwError != ERROR_FILE_NOT_FOUND) {                    printf("Warning: Couldn't delete %s: %d\n", szOld, dwError);                    bGood = FALSE;                }            }            if (!MoveFile(szOrg, szOld)) {                printf("Error: Couldn't back up %s to %s: %d\n",                       szOrg, szOld, GetLastError());                bGood = FALSE;            }            if (!MoveFile(szNew, szOrg)) {                printf("Error: Couldn't install %s as %s: %d\n",                       szNew, szOrg, GetLastError());                bGood = FALSE;            }        }        DeleteFile(szNew);    }  end:    if (pBinary) {        DetourBinaryClose(pBinary);        pBinary = NULL;    }    if (hNew != INVALID_HANDLE_VALUE) {        CloseHandle(hNew);        hNew = INVALID_HANDLE_VALUE;    }    if (hOld != INVALID_HANDLE_VALUE) {        CloseHandle(hOld);        hOld = INVALID_HANDLE_VALUE;    }    return bGood;}////////////////////////////////////////////////////////////////////////////////void PrintUsage(void){    printf("Usage:\n"           "    setdll [options] binary_files\n"           "Options:\n"           "    /d:file.dll  : Add file.dll binary files\n"           "    /r           : Remove extra DLLs from binary files\n"           "    /?           : This help screen.\n");}//////////////////////////////////////////////////////////////////////// main.//int CDECL main(int argc, char **argv){    BOOL fNeedHelp = FALSE;    PCHAR pszFilePart = NULL;    int arg = 1;    for (; arg < argc; arg++) {        if (argv[arg][0] == '-' || argv[arg][0] == '/') {            CHAR *argn = argv[arg] + 1;            CHAR *argp = argn;            while (*argp && *argp != ':' && *argp != '=')                argp++;            if (*argp == ':' || *argp == '=')                *argp++ = '\0';            switch (argn[0]) {              case 'd':                                 // Set DLL              case 'D':                if ((strchr(argp, ':') != NULL || strchr(argp, '\\') != NULL) &&                    GetFullPathName(argp, sizeof(s_szDllPath), s_szDllPath, &pszFilePart)) {                }                else {#ifdef _CRT_INSECURE_DEPRECATE                    sprintf_s(s_szDllPath, sizeof(s_szDllPath), "%s", argp);#else                    sprintf(s_szDllPath, "%s", argp);#endif                }                break;              case 'r':                                 // Remove extra set DLLs.              case 'R':                s_fRemove = TRUE;                break;              case '?':                                 // Help                fNeedHelp = TRUE;                break;              default:                fNeedHelp = TRUE;                printf("Bad argument: %s:%s\n", argn, argp);                break;            }        }    }    if (argc == 1) {        fNeedHelp = TRUE;    }    if (!s_fRemove && s_szDllPath[0] == 0) {        fNeedHelp = TRUE;    }    if (fNeedHelp) {        PrintUsage();        return 1;    }    if (s_fRemove) {        printf("Removing extra DLLs from binary files.\n");    }    else {        if (!DoesDllExportOrdinal1(s_szDllPath)) {            printf("Error: %hs does not export function with ordinal #1.\n",                   s_szDllPath);            return 2;        }        printf("Adding %hs to binary files.\n", s_szDllPath);    }    for (arg = 1; arg < argc; arg++) {        if (argv[arg][0] != '-' && argv[arg][0] != '/') {            SetFile(argv[arg]);        }    }    return 0;}// End of File

5. 至此全部完成

6。完整事例下载地址

      http://download.csdn.net/detail/wangyong0921/4517355

原创粉丝点击