I am working on a basic little program that uses DLL Injection to hook API functions. The problem I am having is that the program the DLL is injected into reports this error:
---------------------------
Trainer_Template.exe
---------------------------
An exception (C0000005) occurred during DllEntryPoint or DllMain in module:
C:\Program Files\Borland\CBuilder6\Projects\API_Hook\DLL\Bin\ API_Hook_DLL.dll
---------------------------
OK
---------------------------
whenever I try to access a member of the IAT. C0000005 being an invalid access error.
The function with the offending code:
Code:
bool HookFunctionInModule(char* szImportedDll, PROC lpfnCurrent,
PROC lpfnNew, HMODULE hMod)
{
//Get the import directory for
//the specified module.
PIMAGE_DOS_HEADER pdhDosHeader =
(PIMAGE_DOS_HEADER)hMod;
if (pdhDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
return false;
PIMAGE_NT_HEADERS pnhNTHeader =
(PIMAGE_NT_HEADERS)(pdhDosHeader->e_lfanew);
if (pnhNTHeader->Signature != IMAGE_NT_SIGNATURE)
return false;
PIMAGE_IMPORT_DESCRIPTOR iidDesc =
(PIMAGE_IMPORT_DESCRIPTOR)
(
(long)hMod + pnhNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress);
if (iidDesc == NULL)
return false;
while (iidDesc->Name)
{
MessageBox(NULL, "HI", "", MB_OK);
char* szName = (iidDesc->Name + (unsigned long)hMod);
MessageBox(NULL, szName, "", MB_OK);
//If the imported dll is the
//right name look for the right
//imported function.
if (lstrcmpi(szName, szImportedDll) == 0)
{
PIMAGE_THUNK_DATA itdThunk =
(PIMAGE_THUNK_DATA)((PBYTE)
hMod + iidDesc->FirstThunk);
while(itdThunk->u1.Function)
{
if ((PROC)itdThunk->u1.Function == lpfnCurrent)
{
//Once we find the right function
//overwrite the address of the
//function with the address
//of our own.
unsigned long* lngOldProtect;
VirtualProtect((void*)itdThunk->u1.Function,
sizeof(long), PAGE_EXECUTE_READWRITE,
lngOldProtect);
WriteProcessMemory(GetCurrentProcess(),
(void*)itdThunk->u1.Function,
lpfnNew, sizeof(long), NULL);
return true;
}
}
}
else
{
MessageBox(NULL, "HIAA", "", MB_OK);
iidDesc++;
}
}
return false;
}
The line it crashes on is "char* szName = (iidDesc->Name + (unsigned long)hMod);".
The thing that really confuses me here is if I try to use ImageDirectoryEntryToData at any time to try to get the IAT it gives that same error right away.
Any ideas what the problem is or how to fix it? I have linked to the entire project below, both the injector and the dll, if it helps.
The whole package.
Thank you for any assistance.