C++ hook

BOOL SetHook(HMODULE hMod);
FARPROC g_orgProc;
int WINAPI MyMessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCation, UINT uType)
{
	return ((PFNMESSAGEBOX)g_orgProc)(hWnd, "新函数", "HookDemo", uType);
}

int main()
{

	HMODULE hMod = LoadLibrary("user32.dll");
	g_orgProc = GetProcAddress(hMod, "MessageBoxA");

	MessageBox(NULL, "原函数", "HookDemo", 0);

	SetHook(GetModuleHandle(NULL));

	MessageBox(NULL, "原函数", "HookDemo", 0);

    return 0;
}

BOOL SetHook(HMODULE hMod) 
{
	IMAGE_DOS_HEADER* pDosHeader = (IMAGE_DOS_HEADER*)hMod;
	IMAGE_OPTIONAL_HEADER* pOptHeader =
		(IMAGE_OPTIONAL_HEADER*)((BYTE*)hMod + pDosHeader->e_lfanew + 24);
	IMAGE_IMPORT_DESCRIPTOR* pImportDesc = (IMAGE_IMPORT_DESCRIPTOR*)
		((BYTE*)hMod + pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);

	while (pImportDesc->FirstThunk)
	{
		char* pszDllName = (char*)((BYTE*)hMod + pImportDesc->Name);
		if (lstrcmpiA(pszDllName, "user32.dll") == 0) {
			break;
		}
		pImportDesc++;
	}

	if (pImportDesc->FirstThunk) {
		IMAGE_THUNK_DATA* pThunk = (IMAGE_THUNK_DATA*)
			((BYTE*)hMod + pImportDesc->FirstThunk);

		while (pThunk->u1.Function)
		{
			DWORD* lpAddr = (DWORD*) & (pThunk->u1.Function);
			if (*lpAddr == (DWORD)g_orgProc) {
				
				DWORD* lpNewProc = (DWORD*)MyMessageBoxA;
				auto oldAddr = &MessageBoxA;
				auto odw = (DWORD)oldAddr;
				DWORD* oldDword= (DWORD*) & odw;
				
				DWORD dwOldProtect;
				MEMORY_BASIC_INFORMATION mbi;
				//VirtualQuery(lpAddr, &mbi, sizeof(mbi));
				VirtualProtect(lpAddr, sizeof(DWORD), PAGE_READWRITE, &dwOldProtect);
				//WriteProcessMemory(GetCurrentProcess(), lpAddr, &lpNewProc, sizeof(DWORD), NULL);
				*lpAddr = (DWORD)MyMessageBoxA;
				VirtualProtect(lpAddr, sizeof(DWORD), dwOldProtect, &dwOldProtect);
				return TRUE;
			}
		}
		pThunk++;
	}
	return FALSE;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值