Hooking import table

 

f.c

#include <windows.h>

int main()

{

MessageBox(0,"hi", "hi", 0);

MessageBox(0,"bye", "hi", 0);

}

 

a.c

#include <windows.h>

void main()

{

HINSTANCE hDll=0;

hDll = LoadLibrary("kSentinel.dll");

printf("Hdll=%x\n",hDll);

system("pause");

}

 

z.bat

del a.exe

del *.dll

del *.obj

cl a.c

cl -c -W0 b.c

link /dll /out:ksentinel.dll b.obj user32.lib advapi32.lib imagehlp.lib

a

 

b.c

#include <windows.h>

#include <stdio.h>

#include <imagehlp.h>

#include <stdlib.h>

typedef int  _stdcall MyNewFunctiontype(int i , char *j, char *k, int l);

char  aa[1000],ProcName[1024];

HHOOK hHook;

HMODULE hUser32;

PIMAGE_IMPORT_DESCRIPTOR pImportDesc;

MyNewFunctiontype *hMessageBoxAddr;

DWORD size,ii,dwOldProtect;

PIMAGE_THUNK_DATA pThunk;

BOOL _stdcall MyMessageBox(int i , char *j, char *k, int l)

{

int ret;

ret = (hMessageBoxAddr)(i,j,"Vijay Mukhi",l);

return ret;

}

LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)

{

return CallNextHookEx( hHook, nCode, wParam, lParam);

}

BOOL APIENTRY DllMain(HINSTANCE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved)

{

if(ul_reason_for_call==DLL_PROCESS_ATTACH)

{

GetModuleFileName(0, ProcName, 1024);

if(strstr(ProcName, "a.exe"))

hHook = SetWindowsHookEx(WH_CBT,HookProc,hModule, 0 );

if(  strstr(ProcName, "f.exe") || strstr(ProcName, "g.exe")  )

{

hUser32 = LoadLibrary("user32.dll");

hMessageBoxAddr = GetProcAddress(hUser32,"MessageBoxA");

pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToData(0x400000,TRUE,IMAGE_DIRECTORY_ENTRY_IMPORT,&size);

sprintf(aa,"pImportDesc=%x hUser32=%x hMessageBoxAddr=%x",pImportDesc,hUser32,hMessageBoxAddr);

OutputDebugString(aa);

while (pImportDesc->Name)

{

PSTR pszModName = (PSTR)((PBYTE)0x400000 + pImportDesc->Name);

OutputDebugString(pszModName);

if (stricmp(pszModName, "USER32.dll") == 0)

break;

pImportDesc++;

}

pThunk = (PIMAGE_THUNK_DATA)( (PBYTE)0x400000 + pImportDesc->FirstThunk );

while (pThunk->u1.Function)

{

PROC* ppfn = (PROC*) &pThunk->u1.Function;

BOOL bFound = (*ppfn == hMessageBoxAddr);

sprintf(aa , "Found=%d hMessageBoxAddr=%x ppfn=%x *ppfn=%x",bFound,hMessageBoxAddr,ppfn , *ppfn);

OutputDebugString(aa);

if (bFound)

{

MEMORY_BASIC_INFORMATION mbi;

VirtualQuery(ppfn, &mbi, sizeof(MEMORY_BASIC_INFORMATION));

ii = VirtualProtect(mbi.BaseAddress,mbi.RegionSize,PAGE_READWRITE,&mbi.Protect);

sprintf(aa , "mbi.BaseAddress=%x mbi.RegionSize=%x ii=%d MyMessageBox=%x",mbi.BaseAddress,mbi.RegionSize,ii,MyMessageBox);

OutputDebugString(aa);

*ppfn = MyMessageBox;

break;

}

pThunk++;

}

}

}

return TRUE;

}