VC IAI HOOK demo

45 篇文章 1 订阅
#include <stdio.h>
#include <Windows.h>
#include <Dbghelp.h>

BOOL ModifyImportTable(IMAGE_IMPORT_DESCRIPTOR* iid, void* target,void* replacement)
{
	IMAGE_THUNK_DATA* itd = (IMAGE_THUNK_DATA*)(((char*)GetModuleHandle(NULL)) + iid->FirstThunk);

	while (itd->u1.Function)
	{
		if (((void*)itd->u1.Function) == target)
		{
			// Temporary change access to memory area to READWRITE
			MEMORY_BASIC_INFORMATION mbi;
			VirtualQuery(itd, &mbi, sizeof(MEMORY_BASIC_INFORMATION));
			VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_READWRITE, &mbi.Protect);

			// Replace entry!!
			*((void**)itd) = replacement;

			// Restore memory permissions
			VirtualProtect(mbi.BaseAddress, mbi.RegionSize, mbi.Protect, &mbi.Protect);

			return TRUE;
		}

		itd += 1;
	}
	return FALSE;
}

BOOL InstallHook(LPCSTR module, LPCSTR function, void* hook, void** original)
{
	HMODULE process = GetModuleHandle(NULL);

	// Save original address to function
	*original = (void*)GetProcAddress(GetModuleHandleA(module), function);
	
	ULONG entrySize;

	IMAGE_IMPORT_DESCRIPTOR* iid = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToData(process, 1, IMAGE_DIRECTORY_ENTRY_IMPORT, &entrySize);

	// Search for module
	while (iid->Name)
	{
		const char* name = ((char*)process) + iid->Name;

		if (stricmp(name, module) == 0)
		{
			return ModifyImportTable(iid, *original, hook);
		}
		iid += 1;
	}

	return FALSE;
}

int (__stdcall *RealMessageBoxA)(HWND, LPCSTR, LPCSTR, UINT);

int __stdcall HookedMessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
{
	printf("HookedMessageBoxA Program is trying to display a message box with title '%s' and text '%s'.\n\nAllow (y/n)? ",lpCaption,lpText);
	char choice;
	scanf_s("%c", &choice);
	if (choice == 'y')
	{
		return RealMessageBoxA(hWnd, lpText, lpCaption, uType);
	}
	else
	{
		printf("\nSupressing message...\n");
		return 0;
	}
}

int main()
{
	if (InstallHook("User32.dll", "MessageBoxA", (void*)HookedMessageBoxA, (void**)(&RealMessageBoxA)))
	{
		printf("Hook installed!\n\n");
		MessageBoxA(NULL, "Let me out!", "I'm trapped!", 0);
	}
	else
	{
		printf("Failed to install hook!\n");
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值