Gopi Krishna Komanduri wrote:
> Hi,
> I wrote a piece of code for API hooking.. but I am getting access violation
> error.. Please correct me where I went wrong.
>
>
> #include<stdio.h>
> #include<tchar.h>
> #include<windows.h>
> typedef void (*name)(DWORD );
> void printname(DWORD i)
> {
> printf("\n i is %d",i);
> printf("\n Gopi");
> }
> int main()
> {
> HMODULE hmod;
> IMAGE_DOS_HEADER *DosHeader;
> IMAGE_NT_HEADERS32 *NTHeaders;
> IMAGE_OPTIONAL_HEADER32 OH;
> IMAGE_IMPORT_DESCRIPTOR *ImportDesc,*ImportDesc_Temp;
> char *tmp;
> char *FuncName;
> DWORD *FuncAddr;
> int ret=-10;
> hmod=LoadLibrary(_T("C:\\Documents and Settings\\PERSONAL\\My
> Documents\\Visual Studio 2005\\Projects\\SumDll\\SumDll\\debug\\SumDll.dll"));
> DosHeader=(IMAGE_DOS_HEADER *)hmod;
> NTHeaders=(IMAGE_NT_HEADERS32 *)(DosHeader->e_lfanew+(BYTE *)DosHeader);
> OH=NTHeaders->OptionalHeader;
> DWORD IMageBase=OH.ImageBase;
> ImportDesc=(IMAGE_IMPORT_DESCRIPTOR
> *)(OH.DataDirectory[1].VirtualAddress+(BYTE *)DosHeader);
> ImportDesc_Temp=ImportDesc;
> DWORD oldprotect,oldprotect_1;
> while(ImportDesc_Temp->Name)
> {
> tmp=(char *)(ImportDesc_Temp->Name+(BYTE *)DosHeader);
> printf("\n The name of the Dll is %s",tmp);
> IMAGE_THUNK_DATA32 *ThunkData=(IMAGE_THUNK_DATA32
> *)(ImportDesc_Temp->OriginalFirstThunk+(BYTE *)DosHeader);
> IMAGE_THUNK_DATA32 *FirstThunkData=(IMAGE_THUNK_DATA32
> *)(ImportDesc_Temp->FirstThunk+(BYTE *)DosHeader);
> int x=0;
> while(ThunkData->u1.Function)
> {
> FuncName=(char *)((BYTE *)DosHeader+ThunkData->u1.AddressOfData+2);
> if(!stricmp(FuncName,"Sleep"))
> {
> FuncAddr = (DWORD *)(FirstThunkData->u1.Function);
> ret = VirtualProtect(FuncAddr,4,PAGE_READWRITE,&oldprotect);
> *FuncAddr=(DWORD )printname;
> ret = VirtualProtect(FuncAddr,4,PAGE_EXECUTE,&oldprotect_1);
> }
> printf("\n The function name is %s",FuncName);
> ThunkData++;
> FirstThunkData++;
> }
> ImportDesc_Temp++;
> x++;
> }
> Sleep(1000); /// getting access violation error here
> return 1;
> }
I'm one of the few people here who have actual experience with API
hooking and you are better off using a toolkit for your first (and
hopefully, from my perspective, last) adventure with API hooking. If
you must use API hooking, start with something like Detours.
However, you are WAY better off not fiddling with API hooking in the
first place. It is dangerous and almost always results in unstable
applications (as you are already seeing). You are also using
VirtualProtect() incorrectly. It is a low-level function that expects
page boundary addresses and sizes.
Hooking kernel32.dll is not a good "get your feet wet" exercise.
--
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197
*NEW* MyTaskFocus 1.1
Get on task. Stay on task.
http://www.CubicleSoft.com/MyTaskFocus/