Hi. What I'm trying to achieve here is an API hook in a single application. The application is writing several logfiles which is clogging up my harddrive, so I thought I'd reroute WriteFile to a function that does nothing.
I was thinking of injecting a DLL and then patch the API-call. However, I'm not sure which technique I should use to reroute an API. I've tried the Microsoft Detour library but I would rather do it myself, thus I can actually learn something on the way.
What is the easiest way, inside a process, to reroute one or several API's?
Look up hooking on CodeProject. There are several tutorials there.
Thank you. I've looked through a few examples and my eye has fallen on to IAT Patching, a quite interesting technique.
I've been writing some code but I have not gotten it to actually work. This is my code so far:
int WINAPI My_MessageBox(HWND, LPCTSTR, LPCTSTR, UINT);
int * addr = (int *)MessageBoxW;
int * myaddr = (int *)My_MessageBox;
PDWORD pAddr = NULL;
unsigned __stdcall ThreadProc(void *param)
// Hook API
HMODULE hMod = GetModuleHandle(NULL);
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hMod;
PIMAGE_NT_HEADERS pNTHeaders = (PIMAGE_NT_HEADERS)((BYTE *)hMod + pDosHeader->e_lfanew);
PIMAGE_OPTIONAL_HEADER pOptHeader = (PIMAGE_OPTIONAL_HEADER)&(pNTHeaders->OptionalHeader);
PIMAGE_IMPORT_DESCRIPTOR pImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)((BYTE *)hMod + pOptHeader->DataDirectory.VirtualAddress);
char * dllname = (char *)((BYTE *)hMod + pImportDescriptor->Name);
PIMAGE_THUNK_DATA pThunkData = (PIMAGE_THUNK_DATA)((BYTE *)hMod + pImportDescriptor->OriginalFirstThunk);
int no = 1;
char *funname = (char *)((BYTE *)hMod + (DWORD)pThunkData->u1.AddressOfData + 2);
PDWORD lpAddr = (DWORD *)((BYTE *)hMod + (DWORD)pImportDescriptor->FirstThunk) + (no-1);
if((*lpAddr) == (DWORD)addr)
VirtualQuery(lpAddr, &mbi, sizeof(mbi));
VirtualProtect(lpAddr, sizeof(DWORD), PAGE_READWRITE, &dwOld);
WriteProcessMemory(GetCurrentProcess(), lpAddr, &myaddr, sizeof(DWORD), NULL);
pAddr = lpAddr;
BOOL APIENTRY DllMain (HINSTANCE hInst /* Library instance handle. */ ,
DWORD reason /* Reason this function is being called. */ ,
LPVOID reserved /* Not used. */ )
_beginthreadex(NULL, 0, ThreadProc, NULL, NULL, NULL);
MessageBox(NULL, "Testing", "Test", MB_OK);
/* Returns TRUE on success, FALSE on failure */
int WINAPI My_MessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCation, UINT uType)
MessageBox(NULL, "Detoured Messagebox call", "Test", MB_OK);
The DLL is injected in to test.exe's memory space and the hook is being runned. Though The MessageBox-calls simply call the original API.
MessageBox(NULL, "Hey", "Test", MB_OK);
MessageBox(NULL, "Hey", "test2", MB_OK);
Have I misunderstood the technique? What would be the problem? SE_DEBUG_PRIVILEGES?