欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IATHook--Ring3

程序员文章站 2022-06-10 14:42:07
...

这是一个Ring3层的Hook技术,对目标进程的导入表中的目标函数进行地址检索匹配,最终Hook掉这个地址,达到我们的目的。
下面给出关键代码:

int
WINAPI
MyMessageBoxA(
	HWND hWnd,
	LPCSTR lpText,
	LPCSTR lpCaption,
	UINT uType)
{
	return __OriginalAddress(NULL, "HookMessageBox", "MyHook", NULL);
}
DWORD IATHook(const char *ModuleName, const char * FunctionName, PVOID HookAddress)
{
	BOOL IsFind = FALSE;
	DWORD OldProtect;

	HMODULE ModuleHandle = LoadLibraryA(ModuleName);

	//从目标模块导出表中找到函数地址
	DWORD	OriginalAddress = (DWORD)GetProcAddress(ModuleHandle, FunctionName);

	//保存全局函数指针,为了在Hook函数中调用,这一步如果你在hook中干其他事情,那就大可不必保存了
	__OriginalAddress = (LPFN_MESSAGEBOXA)OriginalAddress;
	ModuleHandle = GetModuleHandle(NULL);//获得目标进程得模块基地址
	IMAGE_DOS_HEADER*		 ImageDosHeader = (PIMAGE_DOS_HEADER)ModuleHandle;
	IMAGE_NT_HEADERS*		 ImageNtHeaders = (PIMAGE_NT_HEADERS)((DWORD)ModuleHandle + ImageDosHeader->e_lfanew);
	IMAGE_IMPORT_DESCRIPTOR* ImageImportDescriptor = 
		(PIMAGE_IMPORT_DESCRIPTOR)((BYTE*)ImageDosHeader + ImageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
	if (ImageImportDescriptor == NULL)
	{
		return FALSE;
	}
	while (ImageImportDescriptor->FirstThunk)
	{
		//进行导入表模块的名字匹配检索
		char* DllName = (char*)((BYTE*)ImageDosHeader + ImageImportDescriptor->Name);
		if (lstrcmpiA(ModuleName, DllName) == 0)//忽略大小写比较
		{
			IsFind = TRUE;
			break;
		}
		ImageImportDescriptor++;
	}
	if (IsFind == TRUE)
	{
		//进行地址匹配
		IMAGE_THUNK_DATA* ImageThunkData = (PIMAGE_THUNK_DATA)((DWORD)ModuleHandle + ImageImportDescriptor->FirstThunk);
		while (ImageThunkData->u1.Function)
		{
			if ((DWORD)OriginalAddress == ImageThunkData->u1.Function)
			{
				//修改函数地址
				VirtualProtect(&ImageThunkData->u1.Function, 0x1000, PAGE_READWRITE, &OldProtect);
				ImageThunkData->u1.Function = (DWORD)HookAddress;//修改地址槽中的内容
				VirtualProtect(&ImageThunkData->u1.Function, 0x1000, OldProtect, &OldProtect);
				break;
			}
			ImageThunkData++;
		}
	}
	
	return TRUE;

}

原本应该输出:
IATHook--Ring3
Hook之后:
IATHook--Ring3

如果有需要源程序的兄弟,可以私信或者评论。

“Not everyone can become a great artist, but a great artist can come from anywhere.”

相关标签: 应用层Hook