Skip to content

Instantly share code, notes, and snippets.

@storycraft
Created June 21, 2021 07:09
Show Gist options
  • Save storycraft/8f268231ced5a4451e20cc05326eb1c1 to your computer and use it in GitHub Desktop.
Save storycraft/8f268231ced5a4451e20cc05326eb1c1 to your computer and use it in GitHub Desktop.
IAT, EAT address finder function utils
#include <windows.h>
PDWORD getExportRvaAddr(HMODULE mod, LPCSTR funcName) {
UINT_PTR modAddr = (UINT_PTR)mod;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) mod;
PIMAGE_NT_HEADERS header = (PIMAGE_NT_HEADERS) (modAddr + dosHeader->e_lfanew);
DWORD eatOffset = header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
PIMAGE_EXPORT_DIRECTORY exportDir = (PIMAGE_EXPORT_DIRECTORY) (modAddr + eatOffset);
DWORD nameLen = exportDir->NumberOfNames;
PDWORD rvaNames = (PDWORD) (modAddr + exportDir->AddressOfNames);
PDWORD rvaAddrs = (PDWORD)(modAddr + exportDir->AddressOfFunctions);
PWORD ordinals = (PWORD)(modAddr + exportDir->AddressOfNameOrdinals);
for (DWORD i = 0; i < nameLen; i++) {
PSTR name = (PSTR) (modAddr + rvaNames[i]);
if (!strcmp(funcName, name)) {
WORD ordinal = ordinals[i];
return &rvaAddrs[ordinal];
}
}
}
PUINT_PTR getImportAddr(HMODULE mod, LPCSTR dllName, LPCSTR funcName) {
UINT_PTR modAddr = (UINT_PTR) mod;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) mod;
PIMAGE_NT_HEADERS header = (PIMAGE_NT_HEADERS) (modAddr + dosHeader->e_lfanew);
DWORD iatOffset = header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (modAddr + iatOffset);
while (importDesc->OriginalFirstThunk) {
LPCSTR tableDllName = (LPCSTR) (modAddr + importDesc->Name);
if (!_stricmp(dllName, tableDllName)) {
PIMAGE_THUNK_DATA thunk = (PIMAGE_THUNK_DATA) (modAddr + importDesc->FirstThunk);
PIMAGE_THUNK_DATA originalThunk = (PIMAGE_THUNK_DATA) (modAddr + importDesc->OriginalFirstThunk);
for (; originalThunk->u1.Function; thunk++, originalThunk++) {
PIMAGE_IMPORT_BY_NAME nameTable = (PIMAGE_IMPORT_BY_NAME) (modAddr + originalThunk->u1.AddressOfData);
if (!strcmp(funcName, nameTable->Name)) return &thunk->u1.Function;
}
return NULL;
}
importDesc++;
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment