//***********************************************************************************//
// FileName : GBlockHookDll.h
// Author :耿海增
// Date : 2006.10.07
//***********************************************************************************//
#pragma once
#include
#pragma comment(lib,"psapi.lib")
class GBlockHookDll
{
public:
GBlockHookDll()
{
MODULEINFO user32ModInfo = {0};
//获取user32.dll的加载基址和映象大小
GetModuleInformation(GetCurrentProcess(),GetModuleHandle("user32.dll"),&user32ModInfo,sizeof(user32ModInfo));
m_dwUser32Low = (DWORD)user32ModInfo.lpBaseOfDll;
m_dwUser32Hi = (DWORD)user32ModInfo.lpBaseOfDll+user32ModInfo.SizeOfImage;
}
void PatchLoadLibrary()
{
//LoadLibraryExW
//7C801AF1 6A 34 push 34h
//7C801AF3 68 88 E2 80 7C push 7C80E288h
LPVOID* pfnRaw = (LPVOID*)&rawLoadLibraryExW;
LPVOID fnNew = (LPVOID)newLoadLibraryExW;
BYTE* fnRaw = (BYTE*)*pfnRaw;
//1 save the first 7 bytes
const int nFirstBytes = 7;
BYTE* fnFake = (BYTE*)fakeLoadLibraryExW;
memcpy(fnFake,*pfnRaw,nFirstBytes);
fnFake[nFirstBytes] = 0xE9; //jmp to rawAddr+nFirstBytes
*(UINT32*)(fnFake + nFirstBytes+1) = (UINT32)fnRaw+nFirstBytes - (UINT32)(fnFake + nFirstBytes + 5);
//2 modify the raw to jmp to fnNew
DWORD dwOldProtect = 0;
VirtualProtect(fnRaw,nFirstBytes,PAGE_READWRITE,&dwOldProtect); //修改该代码段的属性为可写
*fnRaw = 0xE9;
*(UINT32*)(fnRaw+1) = (UINT32)fnNew - (UINT32)(fnRaw + 5);
VirtualProtect(fnRaw,nFirstBytes,dwOldProtect,0);
//3 change the rawPointer
*pfnRaw = fnFake;
}
private:
static HMODULE WINAPI newLoadLibraryExW(LPCWSTR lpLibFileName,HANDLE hFile,DWORD dwFlags)
{
//get the return address
DWORD dwCaller;
__asm push dword ptr [ebp+4]
__asm pop dword ptr [dwCaller]
if(dwCaller > m_dwUser32Low && dwCaller < m_dwUser32Hi)
{
#ifdef _DEBUG
UINT uLenWide = lstrlenW(lpLibFileName);
char* pNewChar = new char[uLenWide + 1];
memset(pNewChar,0,uLenWide+1);
WideCharToMultiByte(CP_ACP,0,lpLibFileName,-1,pNewChar,uLenWide,NULL,NULL);
TRACE2(".......................LoadLibrary:return addr 0x%x,%s ",dwCaller,pNewChar);
TRACE("Blocked.......................\n");
delete []pNewChar;
#endif
return 0;
}
return rawLoadLibraryExW(lpLibFileName,hFile,dwFlags);
}
private:
static DWORD m_dwUser32Low; //user32.dll 的加载基址
static DWORD m_dwUser32Hi; //user32.dll 的加载基址+ImageSize
static BYTE fakeLoadLibraryExW[12]; //save first bytes of the raw function,and jmp back to that function
//保存LoadLibraryExW的指针,然后修改为fakeLoadLibraryExW
static HMODULE (WINAPI *rawLoadLibraryExW)( LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags );
};
DWORD GBlockHookDll::m_dwUser32Low = 0;
DWORD GBlockHookDll::m_dwUser32Hi = 0;
BYTE GBlockHookDll::fakeLoadLibraryExW[12] = {0};
HMODULE (WINAPI *GBlockHookDll::rawLoadLibraryExW)(LPCWSTR lpLibFileName,HANDLE hFile,DWORD dwFlags) = LoadLibraryExW;
|