请教关于APIHOOK的初级问题(新手)

quaddamage 2003-02-21 12:04:27
请各位帮帮忙:
我从别的地方copy了一段代码想实现简单的APIHOOK,就是在运行notepad.exe时hook MessageBoxW这个API,使它指向ExitProcess,但是这个程序在运行时总是报Access voilation。在单步跟踪时停在了ImageDirectoryEntryToData()
程序代码很短,就包括一个main()和ReplaceIATEntryInOneMod()两个函数,如下:

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

const BYTE cPushOpCode = 0x68;

void ReplaceIATEntryInOneMod(PCSTR pszCalleeModName,
PROC pfnCurrent, PROC pfnNew, HMODULE hmodCaller) {

// Get the address of the module's import section
ULONG ulSize;
PIMAGE_IMPORT_DESCRIPTOR pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)
ImageDirectoryEntryToData(hmodCaller, TRUE,
IMAGE_DIRECTORY_ENTRY_IMPORT, &ulSize);

if (pImportDesc == NULL)
return; // This module has no import section


// Find the import descriptor containing references to callee's functions
for (; pImportDesc->Name; pImportDesc++) {
PSTR pszModName = (PSTR) ((PBYTE) hmodCaller + pImportDesc->Name);
if (lstrcmpiA(pszModName, pszCalleeModName) == 0)
break; // Found
}

if (pImportDesc->Name == 0)
return; // This module doesn't import any functions from this callee

// Get caller's import address table (IAT) for the callee's functions
PIMAGE_THUNK_DATA pThunk = (PIMAGE_THUNK_DATA)
((PBYTE) hmodCaller + pImportDesc->FirstThunk);

// Replace current function address with new function address
for (; pThunk->u1.Function; pThunk++) {

// Get the address of the function address
PROC* ppfn = (PROC*) &pThunk->u1.Function;

// Is this the function we're looking for?
BOOL fFound = (*ppfn == pfnCurrent);

if (fFound) {
// The addresses match, change the import section address
WriteProcessMemory(GetCurrentProcess(), ppfn, &pfnNew,
sizeof(pfnNew), NULL);
return; // We did it, get out
}
}

// If we get to here, the function is not in the caller's import section
}

void main(){
PROC pfnOrig=GetProcAddress(GetModuleHandle("Kernel32"),"MessageBoxW");
HMODULE hmodCaller=GetModuleHandle("notepad.exe");
PROC MyMessageBoxW=GetProcAddress(GetModuleHandle("Kernel32"),"ExitProcess");
ReplaceIATEntryInOneMod(
"Kernel32,dll",
pfnOrig,
MyMessageBoxW,
hmodCaller);

}

还有一个问题就是字调用WriteProcessMemory时,我怎么知道当前的进程是不是notepad.exe?

...全文
37 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
demetry 2003-02-21
  • 打赏
  • 举报
回复
第二个问题:

你要先枚举进程的ID,因为ID是唯一的,而进程句柄则不一定。然后根据ID判断当前进程是不是notepad.exe

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧