BOOL
EATHook(LPCTSTR szDllName, LPCTSTR szFunName, LPVOID NewFun)
{
DWORD addr
=
0
, index
=
0
,dwProtect
=
0
;
HMODULE DllBase
=
LoadLibrary(szDllName);
if
(NULL
=
=
DllBase)
return
(FALSE);
/
/
1.
首先得到Dos头,NT头,数据目录表
PIMAGE_DOS_HEADER pDosHeader
=
(PIMAGE_DOS_HEADER)DllBase;
/
/
PIMAGE_OPTIONAL_HEADER pOptHeader
=
(PIMAGE_OPTIONAL_HEADER)((PBYTE)DllBase
+
pDosHeader
-
>e_lfanew
+
24
);
PIMAGE_NT_HEADERS pNtHeader
=
(PIMAGE_NT_HEADERS)((DWORD)pDosHeader
+
pDosHeader
-
>e_lfanew);
PIMAGE_OPTIONAL_HEADER pOptHeader
=
(PIMAGE_OPTIONAL_HEADER)(&pNtHeader
-
>OptionalHeader);
/
/
2.
得到导出表的虚拟地址
PIMAGE_EXPORT_DIRECTORY pExpDes
=
(PIMAGE_EXPORT_DIRECTORY)
((PBYTE)DllBase
+
pOptHeader
-
>DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
/
/
3.
获取导出表的函数地址,函数名称,函数序号
PULONG pAddressOfFunctions
=
(PULONG)((PBYTE)DllBase
+
pExpDes
-
>AddressOfFunctions);
PULONG pAddressOfNames
=
(PULONG)((PBYTE)DllBase
+
pExpDes
-
>AddressOfNames);
PUSHORT pAddressOfNameOrdinals
=
(PUSHORT)((PBYTE)DllBase
+
pExpDes
-
>AddressOfNameOrdinals);
/
/
4.
循环查找
for
(
int
i
=
0
; i < pExpDes
-
>NumberOfNames;
+
+
i)
{
index
=
pAddressOfNameOrdinals[i];
LPCTSTR pFuncName
=
(LPTSTR)((PBYTE)DllBase
+
pAddressOfNames[i]);
if
(!_tcscmp((LPCTSTR)pFuncName, szFunName))
{
addr
=
pAddressOfFunctions[index];
break
;
}
}
/
/
5.
设置导出函数位置读写属性,将新的导出函数地址写入到该位置
VirtualProtect(&pAddressOfFunctions[index],
0x1000
, PAGE_READWRITE, &dwProtect);
pAddressOfFunctions[index]
=
(DWORD)NewFun
-
(DWORD)DllBase;
WriteProcessMemory(GetCurrentProcess(), &pAddressOfFunctions[index],
(LPCVOID)((DWORD)NewFun
-
(DWORD)DllBase), sizeof(NewFun), &dwProtect);
return
(TRUE);
}
int
__stdcall MyMessageBox(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType)
{
printf(
"hello lyshark \n"
);
return
(
0
);
}
typedef
int
(WINAPI
*
LPFNMESSAGEBOX)(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType);
int
main(
int
argc,char
*
argv[])
{
/
/
对MessageBoxA进行Eat Hook
EATHook(
"USER32.dll"
,
"MessageBoxA"
, MyMessageBox);
/
/
模拟下次调用后就是执行我们的Hook代码
LoadLibrary(
"USER32.dll"
);
HMODULE hDll
=
GetModuleHandle(
"USER32.dll"
);
LPFNMESSAGEBOX lpMessageBox
=
(LPFNMESSAGEBOX)GetProcAddress(hDll,
"MessageBoxA"
);
lpMessageBox(NULL,
"Hello, EAT Hook"
,
"Info"
, MB_OK);
return
(
0
);
}