By just reading a little further how IAT exactly works, I managed to replace the pointer inside the table with my own specified function pointer. By accessing the first thunk from an imported module, it’s fairly easy to iterate through all thunks. At first, we must locate the import table, described by the PIMAGE_IMPORT_DESCRIPTOR type.
PIMAGE_IMPORT_DESCRIPTOR get_import_table( HINSTANCE inst ) {
PIMAGE_DOS_HEADER dos = ( PIMAGE_DOS_HEADER ) inst;
IMAGE_OPTIONAL_HEADER opt = ( IMAGE_OPTIONAL_HEADER ) ( ( ( PIMAGE_NT_HEADERS ) ( ( unsigned char* ) dos + dos->e_lfanew ) )->OptionalHeader );
return ( PIMAGE_IMPORT_DESCRIPTOR ) ( ( unsigned char* ) inst
+ ( ( IMAGE_DATA_DIRECTORY ) ( opt.DataDirectory[1] ) ).VirtualAddress);
}
With the import table located from the given module, we can now easily access the first thunk. Also, we got full control of the imports, described by both the name of the thunk and the pointer within the IAT. Eventually I came up with the following code stub to access the currently looped thunk name.
PIMAGE_THUNK_DATA thunk = ( PIMAGE_THUNK_DATA ) ( ( unsigned char* ) ret + importedModule->FirstThunk );
PIMAGE_IMPORT_BY_NAME importName = ( PIMAGE_IMPORT_BY_NAME ) ( ( unsigned char* ) ret + ( ( PIMAGE_THUNK_DATA ) ( ( unsigned char* ) ret + importedModule->Characteristics ) )->u1.AddressOfData );
And finally, this is how you retrieve the name and the address. By unlocking the page with the PAGE_READWRITE flag, it’s possible to change the pointer to your own function pointer, resulting in some sort of API “hook”. It’s always a good thing to backup the original IAT location of the function (thunk->u1.Function) in order to call the original function and not your hook (would result in a pointless loop anyways).
while( *( unsigned short* ) thunk != 0 ) {
printf( "%s: 0x%xn", importName->Name, ( unsigned long ) thunk->u1.Function );
thunk++;
}
With a few fault corrections there and then, and a little code-cleaning, I wrote a fully working concept. The complete source code can be found here: http://matvp.info/paste/view.php?id=229