请教关于APIHOOK的初级问题(新手)
请各位帮帮忙:
我从别的地方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?