我已经成功地从托管代码中挂钩。但是,我通过将非托管 DLL 注入远程进程并让它重写 DllMain 中的导入表来做到这一点。您可能需要考虑这种方法。
这是我的挂钩功能:
//structure of a function to hook
struct HookedFunction {
public:
LPTSTR moduleName;
LPTSTR functionName;
LPVOID newfunc;
LPVOID* oldfunc;
};
BOOL Hook(HMODULE Module, struct HookedFunction Function) {
//parse dos header
IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module;
if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) return 0; //not a dos program
//parse nt header
IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)(dos_header->e_lfanew + (SIZE_T)Module);
if (nt_header->Signature != IMAGE_NT_SIGNATURE) return 0; //not a windows program
//optional header (pretty much not optional)
IMAGE_OPTIONAL_HEADER optional_header = nt_header->OptionalHeader;
if (optional_header.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0; //no optional header
IMAGE_IMPORT_DESCRIPTOR* idt_address = (IMAGE_IMPORT_DESCRIPTOR*)(optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + (SIZE_T)Module);
if (!optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size) return 0; //no import table
//enumerate the import dlls
BOOL hooked = false;
for(IMAGE_IMPORT_DESCRIPTOR* i = idt_address; i->Name != NULL; i++)
//check the import filename
if (!_stricmp(Function.moduleName, (char*)(i->Name + (SIZE_T)Module)))
//enumerate imported functions for this dll
for (int j = 0; *(j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module)) != NULL; j++)
//check if the function matches the function we are looking for
if (!_stricmp(Function.functionName, (char*)(*(j + (SIZE_T*)(i->OriginalFirstThunk + (SIZE_T)Module)) + (SIZE_T)Module + 2) )) {
//replace the function
LPVOID* memloc = j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module);
if (*memloc != Function.newfunc) { //not already hooked
DWORD oldrights;
DWORD newrights = PAGE_READWRITE;
VirtualProtect(memloc, sizeof(LPVOID), newrights, &oldrights);
if (Function.oldfunc && !*Function.oldfunc)
*Function.oldfunc = *memloc;
*memloc = Function.newfunc;
VirtualProtect(memloc, sizeof(LPVOID), oldrights, &newrights);
}
hooked = true;
}
return hooked;
}