#include <windows.h>
#include "APIHook.h"
#include "APIHook.cpp"
typedef HFILE (WINAPI *POPENFILE)(LPCSTR lpFileName, LPOFSTRUCT lpReOpenBuff, UINT uStyle);
typedef HANDLE (WINAPI *PCREATEFILEW)(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
typedef BOOL (WINAPI *PFILTER)(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
HHOOK hHook;
HINSTANCE HInst;
HMODULE hFilter;
POPENFILE OriginOpenFile = 0;
PCREATEFILEW OriginCreateFileW = 0;
PFILTER Filter = 0;
//------------------------------------------------------------------------------
// Convierte cadenas Unicode y clásicas entre si
char* WideCharToChar(const wchar_t* Entrada, char* Salida, unsigned int Size=-1)
{
int size = Size;
if(Size==-1) size = wcslen(Entrada)+1;
WideCharToMultiByte(CP_ACP, 0, Entrada, -1, Salida, size, NULL, NULL);
return Salida;
}
// Provocamos el Hook Global. La dll se inyectará en todo el sistema de ventanas
LRESULT CALLBACK HookPorc(int nCode,WPARAM wParam,LPARAM lParam)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
extern "C" __declspec(dllexport)
__stdcall void Hook()
{
hHook = SetWindowsHookEx(WH_CALLWNDPROC /*WH_CBT*/, (HOOKPROC)HookPorc, HInst, 0);
}
extern "C" __declspec(dllexport)
__stdcall void UnHook()
{
UnhookWindowsHookEx(hHook);
}
HANDLE WINAPI HCreateFileW(
LPCWSTR lpFileNameW,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
)
{
static Hooking = false;
if(!Hooking){
Hooking = true;
CHAR lpFileName[MAX_PATH + 1];
WideCharToChar(lpFileNameW, lpFileName);
bool Filtro = Filter(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if(!Filtro){
Hooking = false;
return (HANDLE)-1;
}
Hooking = false;
}
return OriginCreateFileW(lpFileNameW, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
}
void InstallHook()
{
char FilterDLL[MAX_PATH+1];
GetModuleFileName(HInst, FilterDLL, sizeof(FilterDLL));
char *F = strrchr(FilterDLL, '\\'); *F = 0;
strcat(FilterDLL, "\\FilterDLL.dll");
hFilter = LoadLibrary(FilterDLL);
Filter = (PFILTER)GetProcAddress(hFilter, "Filter");
InstallHook(HCreateFileW, (void**)&OriginCreateFileW, "Kernel32.dll", "CreateFileW");
}
void UnInstallHook()
{
UnInstallHook((void**)&OriginCreateFileW, "Kernel32.dll", "CreateFileW");
FreeLibrary(hFilter);
}
#pragma argsused
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved)
{
HInst = hinstDLL;
switch (fwdreason) {
case DLL_PROCESS_ATTACH:
InstallHook();
break;
case DLL_PROCESS_DETACH:
UnInstallHook();
break;
}
return 1;
}