HOOK IAT

template <class T>
__forceinline
T* VA2RVA(PVOID Base, ULONG_PTR Va)
{
	return (T*)((PCHAR)Base + Va);
}

PIMAGE_IMPORT_DESCRIPTOR GetImageImportDescriptor(HMODULE hModule)
{
	IMAGE_DOS_HEADER *lpDosHeader = (IMAGE_DOS_HEADER*)hModule;
	IMAGE_NT_HEADERS *lpNtHeader = VA2RVA<IMAGE_NT_HEADERS>(hModule, lpDosHeader->e_lfanew);

	if (DWORD v = lpNtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
	{
		return VA2RVA<IMAGE_IMPORT_DESCRIPTOR>(hModule, v);
	}
	return NULL;
}

BOOL IsVaildImage(HMODULE hModule)
{
	IMAGE_DOS_HEADER *lpDosHeader = (IMAGE_DOS_HEADER*)hModule;

	if (lpDosHeader && lpDosHeader->e_magic == IMAGE_DOS_SIGNATURE)
	{
		IMAGE_NT_HEADERS *lpNtHeader = VA2RVA<IMAGE_NT_HEADERS>(hModule, lpDosHeader->e_lfanew);

		if (lpNtHeader->Signature == IMAGE_NT_SIGNATURE)
		{
			return TRUE;
		}
	}
	return FALSE;
}

PVOID HookIAT(HMODULE hModule, LPCSTR lpModuleName, LPCSTR lpApiName, PVOID lpNewApiAddress)
{
	PVOID lpPrevAddress = NULL;

	if (IsVaildImage(hModule))
	{
		if (PIMAGE_IMPORT_DESCRIPTOR lpImportDescriptor = GetImageImportDescriptor(hModule))
		{
			while (lpImportDescriptor->Characteristics)
			{
				LPCSTR lpLibName = VA2RVA<CONST CHAR>(hModule, lpImportDescriptor->Name);

				if (lstrcmpiA(lpModuleName, lpLibName) == 0)
				{
					PIMAGE_THUNK_DATA lpThunk = VA2RVA<IMAGE_THUNK_DATA>(hModule, lpImportDescriptor->OriginalFirstThunk);

					for (UINT i = 0; lpThunk[i].u1.Ordinal; i++)
					{
						if (!(lpThunk[i].u1.Ordinal & IMAGE_ORDINAL_FLAG))
						{
							PIMAGE_IMPORT_BY_NAME lpImportByName = VA2RVA<IMAGE_IMPORT_BY_NAME>(hModule, lpThunk[i].u1.AddressOfData);

							if (lstrcmpA((CHAR*)lpImportByName->Name, lpApiName) == 0)
							{
								PVOID *lppProcTable = VA2RVA<PVOID>(hModule, lpImportDescriptor->FirstThunk);
								DWORD dwProtect;

								VirtualProtect(&lppProcTable[i], sizeof(PVOID), PAGE_EXECUTE_READWRITE, &dwProtect);
								lpPrevAddress = InterlockedExchangePointer(&lppProcTable[i], lpNewApiAddress);
							}
						}
					}
				}
				lpImportDescriptor++;
			}
		}
	}
	return lpPrevAddress;
}

你可能感兴趣的:(HOOK IAT)