API HOOK(MessageBoxA)

笔记,非专业,只为自己看得懂,用语不专业。

API HOOK

HOOK 5字节。

新地址-老地址-5= HEX,     HEX是倒过来显示的。    

比如

00411082 > /E9 590B0000 JMP 00411BE0

 0B59

 

直接上代码。

// HookTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"



int MyMessageBoxA(
                  HWND hWdn,
                  LPCTSTR lpText,
                  LPCTSTR lpCaption,
                  UINT uType)
{
    char *txt="";
    _asm
    {
        RETN 2;
    }
    //Sleep();
    return 0;
}
//ULONG OldFunAddr;


void My_Hook(ULONG OldFunAddr,ULONG NewFunAddr,int CodeLen);

ULONG My_GetApiAddress(char *lpDllName,char *lpFunName);
int _tmain(int argc, _TCHAR* argv[])
{
    char *dllName="user32.dll";
    char *lpfunName="MessageBoxA";
    
    ULONG NewFuncAddr=(ULONG)MyMessageBoxA;

    MessageBoxA(NULL,"坐等HOOK","坐等HOOK title ",MB_YESNO);
    ULONG     OldFunAddr=My_GetApiAddress(dllName,lpfunName);
    if (OldFunAddr==NULL)
    {
        return NULL;
    }
    My_Hook(OldFunAddr,NewFuncAddr,5);

    MessageBoxA(NULL,"关闭句柄","坐等HOOK title ",MB_YESNO);

    //printf("1");
    //return 0;
}

BYTE hook_code[5] = {0xe9, 0, 0, 0, 0};//存放跳转到MyMessageBoxA的HEX
BYTE jmp_org_code[5] = {0xe9, 0, 0, 0, 0};//存放跳转到原起始地址后5字节的指令


BYTE m_lpJmpCode[5]={0x90,0x90,0x90,0x90,0x90};


void My_Hook(ULONG OldFunAddr,ULONG NewFunAddr,int CodeLen)
{
    //if (IsBadReadPtr((void *)OldFunAddr,CodeLen))
    //{

    //}    
    BYTE JmpMyCode[5]={0};

    ULONG m_oldFunAddr=OldFunAddr;
    ULONG m_NewFunAddr=NewFunAddr;

    INT m_CodeLen=CodeLen;
    
    DWORD lpflOldProtect =NULL; 
    HANDLE hprocss=GetCurrentProcess();

    VirtualProtectEx(hprocss,(LPVOID )m_oldFunAddr,5,PAGE_EXECUTE_READWRITE,&lpflOldProtect); //旧地址    
    *((ULONG*)(hook_code+1))=m_NewFunAddr-m_oldFunAddr-5;//计算HEX 地址。
    memcpy((LPVOID)m_oldFunAddr,hook_code,5);//用无类型指针 把 HEX拷贝过去。
    VirtualProtectEx(hprocss,(LPVOID)m_oldFunAddr,5,lpflOldProtect,&lpflOldProtect);//修改回来。

    CloseHandle(hprocss);
}



ULONG My_GetApiAddress(char *lpDllName,char *lpFunName)
{
    FARPROC fun;
    HMODULE dll;
    UINT m_oldFunAdd;

    dll =GetModuleHandleA(lpDllName);//获取DLL 模块句柄
    if (dll==0)
    {
        dll=LoadLibraryA(lpDllName);
        printf("LoadLibraryA \r\n");
    }
    if (dll==0)
    {
        return NULL;
    }
    fun=GetProcAddress(dll,lpFunName);
    m_oldFunAdd=(ULONG)fun;
    printf("GetProcAddress \r\n");
    printf("%s     Address:%d \r\n",lpFunName,m_oldFunAdd);
    
    return m_oldFunAdd;
}

刚开始学习C++ 语法方面很不熟悉。

 

然后

posted @ 2012-04-30 02:51  Red Cat  阅读(582)  评论(0编辑  收藏  举报

Copyright © 2022 LyShark Powered by .NET 6 on Kubernetes
Theme - LyTheme 1.0