Hooking via Import Address Table Patching - Hamtaro aka Corvu5

Post date: Aug 25, 2010 11:31:09 AM

This project is a small example of hooking the MessageBoxA api by patching the Import Address Table (IAT).

Compiled: Delphi 2007

The hooking code:

type
  _IMAGE_IMPORT_DESCRIPTOR = packed record
    case Integer of
      0:(Characteristics: DWORD);
      1:(OriginalFirstThunk:DWORD;TimeDateStamp:DWORD;ForwarderChain: DWORD;Name: DWORD;FirstThunk: DWORD);
    end;
  IMAGE_IMPORT_DESCRIPTOR=_IMAGE_IMPORT_DESCRIPTOR;
  PIMAGE_IMPORT_DESCRIPTOR=^IMAGE_IMPORT_DESCRIPTOR;
procedure PatchIAT(strMod : Pchar; Alt, Neu : Pointer);
var
  pImportDir : pImage_Import_Descriptor;
  size : CardinaL;
  Base : Cardinal;
  pThunk : PDWORD;
begin
  Base := GetModuleHandle(nil);
  pImportDir := ImageDirectoryEntryToData(Pointer(Base),True,IMAGE_DIRECTORY_ENTRY_IMPORT,size);
  while pImportDIr^.Name <> 0 Do
  begin
    If (lstrcmpiA(Pchar(pImportDir^.Name+ Base),strMod) = 0) then
    begin
      pThunk := PDWORD(Base + pImportDir^.FirstThunk);
      While pThunk^ <> 0 Do
      begin
        if DWORD(Alt) = pthunk^ Then
        begin
          pthunk^ :=  Cardinal(Neu);
        end;
        Inc(pThunk);
      end;
    end;
    Inc(PImportDir);
  end;
end;

Only Delphi source code is included in the archive.