rewrite hooking logic

This commit is contained in:
Akash Mozumdar 2018-08-25 15:45:25 -04:00
parent 70ae03279c
commit a93a7dc444
11 changed files with 326 additions and 624 deletions

View File

@ -7,6 +7,9 @@
#include "defs.h" #include "defs.h"
#include "../vnrhook/hijack/texthook.h" #include "../vnrhook/hijack/texthook.h"
bool operator==(const ThreadParam& one, const ThreadParam& two) { return one.pid == two.pid && one.hook == two.hook && one.retn == two.retn && one.spl == two.spl; }
namespace namespace
{ {
struct ProcessRecord struct ProcessRecord
@ -21,7 +24,6 @@ namespace
ThreadEventCallback OnCreate, OnRemove; ThreadEventCallback OnCreate, OnRemove;
ProcessEventCallback OnAttach, OnDetach; ProcessEventCallback OnAttach, OnDetach;
bool operator==(const ThreadParam& one, const ThreadParam& two) { return one.pid == two.pid && one.hook == two.hook && one.retn == two.retn && one.spl == two.spl; }
std::unordered_map<ThreadParam, TextThread*> textThreadsByParams; std::unordered_map<ThreadParam, TextThread*> textThreadsByParams;
std::unordered_map<DWORD, ProcessRecord> processRecordsByIds; std::unordered_map<DWORD, ProcessRecord> processRecordsByIds;
@ -228,7 +230,7 @@ namespace Host
WaitForSingleObject(pr.sectionMutex, 0); WaitForSingleObject(pr.sectionMutex, 0);
const TextHook* hooks = (const TextHook*)pr.sectionMap; const TextHook* hooks = (const TextHook*)pr.sectionMap;
for (int i = 0; i < MAX_HOOK; ++i) for (int i = 0; i < MAX_HOOK; ++i)
if (hooks[i].Address() == addr) if (hooks[i].hp.address == addr)
ret = hooks[i].hp; ret = hooks[i].hp;
ReleaseMutex(pr.sectionMutex); ReleaseMutex(pr.sectionMutex);
return ret; return ret;
@ -246,10 +248,10 @@ namespace Host
WaitForSingleObject(pr.sectionMutex, 0); WaitForSingleObject(pr.sectionMutex, 0);
const TextHook* hooks = (const TextHook*)pr.sectionMap; const TextHook* hooks = (const TextHook*)pr.sectionMap;
for (int i = 0; i < MAX_HOOK; ++i) for (int i = 0; i < MAX_HOOK; ++i)
if (hooks[i].Address() == addr) if (hooks[i].hp.address == addr)
{ {
buffer.resize(hooks[i].NameLength()); buffer.resize(hooks[i].name_length);
ReadProcessMemory(pr.processHandle, hooks[i].Name(), &buffer[0], hooks[i].NameLength(), nullptr); ReadProcessMemory(pr.processHandle, hooks[i].hook_name, &buffer[0], hooks[i].name_length, nullptr);
} }
ReleaseMutex(pr.sectionMutex); ReleaseMutex(pr.sectionMutex);
USES_CONVERSION; USES_CONVERSION;

View File

@ -25,8 +25,6 @@ struct HookParam
filter_fun_t filter_fun; filter_fun_t filter_fun;
hook_fun_t hook_fun; hook_fun_t hook_fun;
BYTE hook_len, // ?
recover_len; // ?
HANDLE readerHandle; // Artikash 8/4/2018: handle for reader thread HANDLE readerHandle; // Artikash 8/4/2018: handle for reader thread
}; };

View File

@ -546,7 +546,7 @@ bool InsertKiriKiriHook() // 9/20/2014 jichi: change return type to bool
//RegisterEngineType(ENGINE_KIRIKIRI); //RegisterEngineType(ENGINE_KIRIKIRI);
if (k1 && k2) { if (k1 && k2) {
ConsoleOutput("vnreng:KiriKiri1: disable GDI hooks"); ConsoleOutput("vnreng:KiriKiri1: disable GDI hooks");
DisableGDIHooks();
} }
return k1 || k2; return k1 || k2;
} }
@ -1324,7 +1324,7 @@ void NewKiriKiriZHook(DWORD addr)
NewHook(hp, "KiriKiriZ"); NewHook(hp, "KiriKiriZ");
ConsoleOutput("vnreng:KiriKiriZ: disable GDI hooks"); ConsoleOutput("vnreng:KiriKiriZ: disable GDI hooks");
DisableGDIHooks();
} }
bool KiriKiriZHook1(DWORD esp_base, HookParam *) bool KiriKiriZHook1(DWORD esp_base, HookParam *)
@ -1998,7 +1998,7 @@ bool InsertBGI2Hook()
// Disable TextOutA, which is cached and hence missing characters. // Disable TextOutA, which is cached and hence missing characters.
ConsoleOutput("vnreng:BGI2: disable GDI hooks"); ConsoleOutput("vnreng:BGI2: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -2177,7 +2177,7 @@ static bool InsertRealliveDynamicHook(LPVOID addr, DWORD frame, DWORD stack)
NewHook(hp, "RealLive"); NewHook(hp, "RealLive");
//RegisterEngineType(ENGINE_REALLIVE); //RegisterEngineType(ENGINE_REALLIVE);
ConsoleOutput("vnreng:RealLive: disable GDI hooks"); ConsoleOutput("vnreng:RealLive: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
} }
@ -2299,7 +2299,7 @@ bool InsertSiglus3Hook()
NewHook(hp, "SiglusEngine3"); NewHook(hp, "SiglusEngine3");
ConsoleOutput("vnreng:Siglus3: disable GDI hooks"); ConsoleOutput("vnreng:Siglus3: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -2450,7 +2450,7 @@ bool InsertSiglus4Hook()
NewHook(hp, "SiglusEngine4"); NewHook(hp, "SiglusEngine4");
ConsoleOutput("vnreng:Siglus4: disable GDI hooks"); ConsoleOutput("vnreng:Siglus4: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -2640,7 +2640,7 @@ bool InsertSiglus4Hook()
NewHook(hp, "SiglusEngine4"); NewHook(hp, "SiglusEngine4");
ConsoleOutput("vnreng:Siglus4: disable GDI hooks"); ConsoleOutput("vnreng:Siglus4: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
#endif // 0 #endif // 0
@ -4735,7 +4735,7 @@ static bool InsertSystem43OldHook(ULONG startAddress, ULONG stopAddress, LPCSTR
NewHook(hp, hookName); NewHook(hp, hookName);
ConsoleOutput("vnreng:System43: disable GDI hooks"); // disable hooking to TextOutA, which is cached ConsoleOutput("vnreng:System43: disable GDI hooks"); // disable hooking to TextOutA, which is cached
DisableGDIHooks();
return true; return true;
} }
@ -5473,7 +5473,7 @@ static bool InsertSystem43NewHook(ULONG startAddress, ULONG stopAddress, LPCSTR
NewHook(hp, hookName); NewHook(hp, hookName);
ConsoleOutput("vnreng:System43+: disable GDI hooks"); // disable hooking to TextOutA, which is cached ConsoleOutput("vnreng:System43+: disable GDI hooks"); // disable hooking to TextOutA, which is cached
DisableGDIHooks();
return true; return true;
} }
@ -6635,7 +6635,7 @@ bool InsertMalieHook2() // jichi 8/20/2013: Change return type to boolean
NewHook(hp, "Malie"); NewHook(hp, "Malie");
//RegisterEngineType(ENGINE_MALIE); //RegisterEngineType(ENGINE_MALIE);
ConsoleOutput("vnreng:Malie2: disable GDI hooks"); ConsoleOutput("vnreng:Malie2: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -6964,7 +6964,7 @@ bool InsertMalie3Hook()
ConsoleOutput("vnreng: INSERT Malie3"); ConsoleOutput("vnreng: INSERT Malie3");
NewHook(hp, "Malie3"); NewHook(hp, "Malie3");
ConsoleOutput("vnreng:Malie3: disable GDI hooks"); ConsoleOutput("vnreng:Malie3: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -7042,7 +7042,7 @@ bool InsertMalieHook()
if (ok) { if (ok) {
ConsoleOutput("vnreng:Malie: disable GDI hooks"); ConsoleOutput("vnreng:Malie: disable GDI hooks");
DisableGDIHooks();
} }
return ok; return ok;
} }
@ -8077,7 +8077,7 @@ bool InsertApricoTHook()
//RegisterEngineType(ENGINE_APRICOT); //RegisterEngineType(ENGINE_APRICOT);
// jichi 2/14/2015: disable cached GDI functions // jichi 2/14/2015: disable cached GDI functions
ConsoleOutput("vnreng:ApRicoT: disable GDI hooks"); ConsoleOutput("vnreng:ApRicoT: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -8203,9 +8203,6 @@ bool InsertDebonosuScenarioHook()
hp.type = USING_STRING|NO_CONTEXT|USING_SPLIT|FIXING_SPLIT; // there is only one thread hp.type = USING_STRING|NO_CONTEXT|USING_SPLIT|FIXING_SPLIT; // there is only one thread
ConsoleOutput("vnreng: INSERT Debonosu"); ConsoleOutput("vnreng: INSERT Debonosu");
NewHook(hp, "Debonosu"); NewHook(hp, "Debonosu");
//RegisterEngineType(ENGINE_DEBONOSU);
ConsoleOutput("vnreng:Debonosu: disable GDI+ hooks");
DisableGDIPlusHooks();
return true; return true;
} }
} }
@ -8439,7 +8436,7 @@ bool InsertSystemAoiDynamicHook(LPVOID addr, DWORD frame, DWORD stack)
else else
NewHook(hp, "SystemAoi"); // jichi 7/8/2014: renamed, see: ja.wikipedia.org/wiki/ソフトハウスキャラ NewHook(hp, "SystemAoi"); // jichi 7/8/2014: renamed, see: ja.wikipedia.org/wiki/ソフトハウスキャラ
ConsoleOutput("vnreng:SystemAoi: disable GDI hooks"); ConsoleOutput("vnreng:SystemAoi: disable GDI hooks");
DisableGDIHooks();
} else } else
ConsoleOutput("vnreng: failed to detect SystemAoi"); ConsoleOutput("vnreng: failed to detect SystemAoi");
//RegisterEngineType(ENGINE_SOFTHOUSE); //RegisterEngineType(ENGINE_SOFTHOUSE);
@ -8494,7 +8491,7 @@ bool InsertSystemAoiStatic(HMODULE hModule, bool wideChar) // attach scenario
else else
NewHook(hp, "SystemAoiA"); NewHook(hp, "SystemAoiA");
ConsoleOutput("vnreng:SystemAoiStatic: disable GDI hooks"); ConsoleOutput("vnreng:SystemAoiStatic: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
} // unnamed namespace } // unnamed namespace
@ -9675,7 +9672,7 @@ static bool InsertGXP1Hook()
// jichi 5/13/2015: Disable hooking to GetGlyphOutlineW // jichi 5/13/2015: Disable hooking to GetGlyphOutlineW
// FIXME: GetGlyphOutlineW can extract name, but GXP cannot // FIXME: GetGlyphOutlineW can extract name, but GXP cannot
ConsoleOutput("vnreng:GXP: disable GDI hooks"); ConsoleOutput("vnreng:GXP: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
} }
@ -9711,7 +9708,7 @@ static bool InsertGXP2Hook()
ConsoleOutput("vnreng: INSERT GXP2"); ConsoleOutput("vnreng: INSERT GXP2");
NewHook(hp, "GXP2"); NewHook(hp, "GXP2");
ConsoleOutput("vnreng:GXP: disable GDI hooks"); ConsoleOutput("vnreng:GXP: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -9928,7 +9925,7 @@ bool InsertNextonHook()
NewHook(hp, "NEXTON"); NewHook(hp, "NEXTON");
//ConsoleOutput("vnreng:NEXTON: disable GDI hooks"); // There are no GDI functions hooked though //ConsoleOutput("vnreng:NEXTON: disable GDI hooks"); // There are no GDI functions hooked though
//DisableGDIHooks(); // disable GetGlyphOutlineA // // disable GetGlyphOutlineA
return true; return true;
} }
@ -13415,7 +13412,7 @@ bool InsertExpHook()
NewHook(hp, "EXP"); // FIXME: text displayed line by line NewHook(hp, "EXP"); // FIXME: text displayed line by line
ConsoleOutput("vnreng:EXP: disable GDI hooks"); // There are no GDI functions hooked though ConsoleOutput("vnreng:EXP: disable GDI hooks"); // There are no GDI functions hooked though
DisableGDIHooks();
return true; return true;
} }
@ -13709,7 +13706,7 @@ bool Insert5pbHook1()
// GDI functions are not used by 5pb games anyway. // GDI functions are not used by 5pb games anyway.
//ConsoleOutput("vnreng:5pb: disable GDI hooks"); //ConsoleOutput("vnreng:5pb: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
@ -13760,7 +13757,7 @@ bool Insert5pbHook2()
// GDI functions are not used by 5pb games anyway. // GDI functions are not used by 5pb games anyway.
//ConsoleOutput("vnreng:5pb: disable GDI hooks"); //ConsoleOutput("vnreng:5pb: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
@ -13914,7 +13911,7 @@ bool Insert5pbHook3()
NewHook(hp, "5pb3"); NewHook(hp, "5pb3");
// GDI functions are not used by 5pb games anyway. // GDI functions are not used by 5pb games anyway.
//ConsoleOutput("vnreng:5pb: disable GDI hooks"); //ConsoleOutput("vnreng:5pb: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
} // unnamed namespace } // unnamed namespace
@ -14062,7 +14059,7 @@ static bool InsertMinkDynamicHook(LPVOID fun, DWORD frame, DWORD stack)
NewHook(hp, "Mink"); NewHook(hp, "Mink");
ConsoleOutput("vnreng:Mink: disable GDI hooks"); ConsoleOutput("vnreng:Mink: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
#endif // 0 #endif // 0
@ -14119,7 +14116,7 @@ bool InsertMinkHook()
NewHook(hp, "Mink"); NewHook(hp, "Mink");
//ConsoleOutput("vnreng:Mink: disable GDI hooks"); //ConsoleOutput("vnreng:Mink: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
@ -14544,7 +14541,7 @@ bool InsertLeafHook()
NewHook(hp, "Leaf"); NewHook(hp, "Leaf");
//ConsoleOutput("vnreng:Leaf: disable GDI hooks"); //ConsoleOutput("vnreng:Leaf: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
@ -14598,7 +14595,7 @@ bool InsertNekopackHook()
// Disable GDIHook(um.. ?), which is cached and hence missing characters. // Disable GDIHook(um.. ?), which is cached and hence missing characters.
//ConsoleOutput("vnreng:NekoPack: disable GDI hooks"); //ConsoleOutput("vnreng:NekoPack: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
@ -14710,7 +14707,7 @@ bool InsertLunaSoftHook()
// There are no GDI functions anyway // There are no GDI functions anyway
//ConsoleOutput("vnreng:LunaSoft: disable GDI hooks"); //ConsoleOutput("vnreng:LunaSoft: disable GDI hooks");
//DisableGDIHooks(); //
return true; return true;
} }
@ -14853,7 +14850,7 @@ bool InsertFocasLensHook()
NewHook(hp, "FocasLens"); NewHook(hp, "FocasLens");
// GDI functions are kept in case the font is not cached // GDI functions are kept in case the font is not cached
//DisableGDIHooks(); //
return true; return true;
} }
@ -15026,7 +15023,7 @@ bool InsertSyuntadaHook()
// TextOutA will produce repeated texts // TextOutA will produce repeated texts
ConsoleOutput("vnreng:Syuntada: disable GDI hooks"); ConsoleOutput("vnreng:Syuntada: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
@ -15239,7 +15236,7 @@ bool InsertBootupGDIHook()
NewHook(hp, widechar ? "BootupW" : "BootupA"); NewHook(hp, widechar ? "BootupW" : "BootupA");
ConsoleOutput("vnreng:BootupGDI: disable GDI hooks"); ConsoleOutput("vnreng:BootupGDI: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }
bool InsertBootupLstrHook() // for character name bool InsertBootupLstrHook() // for character name
@ -16394,7 +16391,7 @@ bool InsertAdobeFlash10Hook()
NewHook(hp, "Adobe Flash 10"); NewHook(hp, "Adobe Flash 10");
ConsoleOutput("vnreng:AdobeFlash10: disable GDI hooks"); ConsoleOutput("vnreng:AdobeFlash10: disable GDI hooks");
DisableGDIHooks();
return true; return true;
} }

View File

@ -22,14 +22,13 @@ enum { MAX_REL_ADDR = 0x200000 }; // jichi 8/18/2013: maximum relative address
// - Global variables - // - Global variables -
DWORD processStartAddress, processStopAddress;
namespace Engine { namespace Engine {
WCHAR *processName, // cached WCHAR *processName, // cached
processPath[MAX_PATH]; // cached processPath[MAX_PATH]; // cached
DWORD process_base,
process_limit;
//LPVOID trigger_addr; //LPVOID trigger_addr;
trigger_fun_t trigger_fun_; trigger_fun_t trigger_fun_;
@ -85,7 +84,7 @@ bool DeterminePCEngine()
// PC games // PC games
PcHooks::hookGDIFunctions(); PcHooks::hookGDIFunctions();
EnableGDIPlusHooks(); PcHooks::hookGDIPlusFunctions();
return false; return false;
} }
@ -866,8 +865,6 @@ bool DetermineEngineType()
seh_with_eh(ExceptHandler, seh_with_eh(ExceptHandler,
found = UnsafeDetermineEngineType()); found = UnsafeDetermineEngineType());
#endif // ITH_HAS_SEH #endif // ITH_HAS_SEH
if (::GDIPlusHooksEnabled())
PcHooks::hookGDIPlusFunctions();
if (!found) { // jichi 10/2/2013: Only enable it if no game engine is detected if (!found) { // jichi 10/2/2013: Only enable it if no game engine is detected
PcHooks::hookLstrFunctions(); PcHooks::hookLstrFunctions();
PcHooks::hookCharNextFunctions(); PcHooks::hookCharNextFunctions();
@ -891,6 +888,15 @@ void Hijack()
GetModuleFileNameW(nullptr, processPath, MAX_PATH); GetModuleFileNameW(nullptr, processPath, MAX_PATH);
processName = wcsrchr(processPath, L'\\') + 1; processName = wcsrchr(processPath, L'\\') + 1;
::processStartAddress = ::processStopAddress = (DWORD)GetModuleHandleW(nullptr);
MEMORY_BASIC_INFORMATION info;
do
{
VirtualQuery((void*)::processStopAddress, &info, sizeof(info));
::processStopAddress = (DWORD)info.BaseAddress + info.RegionSize;
} while (info.Protect > PAGE_NOACCESS);
processStopAddress -= info.RegionSize;
DetermineEngineType(); DetermineEngineType();
hijacked = true; hijacked = true;
} }

View File

@ -123,7 +123,7 @@ void PcHooks::hookGDIPlusFunctions()
{ {
HMODULE hModule = ::GetModuleHandleA("gdiplus.dll"); HMODULE hModule = ::GetModuleHandleA("gdiplus.dll");
if (!hModule) { if (!hModule) {
ConsoleOutput("not loaded"); ConsoleOutput("gdi+: not loaded");
return; return;
} }

View File

@ -10,218 +10,92 @@
#endif // _MSC_VER #endif // _MSC_VER
#include "hijack/texthook.h" #include "hijack/texthook.h"
#include "MinHook.h"
#include "engine/match.h" #include "engine/match.h"
#include "except.h" #include "except.h"
#include "main.h" #include "main.h"
#include "pipe.h"
#include "const.h" #include "const.h"
#include "ithsys/ithsys.h" #include "ithsys/ithsys.h"
#include "disasm/disasm.h" #include "disasm/disasm.h"
#include "growl.h" #include "growl.h"
//#include "winseh/winseh.h" #include <Psapi.h>
//#define ConsoleOutput(...) (void)0 // jichi 9/17/2013: I don't need this >< TextHook *hookman;
// - Global variables -
// 10/14/2014 jichi: disable GDI hooks
static bool gdi_hook_enabled_ = true; // enable GDI by default
static bool gdiplus_hook_enabled_ = false; // disable GDIPlus by default
bool GDIHooksEnabled() { return ::gdi_hook_enabled_; }
bool GDIPlusHooksEnabled() { return ::gdiplus_hook_enabled_; }
void EnableGDIHooks() { ::gdi_hook_enabled_ = true; }
void EnableGDIPlusHooks() { ::gdiplus_hook_enabled_ = true; }
void DisableGDIHooks() { ::gdi_hook_enabled_ = false; }
void DisableGDIPlusHooks() { ::gdiplus_hook_enabled_ = false; }
//FilterRange filter[8];
DWORD flag,
enter_count;
TextHook *hookman,
*current_available;
// - Unnamed helpers - // - Unnamed helpers -
#ifndef _WIN64 #ifndef _WIN64
namespace { // unnamed namespace { // unnamed
//provide const time hook entry.
int userhook_count;
const BYTE common_hook[] = { const BYTE common_hook[] = {
0x9c, // pushfd 0x9c, // pushfd
0x60, // pushad 0x60, // pushad
0x9c, // pushfd 0x9c, // pushfd
0x8d,0x54,0x24,0x28, // lea edx,[esp+0x28] ; esp value 0x8d,0x54,0x24,0x28, // lea edx,[esp+0x28] ; esp value
0x8b,0x32, // mov esi,[edx] ; return address 0x8b,0x32, // mov esi,[edx] ; return address
0xb9, 0,0,0,0, // mov ecx, $ ; pointer to TextHook 0xb9, 0,0,0,0, // mov ecx, $ ; pointer to TextHook
0xe8, 0,0,0,0, // call @hook 0xe8, 0,0,0,0, // call @hook
0x9d, // popfd 0x9d, // popfd
0x61, // popad 0x61, // popad
0x9d // popfd 0x9d, // popfd
}; 0xe9 // jmp @original
};
/** DWORD Hash(std::wstring module)
* jichi 7/19/2014 {
* DWORD hash = 0;
* @param original_addr for (auto i : module) hash = _rotr(hash, 7) + i;
* @param new_addr return hash;
* @param hook_len }
* @param original_len
* @return -1 if failed, else 0 if ?, else ?
*/
int MapInstruction(DWORD original_addr, DWORD new_addr, BYTE &hook_len, BYTE &original_len)
{
int flag = 0;
DWORD l = 0;
const BYTE *r = (const BYTE *)original_addr; // 7/19/2014 jichi: original address is not modified
BYTE *c = (BYTE *)new_addr; // 7/19/2014 jichi: but new address might be modified
while((r - (BYTE *) original_addr) < 5) {
l = ::disasm(r);
if (l == 0) {
ConsoleOutput("vnrcli:MapInstruction: FAILED: failed to disasm");
return -1;
}
::memcpy(c, r, l); //copy original instruction
if (*r >= 0x70 && *r < 0x80) { //jmp back
c[0] = 0xf; DWORD GetModuleBase(DWORD hash)
c[1] = *r + 0x10; {
c += 6; HMODULE allModules[1000];
__asm DWORD size;
{ EnumProcessModules(GetCurrentProcess(), allModules, sizeof(allModules), &size);
mov eax,r wchar_t name[MAX_PATH];
add eax,2 for (int i = 0; i < size / sizeof(HMODULE); ++i)
movsx edx,byte ptr [eax-1] {
add edx,eax GetModuleFileNameW(allModules[i], name, MAX_PATH);
mov eax,c _wcslwr(name);
sub edx,eax if (Hash(wcsrchr(name, L'\\') + 1) == hash) return (DWORD)allModules[i];
mov [eax-4],edx }
} return 0;
} else if (*r == 0xeb) { }
c[0] = 0xe9;
c += 5;
__asm
{
mov eax,r
add eax,2
movsx edx,[eax-1]
add edx,eax
mov eax,c
sub edx,eax
mov [eax-4],edx
}
if (r - (BYTE *)original_addr < 5 - l) {
ConsoleOutput("vnrcli:MapInstruction: not safe to move instruction right after short jmp");
return -1; // Not safe to move instruction right after short jmp.
} else
flag = 1;
} else if (*r == 0xe8 || *r == 0xe9) {
c[0]=*r;
c += 5;
flag = (*r == 0xe9);
__asm
{
mov eax,r
add eax,5
mov edx,[eax-4]
add edx,eax
mov eax,c
sub edx,eax
mov [eax-4],edx
}
} else if (*r == 0xf && (*(r + 1) >> 4) == 0x8) {
c += 6;
__asm
{
mov eax,r
mov edx,dword ptr [eax+2]
add eax,6
add eax,edx
mov edx,c
sub eax,edx
mov [edx-4],eax
}
}
else
c += l;
r += l;
}
original_len = r - (BYTE *)original_addr;
hook_len = c - (BYTE *)new_addr;
return flag;
}
//copy original instruction __declspec(naked) // jichi 10/2/2013: No prolog and epilog
//jmp back int ProcessHook(DWORD dwDataBase, DWORD dwRetn, TextHook *hook) // Use SEH to ensure normal execution even bad hook inserted.
DWORD GetModuleBase(DWORD hash) {
{ // jichi 12/17/2013: The function parameters here are meaning leass. The parameters are in esi and edi
__asm __asm
{ {
mov eax,fs:[0x30] push esi
mov eax,[eax+0xc] push edx
mov esi,[eax+0x14] call TextHook::Send
mov edi,_wcslwr retn // jichi 12/13/2013: return near, see: http://stackoverflow.com/questions/1396909/ret-retn-retf-how-to-use-them
listfind: }
mov edx,[esi+0x28] }
test edx,edx
jz notfound
push edx
call edi
pop edx
xor eax,eax
calc:
movzx ecx, word ptr [edx]
test cl,cl
jz fin
ror eax,7
add eax,ecx
add edx,2
jmp calc
fin:
cmp eax,[hash]
je found
mov esi,[esi]
jmp listfind
notfound:
xor eax,eax
jmp termin
found:
mov eax,[esi+0x10]
termin:
}
}
__declspec(naked) // jichi 10/2/2013: No prolog and epilog
int ProcessHook(DWORD dwDataBase, DWORD dwRetn, TextHook *hook) // Use SEH to ensure normal execution even bad hook inserted.
{
// jichi 12/17/2013: The function parameters here are meaning leass. The parameters are in esi and edi
__asm
{
push esi
push edx
call TextHook::Send
retn // jichi 12/13/2013: return near, see: http://stackoverflow.com/questions/1396909/ret-retn-retf-how-to-use-them
}
}
} // unnamed namespace } // unnamed namespace
#endif // _WIN32 #endif // _WIN32
// - TextHook methods - // - TextHook methods -
int TextHook::InsertHook() bool TextHook::InsertHook()
{ {
int ok = 1; bool ret = false;
//ConsoleOutput("vnrcli:InsertHook: enter"); //ConsoleOutput("vnrcli:InsertHook: enter");
WaitForSingleObject(hmMutex, 0); WaitForSingleObject(hmMutex, 0);
if (hp.type & DIRECT_READ) ok = InsertReadCode(); if (hp.type & DIRECT_READ) ret = InsertReadCode();
#ifndef _WIN64 #ifndef _WIN64
else ok = InsertHookCode(); else ret = InsertHookCode();
#endif #endif
ReleaseMutex(hmMutex); ReleaseMutex(hmMutex);
//ConsoleOutput("vnrcli:InsertHook: leave"); //ConsoleOutput("vnrcli:InsertHook: leave");
return ok; return ret;
} }
#ifndef _WIN64 #ifndef _WIN64
@ -234,211 +108,136 @@ int TextHook::InsertHook()
// - dwRetn: the return address of the hook // - dwRetn: the return address of the hook
DWORD TextHook::Send(DWORD dwDataBase, DWORD dwRetn) DWORD TextHook::Send(DWORD dwDataBase, DWORD dwRetn)
{ {
DWORD ret = 0; DWORD ret = 0;
ITH_WITH_SEH(ret = UnsafeSend(dwDataBase, dwRetn)); ITH_WITH_SEH(ret = UnsafeSend(dwDataBase, dwRetn));
return ret; return ret;
} }
DWORD TextHook::UnsafeSend(DWORD dwDataBase, DWORD dwRetn) DWORD TextHook::UnsafeSend(DWORD dwDataBase, DWORD dwRetn)
{ {
DWORD dwCount, DWORD dwCount,
dwAddr, dwAddr,
dwDataIn, dwDataIn,
dwSplit; dwSplit;
BYTE pbData[PIPE_BUFFER_SIZE]; BYTE pbData[PIPE_BUFFER_SIZE];
DWORD dwType = hp.type; DWORD dwType = hp.type;
dwAddr = hp.address; dwAddr = hp.address;
/** jichi 12/24/2014 /** jichi 12/24/2014
* @param addr function address * @param addr function address
* @param frame real address of the function, supposed to be the same as addr * @param frame real address of the function, supposed to be the same as addr
* @param stack address of current stack - 4 * @param stack address of current stack - 4
* @return If success, which is reverted * @return If success, which is reverted
*/ */
if (::trigger) if (::trigger)
::trigger = Engine::InsertDynamicHook((LPVOID)dwAddr, *(DWORD *)(dwDataBase - 0x1c), *(DWORD *)(dwDataBase-0x18)); ::trigger = Engine::InsertDynamicHook((LPVOID)dwAddr, *(DWORD *)(dwDataBase - 0x1c), *(DWORD *)(dwDataBase - 0x18));
// jichi 10/24/2014: generic hook function // jichi 10/24/2014: generic hook function
if (hp.hook_fun && !hp.hook_fun(dwDataBase, &hp)) if (hp.hook_fun && !hp.hook_fun(dwDataBase, &hp))
hp.hook_fun = nullptr; hp.hook_fun = nullptr;
if (dwType & HOOK_EMPTY) // jichi 10/24/2014: dummy hook only for dynamic hook if (dwType & HOOK_EMPTY) // jichi 10/24/2014: dummy hook only for dynamic hook
return 0; return 0;
dwCount = 0; dwCount = 0;
dwSplit = 0; dwSplit = 0;
dwDataIn = *(DWORD *)(dwDataBase + hp.offset); // default value dwDataIn = *(DWORD *)(dwDataBase + hp.offset); // default value
if (hp.text_fun) { if (hp.text_fun) {
hp.text_fun(dwDataBase, &hp, 0, &dwDataIn, &dwSplit, &dwCount); hp.text_fun(dwDataBase, &hp, 0, &dwDataIn, &dwSplit, &dwCount);
} else { }
if (dwDataIn == 0) else {
return 0; if (dwDataIn == 0)
if (dwType & FIXING_SPLIT) return 0;
dwSplit = FIXED_SPLIT_VALUE; // fuse all threads, and prevent floating if (dwType & FIXING_SPLIT)
else if (dwType & USING_SPLIT) { dwSplit = FIXED_SPLIT_VALUE; // fuse all threads, and prevent floating
dwSplit = *(DWORD *)(dwDataBase + hp.split); else if (dwType & USING_SPLIT) {
if (dwType & SPLIT_INDIRECT) { dwSplit = *(DWORD *)(dwDataBase + hp.split);
if (IthGetMemoryRange((LPVOID)(dwSplit + hp.split_index), 0, 0)) if (dwType & SPLIT_INDIRECT) {
dwSplit = *(DWORD *)(dwSplit + hp.split_index); if (IthGetMemoryRange((LPVOID)(dwSplit + hp.split_index), 0, 0))
else dwSplit = *(DWORD *)(dwSplit + hp.split_index);
return 0; else
} return 0;
} }
if (dwType & DATA_INDIRECT) { }
if (IthGetMemoryRange((LPVOID)(dwDataIn + hp.index), 0, 0)) if (dwType & DATA_INDIRECT) {
dwDataIn = *(DWORD *)(dwDataIn + hp.index); if (IthGetMemoryRange((LPVOID)(dwDataIn + hp.index), 0, 0))
else dwDataIn = *(DWORD *)(dwDataIn + hp.index);
return 0; else
} return 0;
dwCount = GetLength(dwDataBase, dwDataIn); }
} dwCount = GetLength(dwDataBase, dwDataIn);
// jichi 12/25/2013: validate data size }
if (dwCount == 0 || dwCount > PIPE_BUFFER_SIZE - sizeof(ThreadParam)) // jichi 12/25/2013: validate data size
return 0; if (dwCount == 0 || dwCount > PIPE_BUFFER_SIZE - sizeof(ThreadParam))
return 0;
if (hp.length_offset == 1) { if (hp.length_offset == 1) {
dwDataIn &= 0xffff; dwDataIn &= 0xffff;
if ((dwType & BIG_ENDIAN) && (dwDataIn >> 8)) if ((dwType & BIG_ENDIAN) && (dwDataIn >> 8))
dwDataIn = _byteswap_ushort(dwDataIn & 0xffff); dwDataIn = _byteswap_ushort(dwDataIn & 0xffff);
if (dwCount == 1) if (dwCount == 1)
dwDataIn &= 0xff; dwDataIn &= 0xff;
*(WORD *)(pbData + sizeof(ThreadParam)) = dwDataIn & 0xffff; *(WORD *)(pbData + sizeof(ThreadParam)) = dwDataIn & 0xffff;
} }
else else
::memcpy(pbData + sizeof(ThreadParam), (void *)dwDataIn, dwCount); ::memcpy(pbData + sizeof(ThreadParam), (void *)dwDataIn, dwCount);
// jichi 10/14/2014: Add filter function // jichi 10/14/2014: Add filter function
if (hp.filter_fun && !hp.filter_fun(pbData + sizeof(ThreadParam), &dwCount, &hp, 0) || dwCount <= 0) { if (hp.filter_fun && !hp.filter_fun(pbData + sizeof(ThreadParam), &dwCount, &hp, 0) || dwCount <= 0) {
return 0; return 0;
} }
if (dwType & (NO_CONTEXT|FIXING_SPLIT)) if (dwType & (NO_CONTEXT | FIXING_SPLIT))
dwRetn = 0; dwRetn = 0;
*(ThreadParam*)pbData = { GetCurrentProcessId(), dwAddr, dwRetn, dwSplit }; *(ThreadParam*)pbData = { GetCurrentProcessId(), dwAddr, dwRetn, dwSplit };
if (dwCount) { if (dwCount) {
DWORD unused; DWORD unused;
//CliLockPipe(); //CliLockPipe();
WriteFile(::hookPipe, pbData, dwCount + sizeof(ThreadParam), &unused, nullptr); WriteFile(::hookPipe, pbData, dwCount + sizeof(ThreadParam), &unused, nullptr);
//CliUnlockPipe(); //CliUnlockPipe();
} }
return 0; return 0;
} }
int TextHook::InsertHookCode() bool TextHook::InsertHookCode()
{ {
DWORD ret = no; bool ret = false;
// jichi 9/17/2013: might raise 0xC0000005 AccessViolationException on win7 // jichi 9/17/2013: might raise 0xC0000005 AccessViolationException on win7
ITH_WITH_SEH(ret = UnsafeInsertHookCode()); __try { ret = UnsafeInsertHookCode(); }
//if (ret == no) __except (1) {};
// ITH_WARN(L"Failed to insert hook"); return ret;
return ret;
} }
int TextHook::UnsafeInsertHookCode() bool TextHook::UnsafeInsertHookCode()
{ {
//ConsoleOutput("vnrcli:UnsafeInsertHookCode: enter"); if (hp.module && (hp.type & MODULE_OFFSET)) // Map hook offset to real address.
if (hp.module && (hp.type & MODULE_OFFSET)) { // Map hook offset to real address. {
if (DWORD base = GetModuleBase(hp.module)) { if (DWORD base = GetModuleBase(hp.module)) hp.address += base;
hp.address += base; else return ConsoleOutput("NextHooker: UnsafeInsertHookCode: FAILED: module not present"), false;
} hp.type &= ~MODULE_OFFSET;
else { }
currentHook--;
ConsoleOutput("vnrcli:UnsafeInsertHookCode: FAILED: module not present");
return no;
}
hp.type &= ~MODULE_OFFSET;
}
BYTE* original;
if (MH_CreateHook((void*)hp.address, (void*)trampoline, (void**)&original) != MH_OK) return false;
{ void* thisPtr = (void*)this;
TextHook *it = hookman; void* funcPtr = (void*)((BYTE*)ProcessHook - (BYTE*)(trampoline + 19));
for (int i = 0; (i < currentHook) && it; it++) { // Check if there is a collision. DWORD dist = original - (trampoline + sizeof(common_hook)) - 4;
if (it->Address())
i++;
//it = hookman + i;
if (it == this)
continue;
if (it->Address() <= hp.address &&
it->Address() + it->Length() > hp.address) {
it->ClearHook();
break;
}
}
}
// Verify hp.address. memcpy(trampoline, common_hook, sizeof(common_hook));
if (!IthGetMemoryRange((LPCVOID)hp.address, nullptr, nullptr)) memcpy(trampoline + 10, &thisPtr, sizeof(void*));
{ memcpy(trampoline + 15, &funcPtr, sizeof(void*));
ConsoleOutput("NextHooker: FAILED: cannot access requested memory"); memcpy(trampoline + sizeof(common_hook), &dist, sizeof(dist));
return no;
}
memcpy(recover, common_hook, sizeof(common_hook)); if (MH_EnableHook((void*)hp.address) != MH_OK) return false;
void* thisPtr = (void*)this;
void* funcPtr = (void*)((BYTE*)ProcessHook - (BYTE*)(recover + 19));
memcpy(recover + 10, &thisPtr, sizeof(void*));
memcpy(recover + 15, &funcPtr, sizeof(void*));
BYTE *c = (BYTE *)hp.address,
*r = recover;
BYTE inst[] = // jichi 9/27/2013: Why 8? Only 5 bytes will be written using NtWriteVirtualMemory
{
0xe9, 0, 0, 0, 0, // jmp recover
0xcc, 0xcc, 0xcc // int3
};
void* relRecover = (void*)(recover - (BYTE*)hp.address - 5);
memcpy(inst + 1, &relRecover, sizeof(void*));
r += sizeof(common_hook);
hp.hook_len = 5;
int address = hp.address;
switch (MapInstruction(hp.address, (DWORD)r, hp.hook_len, hp.recover_len)) {
case -1:
ConsoleOutput("vnrcli:UnsafeInsertHookCode: FAILED: failed to map instruction");
return no;
case 0:
__asm
{
mov ecx,this
movzx eax,[ecx]hp.hook_len
movzx edx,[ecx]hp.recover_len
add edx,address
add eax,r
add eax,5
sub edx,eax
mov [eax-5],0xe9 // jichi 9/27/2013: 0xe9 is jump
mov [eax-4],edx
}
}
// jichi 9/27/2013: Save the original instructions in the memory
memcpy(original, (LPVOID)hp.address, hp.recover_len);
//Check if the new hook range conflict with existing ones. Clear older if conflict.
{
TextHook *it = hookman;
for (int i = 0; i < currentHook; it++) {
if (it->Address())
i++;
if (it == this)
continue;
if (it->Address() >= hp.address &&
it->Address() < hp.hook_len + hp.address) {
it->ClearHook();
break;
}
}
}
DWORD old; return true;
LPVOID addr = (void*)hp.address;
VirtualProtect(addr, sizeof(inst), PAGE_EXECUTE_READWRITE, &old);
memcpy(addr, inst, hp.recover_len);
FlushInstructionCache(GetCurrentProcess(), addr, hp.recover_len);
return 0;
} }
#endif // _WIN32 #endif // _WIN32
@ -478,132 +277,97 @@ DWORD WINAPI ReaderThread(LPVOID threadParam)
return 0; return 0;
} }
int TextHook::InsertReadCode() bool TextHook::InsertReadCode()
{ {
hp.hook_len = 0x40; RemoveHook(hp.address); // Artikash 8/25/2018: clear existing
//Check if the new hook range conflict with existing ones. Clear older if conflict.
TextHook *it = hookman;
for (int i = 0; i < currentHook; it++) {
if (it->Address())
i++;
if (it == this)
continue;
if ((it->Address() >= hp.address && it->Address() < hp.hook_len + hp.address) || (it->Address() <= hp.address && it->Address() + it->Length() > hp.address))
it->ClearHook();
}
if (!IthGetMemoryRange((LPCVOID)hp.address, 0, 0)) if (!IthGetMemoryRange((LPCVOID)hp.address, 0, 0))
{ {
ConsoleOutput("cannot access read address"); ConsoleOutput("NextHooker:InsertReadCode failed: cannot access read address");
return no; return false;
} }
hp.readerHandle = CreateThread(nullptr, 0, ReaderThread, this, 0, nullptr); hp.readerHandle = CreateThread(nullptr, 0, ReaderThread, this, 0, nullptr);
return yes; return true;
} }
int TextHook::InitHook(const HookParam &h, LPCSTR name, WORD set_flag) void TextHook::InitHook(const HookParam &h, LPCSTR name, WORD set_flag)
{ {
WaitForSingleObject(hmMutex, 0); WaitForSingleObject(hmMutex, 0);
hp = h; hp = h;
hp.type |= set_flag; hp.type |= set_flag;
if (name && name != hook_name) { if (name && name != hook_name) SetHookName(name);
SetHookName(name); ReleaseMutex(hmMutex);
}
currentHook++;
current_available = this+1;
while (current_available->Address())
current_available++;
ReleaseMutex(hmMutex);
return 1;
} }
int TextHook::RemoveHookCode() void TextHook::RemoveHookCode()
{ {
if (!hp.address) MH_DisableHook((void*)hp.address);
return no;
DWORD l = hp.hook_len;
memcpy((void*)hp.address, original, hp.recover_len);
FlushInstructionCache(GetCurrentProcess(), (void*)hp.address, hp.recover_len);
return yes;
} }
int TextHook::RemoveReadCode() void TextHook::RemoveReadCode()
{ {
if (!hp.address) return no;
TerminateThread(hp.readerHandle, 0); TerminateThread(hp.readerHandle, 0);
CloseHandle(hp.readerHandle); CloseHandle(hp.readerHandle);
return yes;
} }
int TextHook::ClearHook() void TextHook::ClearHook()
{ {
int err; WaitForSingleObject(hmMutex, 0);
WaitForSingleObject(hmMutex, 0); ConsoleOutput("NextHooker:RemoveHook: enter");
ConsoleOutput("vnrcli:RemoveHook: enter"); if (hp.type & DIRECT_READ) RemoveReadCode();
if (hp.type & DIRECT_READ) err = RemoveReadCode(); else RemoveHookCode();
else err = RemoveHookCode(); NotifyHookRemove(hp.address);
NotifyHookRemove(hp.address); if (hook_name) delete[] hook_name;
if (hook_name) { memset(this, 0, sizeof(TextHook)); // jichi 11/30/2013: This is the original code of ITH
delete[] hook_name; //if (current_available>this)
hook_name = nullptr; // current_available = this;
} currentHook--;
memset(this, 0, sizeof(TextHook)); // jichi 11/30/2013: This is the original code of ITH ConsoleOutput("NextHooker:RemoveHook: leave");
//if (current_available>this) ReleaseMutex(hmMutex);
// current_available = this;
currentHook--;
ConsoleOutput("vnrcli:RemoveHook: leave");
ReleaseMutex(hmMutex);
return err;
} }
int TextHook::SetHookName(LPCSTR name) void TextHook::SetHookName(LPCSTR name)
{ {
name_length = strlen(name) + 1; name_length = strlen(name) + 1;
if (hook_name) if (hook_name) delete[] hook_name;
delete[] hook_name; hook_name = new char[name_length];
hook_name = new char[name_length]; strcpy(hook_name, name);
//ITH_MEMSET_HEAP(hook_name, 0, sizeof(wchar_t) * name_length); // jichi 9/26/2013: zero memory
strcpy(hook_name, name);
return 0;
} }
int TextHook::GetLength(DWORD base, DWORD in) int TextHook::GetLength(DWORD base, DWORD in)
{ {
if (base == 0) if (base == 0)
return 0; return 0;
int len; int len;
switch (hp.length_offset) { switch (hp.length_offset) {
default: // jichi 12/26/2013: I should not put this default branch to the end default: // jichi 12/26/2013: I should not put this default branch to the end
len = *((int *)base + hp.length_offset); len = *((int *)base + hp.length_offset);
if (len >= 0) { if (len >= 0) {
if (hp.type & USING_UNICODE) if (hp.type & USING_UNICODE)
len <<= 1; len <<= 1;
break; break;
} }
else if (len != -1) else if (len != -1)
break; break;
//len == -1 then continue to case 0. //len == -1 then continue to case 0.
case 0: case 0:
if (hp.type & USING_UNICODE) if (hp.type & USING_UNICODE)
len = wcslen((const wchar_t *)in) << 1; len = wcslen((const wchar_t *)in) << 1;
else else
len = strlen((const char *)in); len = strlen((const char *)in);
break; break;
case 1: case 1:
if (hp.type & USING_UNICODE) if (hp.type & USING_UNICODE)
len = 2; len = 2;
else { else {
if (hp.type & BIG_ENDIAN) if (hp.type & BIG_ENDIAN)
in >>= 8; in >>= 8;
len = LeadByteTable[in & 0xff]; //Slightly faster than IsDBCSLeadByte len = LeadByteTable[in & 0xff]; //Slightly faster than IsDBCSLeadByte
} }
break; break;
} }
// jichi 12/25/2013: This function originally return -1 if failed // jichi 12/25/2013: This function originally return -1 if failed
//return len; //return len;
return max(0, len); return max(0, len);
} }
// EOF // EOF

View File

@ -18,47 +18,33 @@ extern DWORD trigger;
class TextHook class TextHook
{ {
int InsertHookCode(); bool InsertHookCode();
int InsertReadCode(); bool InsertReadCode();
int UnsafeInsertHookCode(); bool UnsafeInsertHookCode();
DWORD UnsafeSend(DWORD dwDataBase, DWORD dwRetn); DWORD UnsafeSend(DWORD dwDataBase, DWORD dwRetn);
int RemoveHookCode(); void RemoveHookCode();
int RemoveReadCode(); void RemoveReadCode();
int SetHookName(LPCSTR name); void SetHookName(LPCSTR name);
public: public:
HookParam hp; HookParam hp;
LPSTR hook_name; LPSTR hook_name;
int name_length; int name_length;
BYTE recover[0x68 - sizeof(HookParam)]; BYTE trampoline[80];
BYTE original[0x10];
unsigned __int64 Address() const { return hp.address; } bool InsertHook();
DWORD Type() const { return hp.type; } void InitHook(const HookParam &hp, LPCSTR name = 0, WORD set_flag = 0);
WORD Length() const { return hp.hook_len; }
LPSTR Name() const { return hook_name; }
int NameLength() const { return name_length; }
int InsertHook();
int InitHook(const HookParam &hp, LPCSTR name = 0, WORD set_flag = 0);
DWORD Send(DWORD dwDataBase, DWORD dwRetn); DWORD Send(DWORD dwDataBase, DWORD dwRetn);
int ClearHook(); void ClearHook();
int GetLength(DWORD base, DWORD in); // jichi 12/25/2013: Return 0 if failed int GetLength(DWORD base, DWORD in); // jichi 12/25/2013: Return 0 if failed
}; };
// jichi 1/16/2015: Though called max hook, it means max number of text threads enum { MAX_HOOK = 300 };
enum { MAX_HOOK = 64 };
enum { HOOK_SECTION_SIZE = MAX_HOOK * sizeof(TextHook) * 2, HOOK_BUFFER_SIZE = MAX_HOOK * sizeof(TextHook) }; enum { HOOK_SECTION_SIZE = MAX_HOOK * sizeof(TextHook) * 2, HOOK_BUFFER_SIZE = MAX_HOOK * sizeof(TextHook) };
extern TextHook *hookman, extern TextHook *hookman;
*current_available;
extern bool running, extern bool running;
live;
extern HANDLE hookPipe, extern HANDLE hookPipe, hmMutex;
hmMutex;
DWORD WINAPI PipeManager(LPVOID unused);
enum : int { yes = 0, no = 1 };
// EOF // EOF

View File

@ -10,29 +10,18 @@
#include "main.h" #include "main.h"
#include "defs.h" #include "defs.h"
#include "MinHook.h"
#include "pipe.h"
#include "engine/engine.h" #include "engine/engine.h"
#include "engine/match.h" #include "engine/match.h"
#include "hijack/texthook.h" #include "hijack/texthook.h"
#include "util/growl.h" #include "util/growl.h"
// Global variables
// jichi 6/3/2014: memory range of the current module
DWORD processStartAddress,
processStopAddress;
WCHAR hm_section[0x100];
HANDLE hSection; HANDLE hSection;
bool running; bool running;
int currentHook = 0, int currentHook = 0, userhookCount = 0;
user_hook_count = 0;
DWORD trigger = 0; DWORD trigger = 0;
HANDLE HANDLE hmMutex;
hFile,
hMutex,
hmMutex;
void CreatePipe();
BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused) BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
{ {
@ -47,19 +36,11 @@ BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
// jichi 9/25/2013: Interprocedural communication with vnrsrv. // jichi 9/25/2013: Interprocedural communication with vnrsrv.
hSection = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_EXECUTE_READWRITE, 0, HOOK_SECTION_SIZE, (ITH_SECTION_ + std::to_wstring(GetCurrentProcessId())).c_str()); hSection = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_EXECUTE_READWRITE, 0, HOOK_SECTION_SIZE, (ITH_SECTION_ + std::to_wstring(GetCurrentProcessId())).c_str());
::hookman = (TextHook*)MapViewOfFile(hSection, FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE, 0, 0, HOOK_BUFFER_SIZE); ::hookman = (TextHook*)MapViewOfFile(hSection, FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE, 0, 0, HOOK_BUFFER_SIZE);
memset(::hookman, 0, HOOK_BUFFER_SIZE);
::processStartAddress = ::processStopAddress = (DWORD)GetModuleHandleW(nullptr); MH_Initialize();
MEMORY_BASIC_INFORMATION info;
do
{
VirtualQuery((void*)::processStopAddress, &info, sizeof(info));
::processStopAddress = (DWORD)info.BaseAddress + info.RegionSize;
} while (info.Protect > PAGE_NOACCESS);
processStopAddress -= info.RegionSize;
::running = true; ::running = true;
::current_available = ::hookman;
CreatePipe(); CreatePipe();
} }
@ -67,14 +48,13 @@ BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
case DLL_PROCESS_DETACH: case DLL_PROCESS_DETACH:
{ {
::running = false; ::running = false;
MH_Uninitialize();
for (TextHook *man = ::hookman; man < ::hookman + MAX_HOOK; man++) if (man->Address()) man->ClearHook(); for (TextHook *man = ::hookman; man < ::hookman + MAX_HOOK; man++) if (man->hp.address) man->ClearHook();
//if (ith_has_section) //if (ith_has_section)
UnmapViewOfFile(::hookman); UnmapViewOfFile(::hookman);
CloseHandle(::hookPipe); CloseHandle(::hookPipe);
CloseHandle(hSection); CloseHandle(hSection);
CloseHandle(hMutex);
CloseHandle(hmMutex); CloseHandle(hmMutex);
//} ITH_EXCEPT {} //} ITH_EXCEPT {}
} }
@ -84,47 +64,32 @@ BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
} }
//extern "C" { //extern "C" {
DWORD NewHook(const HookParam &hp, LPCSTR lpname, DWORD flag) void NewHook(const HookParam &hp, LPCSTR lpname, DWORD flag)
{ {
std::string name = lpname; std::string name = lpname;
int current = ::current_available - ::hookman; if (++currentHook < MAX_HOOK)
if (current < MAX_HOOK) { {
//flag &= 0xffff; if (name[0] == '\0') name = "UserHook" + std::to_string(userhookCount++);
//if ((flag & HOOK_AUXILIARY) == 0) ConsoleOutput(("NextHooker: try inserting hook: " + name).c_str());
flag |= HOOK_ADDITIONAL;
if (name[0] == '\0')
{
name = "UserHook" + std::to_string(user_hook_count++);
}
ConsoleOutput(("vnrcli:NewHook: try inserting hook: " + name).c_str());
// jichi 7/13/2014: This function would raise when too many hooks added // jichi 7/13/2014: This function would raise when too many hooks added
::hookman[current].InitHook(hp, name.c_str(), flag & 0xffff); ::hookman[currentHook].InitHook(hp, name.c_str(), flag);
if (::hookman[currentHook].InsertHook()) ConsoleOutput(("NextHooker: inserted hook: " + name).c_str());
if (::hookman[current].InsertHook() == 0) { else ConsoleOutput("NextHooker:WARNING: failed to insert hook");
ConsoleOutput(("vnrcli:NewHook: inserted hook: " + name).c_str());
NotifyHookInsert(hp, name.c_str());
}
else
ConsoleOutput("vnrcli:NewHook:WARNING: failed to insert hook");
} }
return 0; else ConsoleOutput("NextHooker: too many hooks: can't insert");
} }
DWORD RemoveHook(unsigned __int64 addr)
void RemoveHook(unsigned __int64 addr)
{ {
for (int i = 0; i < MAX_HOOK; i++) for (int i = 0; i < MAX_HOOK; i++)
if (::hookman[i].Address() == addr) { if (abs((long long)(::hookman[i].hp.address - addr)) < 9)
::hookman[i].ClearHook(); ::hookman[i].ClearHook();
return 0;
}
return 0;
} }
DWORD SwitchTrigger(DWORD t) void SwitchTrigger(DWORD t)
{ {
trigger = t; trigger = t;
return 0;
} }
// EOF // EOF

View File

@ -6,20 +6,10 @@
#include "common.h" #include "common.h"
#include "types.h" #include "types.h"
#include "pipe.h"
void ConsoleOutput(LPCSTR text); // jichi 12/25/2013: Used to return length of sent text void NewHook(const HookParam &hp, LPCSTR name, DWORD flag = HOOK_ENGINE);
void NotifyHookInsert(HookParam hp, LPCSTR name); void RemoveHook(unsigned __int64 addr);
void NotifyHookRemove(unsigned __int64 addr); void SwitchTrigger(DWORD on);
DWORD NewHook(const HookParam &hp, LPCSTR name, DWORD flag = HOOK_ENGINE);
DWORD RemoveHook(unsigned __int64 addr);
DWORD SwitchTrigger(DWORD on);
// 10/14/2014 jichi: disable GDI hooks
void EnableGDIHooks();
void EnableGDIPlusHooks();
void DisableGDIHooks();
void DisableGDIPlusHooks();
bool GDIHooksEnabled();
bool GDIPlusHooksEnabled();
// EOF // EOF

View File

@ -7,7 +7,7 @@
# pragma warning (disable:4100) // C4100: unreference formal parameter # pragma warning (disable:4100) // C4100: unreference formal parameter
#endif // _MSC_VER #endif // _MSC_VER
#include "types.h" #include "pipe.h"
#include "main.h" #include "main.h"
#include "hijack/texthook.h" #include "hijack/texthook.h"
#include "engine/match.h" #include "engine/match.h"
@ -52,7 +52,7 @@ void CreatePipe()
ReleaseMutex(pipeAcquisitionMutex); ReleaseMutex(pipeAcquisitionMutex);
CloseHandle(pipeAcquisitionMutex); CloseHandle(pipeAcquisitionMutex);
ConsoleOutput("vnrcli:WaitForPipe: pipe connected"); ConsoleOutput("NextHooker: pipe connected");
#ifdef _WIN64 #ifdef _WIN64
ConsoleOutput("Hooks don't work on x64, only read codes work. Engine disabled."); ConsoleOutput("Hooks don't work on x64, only read codes work. Engine disabled.");
#else #else
@ -71,9 +71,7 @@ void CreatePipe()
case HOST_COMMAND_REMOVE_HOOK: case HOST_COMMAND_REMOVE_HOOK:
{ {
auto info = *(RemoveHookCmd*)buffer; auto info = *(RemoveHookCmd*)buffer;
for (int i = 0; i < MAX_HOOK; ++i) RemoveHook(info.address);
if (::hookman[i].Address() == info.address)
::hookman[i].ClearHook();
} }
break; break;
case HOST_COMMAND_DETACH: case HOST_COMMAND_DETACH:
@ -96,18 +94,6 @@ void ConsoleOutput(LPCSTR text)
WriteFile(::hookPipe, &info, strlen(text) + sizeof(info), DUMMY, nullptr); WriteFile(::hookPipe, &info, strlen(text) + sizeof(info), DUMMY, nullptr);
} }
void NotifyHookInsert(HookParam hp, LPCSTR name)
{
//BYTE buffer[PIPE_BUFFER_SIZE];
//*(DWORD*)buffer = HOST_NOTIFICATION;
//*(DWORD*)(buffer + sizeof(DWORD)) = HOST_NOTIFICATION_NEWHOOK;
//*(HookParam*)(buffer + sizeof(DWORD) * 2) = hp;
//strcpy((char*)buffer + sizeof(DWORD) * 2 + sizeof(HookParam), name);
//DWORD unused;
//WriteFile(::hookPipe, buffer, strlen(name) + sizeof(DWORD) * 2 + sizeof(HookParam), &unused, nullptr);
//return;
}
void NotifyHookRemove(unsigned __int64 addr) void NotifyHookRemove(unsigned __int64 addr)
{ {
auto info = HookRemovedNotif(addr); auto info = HookRemovedNotif(addr);

8
vnrhook/pipe.h Normal file
View File

@ -0,0 +1,8 @@
#pragma once
#include "common.h"
#include "types.h"
void CreatePipe();
void NotifyHookRemove(unsigned __int64 addr);
void ConsoleOutput(LPCSTR text); // jichi 12/25/2013: Used to return length of sent text