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 "../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
{
struct ProcessRecord
@ -21,7 +24,6 @@ namespace
ThreadEventCallback OnCreate, OnRemove;
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<DWORD, ProcessRecord> processRecordsByIds;
@ -228,7 +230,7 @@ namespace Host
WaitForSingleObject(pr.sectionMutex, 0);
const TextHook* hooks = (const TextHook*)pr.sectionMap;
for (int i = 0; i < MAX_HOOK; ++i)
if (hooks[i].Address() == addr)
if (hooks[i].hp.address == addr)
ret = hooks[i].hp;
ReleaseMutex(pr.sectionMutex);
return ret;
@ -246,10 +248,10 @@ namespace Host
WaitForSingleObject(pr.sectionMutex, 0);
const TextHook* hooks = (const TextHook*)pr.sectionMap;
for (int i = 0; i < MAX_HOOK; ++i)
if (hooks[i].Address() == addr)
if (hooks[i].hp.address == addr)
{
buffer.resize(hooks[i].NameLength());
ReadProcessMemory(pr.processHandle, hooks[i].Name(), &buffer[0], hooks[i].NameLength(), nullptr);
buffer.resize(hooks[i].name_length);
ReadProcessMemory(pr.processHandle, hooks[i].hook_name, &buffer[0], hooks[i].name_length, nullptr);
}
ReleaseMutex(pr.sectionMutex);
USES_CONVERSION;

View File

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

View File

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

View File

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

View File

@ -10,218 +10,92 @@
#endif // _MSC_VER
#include "hijack/texthook.h"
#include "MinHook.h"
#include "engine/match.h"
#include "except.h"
#include "main.h"
#include "pipe.h"
#include "const.h"
#include "ithsys/ithsys.h"
#include "disasm/disasm.h"
#include "growl.h"
//#include "winseh/winseh.h"
#include <Psapi.h>
//#define ConsoleOutput(...) (void)0 // jichi 9/17/2013: I don't need this ><
// - 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;
TextHook *hookman;
// - Unnamed helpers -
#ifndef _WIN64
namespace { // unnamed
//provide const time hook entry.
int userhook_count;
const BYTE common_hook[] = {
0x9c, // pushfd
0x60, // pushad
0x9c, // pushfd
0x8d,0x54,0x24,0x28, // lea edx,[esp+0x28] ; esp value
0x8b,0x32, // mov esi,[edx] ; return address
0xb9, 0,0,0,0, // mov ecx, $ ; pointer to TextHook
0xe8, 0,0,0,0, // call @hook
0x9d, // popfd
0x61, // popad
0x9d // popfd
};
const BYTE common_hook[] = {
0x9c, // pushfd
0x60, // pushad
0x9c, // pushfd
0x8d,0x54,0x24,0x28, // lea edx,[esp+0x28] ; esp value
0x8b,0x32, // mov esi,[edx] ; return address
0xb9, 0,0,0,0, // mov ecx, $ ; pointer to TextHook
0xe8, 0,0,0,0, // call @hook
0x9d, // popfd
0x61, // popad
0x9d, // popfd
0xe9 // jmp @original
};
/**
* jichi 7/19/2014
*
* @param original_addr
* @param new_addr
* @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;
}
DWORD Hash(std::wstring module)
{
DWORD hash = 0;
for (auto i : module) hash = _rotr(hash, 7) + i;
return hash;
}
::memcpy(c, r, l);
if (*r >= 0x70 && *r < 0x80) {
c[0] = 0xf;
c[1] = *r + 0x10;
c += 6;
__asm
{
mov eax,r
add eax,2
movsx edx,byte ptr [eax-1]
add edx,eax
mov eax,c
sub edx,eax
mov [eax-4],edx
}
} 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
//jmp back
DWORD GetModuleBase(DWORD hash)
{
HMODULE allModules[1000];
DWORD size;
EnumProcessModules(GetCurrentProcess(), allModules, sizeof(allModules), &size);
wchar_t name[MAX_PATH];
for (int i = 0; i < size / sizeof(HMODULE); ++i)
{
GetModuleFileNameW(allModules[i], name, MAX_PATH);
_wcslwr(name);
if (Hash(wcsrchr(name, L'\\') + 1) == hash) return (DWORD)allModules[i];
}
return 0;
}
//copy original instruction
//jmp back
DWORD GetModuleBase(DWORD hash)
{
__asm
{
mov eax,fs:[0x30]
mov eax,[eax+0xc]
mov esi,[eax+0x14]
mov edi,_wcslwr
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
}
}
__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
#endif // _WIN32
// - TextHook methods -
int TextHook::InsertHook()
bool TextHook::InsertHook()
{
int ok = 1;
//ConsoleOutput("vnrcli:InsertHook: enter");
WaitForSingleObject(hmMutex, 0);
if (hp.type & DIRECT_READ) ok = InsertReadCode();
bool ret = false;
//ConsoleOutput("vnrcli:InsertHook: enter");
WaitForSingleObject(hmMutex, 0);
if (hp.type & DIRECT_READ) ret = InsertReadCode();
#ifndef _WIN64
else ok = InsertHookCode();
else ret = InsertHookCode();
#endif
ReleaseMutex(hmMutex);
//ConsoleOutput("vnrcli:InsertHook: leave");
return ok;
ReleaseMutex(hmMutex);
//ConsoleOutput("vnrcli:InsertHook: leave");
return ret;
}
#ifndef _WIN64
@ -234,211 +108,136 @@ int TextHook::InsertHook()
// - dwRetn: the return address of the hook
DWORD TextHook::Send(DWORD dwDataBase, DWORD dwRetn)
{
DWORD ret = 0;
ITH_WITH_SEH(ret = UnsafeSend(dwDataBase, dwRetn));
return ret;
DWORD ret = 0;
ITH_WITH_SEH(ret = UnsafeSend(dwDataBase, dwRetn));
return ret;
}
DWORD TextHook::UnsafeSend(DWORD dwDataBase, DWORD dwRetn)
{
DWORD dwCount,
dwAddr,
dwDataIn,
dwSplit;
BYTE pbData[PIPE_BUFFER_SIZE];
DWORD dwType = hp.type;
DWORD dwCount,
dwAddr,
dwDataIn,
dwSplit;
BYTE pbData[PIPE_BUFFER_SIZE];
DWORD dwType = hp.type;
dwAddr = hp.address;
dwAddr = hp.address;
/** jichi 12/24/2014
* @param addr function address
* @param frame real address of the function, supposed to be the same as addr
* @param stack address of current stack - 4
* @return If success, which is reverted
*/
if (::trigger)
::trigger = Engine::InsertDynamicHook((LPVOID)dwAddr, *(DWORD *)(dwDataBase - 0x1c), *(DWORD *)(dwDataBase-0x18));
/** jichi 12/24/2014
* @param addr function address
* @param frame real address of the function, supposed to be the same as addr
* @param stack address of current stack - 4
* @return If success, which is reverted
*/
if (::trigger)
::trigger = Engine::InsertDynamicHook((LPVOID)dwAddr, *(DWORD *)(dwDataBase - 0x1c), *(DWORD *)(dwDataBase - 0x18));
// jichi 10/24/2014: generic hook function
if (hp.hook_fun && !hp.hook_fun(dwDataBase, &hp))
hp.hook_fun = nullptr;
// jichi 10/24/2014: generic hook function
if (hp.hook_fun && !hp.hook_fun(dwDataBase, &hp))
hp.hook_fun = nullptr;
if (dwType & HOOK_EMPTY) // jichi 10/24/2014: dummy hook only for dynamic hook
return 0;
if (dwType & HOOK_EMPTY) // jichi 10/24/2014: dummy hook only for dynamic hook
return 0;
dwCount = 0;
dwSplit = 0;
dwDataIn = *(DWORD *)(dwDataBase + hp.offset); // default value
dwCount = 0;
dwSplit = 0;
dwDataIn = *(DWORD *)(dwDataBase + hp.offset); // default value
if (hp.text_fun) {
hp.text_fun(dwDataBase, &hp, 0, &dwDataIn, &dwSplit, &dwCount);
} else {
if (dwDataIn == 0)
return 0;
if (dwType & FIXING_SPLIT)
dwSplit = FIXED_SPLIT_VALUE; // fuse all threads, and prevent floating
else if (dwType & USING_SPLIT) {
dwSplit = *(DWORD *)(dwDataBase + hp.split);
if (dwType & SPLIT_INDIRECT) {
if (IthGetMemoryRange((LPVOID)(dwSplit + hp.split_index), 0, 0))
dwSplit = *(DWORD *)(dwSplit + hp.split_index);
else
return 0;
}
}
if (dwType & DATA_INDIRECT) {
if (IthGetMemoryRange((LPVOID)(dwDataIn + hp.index), 0, 0))
dwDataIn = *(DWORD *)(dwDataIn + hp.index);
else
return 0;
}
dwCount = GetLength(dwDataBase, dwDataIn);
}
// jichi 12/25/2013: validate data size
if (dwCount == 0 || dwCount > PIPE_BUFFER_SIZE - sizeof(ThreadParam))
return 0;
if (hp.text_fun) {
hp.text_fun(dwDataBase, &hp, 0, &dwDataIn, &dwSplit, &dwCount);
}
else {
if (dwDataIn == 0)
return 0;
if (dwType & FIXING_SPLIT)
dwSplit = FIXED_SPLIT_VALUE; // fuse all threads, and prevent floating
else if (dwType & USING_SPLIT) {
dwSplit = *(DWORD *)(dwDataBase + hp.split);
if (dwType & SPLIT_INDIRECT) {
if (IthGetMemoryRange((LPVOID)(dwSplit + hp.split_index), 0, 0))
dwSplit = *(DWORD *)(dwSplit + hp.split_index);
else
return 0;
}
}
if (dwType & DATA_INDIRECT) {
if (IthGetMemoryRange((LPVOID)(dwDataIn + hp.index), 0, 0))
dwDataIn = *(DWORD *)(dwDataIn + hp.index);
else
return 0;
}
dwCount = GetLength(dwDataBase, dwDataIn);
}
// jichi 12/25/2013: validate data size
if (dwCount == 0 || dwCount > PIPE_BUFFER_SIZE - sizeof(ThreadParam))
return 0;
if (hp.length_offset == 1) {
dwDataIn &= 0xffff;
if ((dwType & BIG_ENDIAN) && (dwDataIn >> 8))
dwDataIn = _byteswap_ushort(dwDataIn & 0xffff);
if (dwCount == 1)
dwDataIn &= 0xff;
*(WORD *)(pbData + sizeof(ThreadParam)) = dwDataIn & 0xffff;
}
else
::memcpy(pbData + sizeof(ThreadParam), (void *)dwDataIn, dwCount);
if (hp.length_offset == 1) {
dwDataIn &= 0xffff;
if ((dwType & BIG_ENDIAN) && (dwDataIn >> 8))
dwDataIn = _byteswap_ushort(dwDataIn & 0xffff);
if (dwCount == 1)
dwDataIn &= 0xff;
*(WORD *)(pbData + sizeof(ThreadParam)) = dwDataIn & 0xffff;
}
else
::memcpy(pbData + sizeof(ThreadParam), (void *)dwDataIn, dwCount);
// jichi 10/14/2014: Add filter function
if (hp.filter_fun && !hp.filter_fun(pbData + sizeof(ThreadParam), &dwCount, &hp, 0) || dwCount <= 0) {
return 0;
}
// jichi 10/14/2014: Add filter function
if (hp.filter_fun && !hp.filter_fun(pbData + sizeof(ThreadParam), &dwCount, &hp, 0) || dwCount <= 0) {
return 0;
}
if (dwType & (NO_CONTEXT|FIXING_SPLIT))
dwRetn = 0;
if (dwType & (NO_CONTEXT | FIXING_SPLIT))
dwRetn = 0;
*(ThreadParam*)pbData = { GetCurrentProcessId(), dwAddr, dwRetn, dwSplit };
if (dwCount) {
if (dwCount) {
DWORD unused;
//CliLockPipe();
WriteFile(::hookPipe, pbData, dwCount + sizeof(ThreadParam), &unused, nullptr);
//CliUnlockPipe();
}
return 0;
//CliLockPipe();
WriteFile(::hookPipe, pbData, dwCount + sizeof(ThreadParam), &unused, nullptr);
//CliUnlockPipe();
}
return 0;
}
int TextHook::InsertHookCode()
bool TextHook::InsertHookCode()
{
DWORD ret = no;
// jichi 9/17/2013: might raise 0xC0000005 AccessViolationException on win7
ITH_WITH_SEH(ret = UnsafeInsertHookCode());
//if (ret == no)
// ITH_WARN(L"Failed to insert hook");
return ret;
bool ret = false;
// jichi 9/17/2013: might raise 0xC0000005 AccessViolationException on win7
__try { ret = UnsafeInsertHookCode(); }
__except (1) {};
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 (DWORD base = GetModuleBase(hp.module)) {
hp.address += base;
}
else {
currentHook--;
ConsoleOutput("vnrcli:UnsafeInsertHookCode: FAILED: module not present");
return no;
}
hp.type &= ~MODULE_OFFSET;
}
if (hp.module && (hp.type & MODULE_OFFSET)) // Map hook offset to real address.
{
if (DWORD base = GetModuleBase(hp.module)) hp.address += base;
else return ConsoleOutput("NextHooker: UnsafeInsertHookCode: FAILED: module not present"), false;
hp.type &= ~MODULE_OFFSET;
}
BYTE* original;
if (MH_CreateHook((void*)hp.address, (void*)trampoline, (void**)&original) != MH_OK) return false;
{
TextHook *it = hookman;
for (int i = 0; (i < currentHook) && it; it++) { // Check if there is a collision.
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;
}
}
}
void* thisPtr = (void*)this;
void* funcPtr = (void*)((BYTE*)ProcessHook - (BYTE*)(trampoline + 19));
DWORD dist = original - (trampoline + sizeof(common_hook)) - 4;
// Verify hp.address.
if (!IthGetMemoryRange((LPCVOID)hp.address, nullptr, nullptr))
{
ConsoleOutput("NextHooker: FAILED: cannot access requested memory");
return no;
}
memcpy(trampoline, common_hook, sizeof(common_hook));
memcpy(trampoline + 10, &thisPtr, sizeof(void*));
memcpy(trampoline + 15, &funcPtr, sizeof(void*));
memcpy(trampoline + sizeof(common_hook), &dist, sizeof(dist));
memcpy(recover, common_hook, sizeof(common_hook));
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;
}
}
}
if (MH_EnableHook((void*)hp.address) != MH_OK) return false;
DWORD old;
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;
return true;
}
#endif // _WIN32
@ -478,132 +277,97 @@ DWORD WINAPI ReaderThread(LPVOID threadParam)
return 0;
}
int TextHook::InsertReadCode()
bool TextHook::InsertReadCode()
{
hp.hook_len = 0x40;
//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();
}
RemoveHook(hp.address); // Artikash 8/25/2018: clear existing
if (!IthGetMemoryRange((LPCVOID)hp.address, 0, 0))
{
ConsoleOutput("cannot access read address");
return no;
ConsoleOutput("NextHooker:InsertReadCode failed: cannot access read address");
return false;
}
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);
hp = h;
hp.type |= set_flag;
if (name && name != hook_name) {
SetHookName(name);
}
currentHook++;
current_available = this+1;
while (current_available->Address())
current_available++;
ReleaseMutex(hmMutex);
return 1;
WaitForSingleObject(hmMutex, 0);
hp = h;
hp.type |= set_flag;
if (name && name != hook_name) SetHookName(name);
ReleaseMutex(hmMutex);
}
int TextHook::RemoveHookCode()
void TextHook::RemoveHookCode()
{
if (!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;
MH_DisableHook((void*)hp.address);
}
int TextHook::RemoveReadCode()
void TextHook::RemoveReadCode()
{
if (!hp.address) return no;
TerminateThread(hp.readerHandle, 0);
CloseHandle(hp.readerHandle);
return yes;
}
int TextHook::ClearHook()
void TextHook::ClearHook()
{
int err;
WaitForSingleObject(hmMutex, 0);
ConsoleOutput("vnrcli:RemoveHook: enter");
if (hp.type & DIRECT_READ) err = RemoveReadCode();
else err = RemoveHookCode();
NotifyHookRemove(hp.address);
if (hook_name) {
delete[] hook_name;
hook_name = nullptr;
}
memset(this, 0, sizeof(TextHook)); // jichi 11/30/2013: This is the original code of ITH
//if (current_available>this)
// current_available = this;
currentHook--;
ConsoleOutput("vnrcli:RemoveHook: leave");
ReleaseMutex(hmMutex);
return err;
WaitForSingleObject(hmMutex, 0);
ConsoleOutput("NextHooker:RemoveHook: enter");
if (hp.type & DIRECT_READ) RemoveReadCode();
else RemoveHookCode();
NotifyHookRemove(hp.address);
if (hook_name) delete[] hook_name;
memset(this, 0, sizeof(TextHook)); // jichi 11/30/2013: This is the original code of ITH
//if (current_available>this)
// current_available = this;
currentHook--;
ConsoleOutput("NextHooker:RemoveHook: leave");
ReleaseMutex(hmMutex);
}
int TextHook::SetHookName(LPCSTR name)
void TextHook::SetHookName(LPCSTR name)
{
name_length = strlen(name) + 1;
if (hook_name)
delete[] hook_name;
hook_name = new char[name_length];
//ITH_MEMSET_HEAP(hook_name, 0, sizeof(wchar_t) * name_length); // jichi 9/26/2013: zero memory
strcpy(hook_name, name);
return 0;
name_length = strlen(name) + 1;
if (hook_name) delete[] hook_name;
hook_name = new char[name_length];
strcpy(hook_name, name);
}
int TextHook::GetLength(DWORD base, DWORD in)
{
if (base == 0)
return 0;
int len;
switch (hp.length_offset) {
default: // jichi 12/26/2013: I should not put this default branch to the end
len = *((int *)base + hp.length_offset);
if (len >= 0) {
if (hp.type & USING_UNICODE)
len <<= 1;
break;
}
else if (len != -1)
break;
//len == -1 then continue to case 0.
case 0:
if (hp.type & USING_UNICODE)
len = wcslen((const wchar_t *)in) << 1;
else
len = strlen((const char *)in);
break;
case 1:
if (hp.type & USING_UNICODE)
len = 2;
else {
if (hp.type & BIG_ENDIAN)
in >>= 8;
len = LeadByteTable[in & 0xff]; //Slightly faster than IsDBCSLeadByte
}
break;
}
// jichi 12/25/2013: This function originally return -1 if failed
//return len;
return max(0, len);
if (base == 0)
return 0;
int len;
switch (hp.length_offset) {
default: // jichi 12/26/2013: I should not put this default branch to the end
len = *((int *)base + hp.length_offset);
if (len >= 0) {
if (hp.type & USING_UNICODE)
len <<= 1;
break;
}
else if (len != -1)
break;
//len == -1 then continue to case 0.
case 0:
if (hp.type & USING_UNICODE)
len = wcslen((const wchar_t *)in) << 1;
else
len = strlen((const char *)in);
break;
case 1:
if (hp.type & USING_UNICODE)
len = 2;
else {
if (hp.type & BIG_ENDIAN)
in >>= 8;
len = LeadByteTable[in & 0xff]; //Slightly faster than IsDBCSLeadByte
}
break;
}
// jichi 12/25/2013: This function originally return -1 if failed
//return len;
return max(0, len);
}
// EOF

View File

@ -18,47 +18,33 @@ extern DWORD trigger;
class TextHook
{
int InsertHookCode();
int InsertReadCode();
int UnsafeInsertHookCode();
bool InsertHookCode();
bool InsertReadCode();
bool UnsafeInsertHookCode();
DWORD UnsafeSend(DWORD dwDataBase, DWORD dwRetn);
int RemoveHookCode();
int RemoveReadCode();
int SetHookName(LPCSTR name);
void RemoveHookCode();
void RemoveReadCode();
void SetHookName(LPCSTR name);
public:
HookParam hp;
LPSTR hook_name;
int name_length;
BYTE recover[0x68 - sizeof(HookParam)];
BYTE original[0x10];
BYTE trampoline[80];
unsigned __int64 Address() const { return hp.address; }
DWORD Type() const { return hp.type; }
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);
bool InsertHook();
void InitHook(const HookParam &hp, LPCSTR name = 0, WORD set_flag = 0);
DWORD Send(DWORD dwDataBase, DWORD dwRetn);
int ClearHook();
void ClearHook();
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 = 64 };
enum { MAX_HOOK = 300 };
enum { HOOK_SECTION_SIZE = MAX_HOOK * sizeof(TextHook) * 2, HOOK_BUFFER_SIZE = MAX_HOOK * sizeof(TextHook) };
extern TextHook *hookman,
*current_available;
extern TextHook *hookman;
extern bool running,
live;
extern bool running;
extern HANDLE hookPipe,
hmMutex;
DWORD WINAPI PipeManager(LPVOID unused);
enum : int { yes = 0, no = 1 };
extern HANDLE hookPipe, hmMutex;
// EOF

View File

@ -10,29 +10,18 @@
#include "main.h"
#include "defs.h"
#include "MinHook.h"
#include "pipe.h"
#include "engine/engine.h"
#include "engine/match.h"
#include "hijack/texthook.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;
bool running;
int currentHook = 0,
user_hook_count = 0;
int currentHook = 0, userhookCount = 0;
DWORD trigger = 0;
HANDLE
hFile,
hMutex,
hmMutex;
void CreatePipe();
HANDLE hmMutex;
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.
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);
memset(::hookman, 0, HOOK_BUFFER_SIZE);
::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;
MH_Initialize();
::running = true;
::current_available = ::hookman;
CreatePipe();
}
@ -67,14 +48,13 @@ BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
case DLL_PROCESS_DETACH:
{
::running = false;
for (TextHook *man = ::hookman; man < ::hookman + MAX_HOOK; man++) if (man->Address()) man->ClearHook();
MH_Uninitialize();
for (TextHook *man = ::hookman; man < ::hookman + MAX_HOOK; man++) if (man->hp.address) man->ClearHook();
//if (ith_has_section)
UnmapViewOfFile(::hookman);
CloseHandle(::hookPipe);
CloseHandle(hSection);
CloseHandle(hMutex);
CloseHandle(hmMutex);
//} ITH_EXCEPT {}
}
@ -84,47 +64,32 @@ BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
}
//extern "C" {
DWORD NewHook(const HookParam &hp, LPCSTR lpname, DWORD flag)
void NewHook(const HookParam &hp, LPCSTR lpname, DWORD flag)
{
std::string name = lpname;
int current = ::current_available - ::hookman;
if (current < MAX_HOOK) {
//flag &= 0xffff;
//if ((flag & HOOK_AUXILIARY) == 0)
flag |= HOOK_ADDITIONAL;
if (name[0] == '\0')
{
name = "UserHook" + std::to_string(user_hook_count++);
}
ConsoleOutput(("vnrcli:NewHook: try inserting hook: " + name).c_str());
if (++currentHook < MAX_HOOK)
{
if (name[0] == '\0') name = "UserHook" + std::to_string(userhookCount++);
ConsoleOutput(("NextHooker: try inserting hook: " + name).c_str());
// jichi 7/13/2014: This function would raise when too many hooks added
::hookman[current].InitHook(hp, name.c_str(), flag & 0xffff);
if (::hookman[current].InsertHook() == 0) {
ConsoleOutput(("vnrcli:NewHook: inserted hook: " + name).c_str());
NotifyHookInsert(hp, name.c_str());
}
else
ConsoleOutput("vnrcli:NewHook:WARNING: failed to insert hook");
::hookman[currentHook].InitHook(hp, name.c_str(), flag);
if (::hookman[currentHook].InsertHook()) ConsoleOutput(("NextHooker: inserted hook: " + name).c_str());
else ConsoleOutput("NextHooker: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++)
if (::hookman[i].Address() == addr) {
if (abs((long long)(::hookman[i].hp.address - addr)) < 9)
::hookman[i].ClearHook();
return 0;
}
return 0;
}
DWORD SwitchTrigger(DWORD t)
void SwitchTrigger(DWORD t)
{
trigger = t;
return 0;
}
// EOF

View File

@ -6,20 +6,10 @@
#include "common.h"
#include "types.h"
#include "pipe.h"
void ConsoleOutput(LPCSTR text); // jichi 12/25/2013: Used to return length of sent text
void NotifyHookInsert(HookParam hp, LPCSTR name);
void NotifyHookRemove(unsigned __int64 addr);
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();
void NewHook(const HookParam &hp, LPCSTR name, DWORD flag = HOOK_ENGINE);
void RemoveHook(unsigned __int64 addr);
void SwitchTrigger(DWORD on);
// EOF

View File

@ -7,7 +7,7 @@
# pragma warning (disable:4100) // C4100: unreference formal parameter
#endif // _MSC_VER
#include "types.h"
#include "pipe.h"
#include "main.h"
#include "hijack/texthook.h"
#include "engine/match.h"
@ -52,7 +52,7 @@ void CreatePipe()
ReleaseMutex(pipeAcquisitionMutex);
CloseHandle(pipeAcquisitionMutex);
ConsoleOutput("vnrcli:WaitForPipe: pipe connected");
ConsoleOutput("NextHooker: pipe connected");
#ifdef _WIN64
ConsoleOutput("Hooks don't work on x64, only read codes work. Engine disabled.");
#else
@ -71,9 +71,7 @@ void CreatePipe()
case HOST_COMMAND_REMOVE_HOOK:
{
auto info = *(RemoveHookCmd*)buffer;
for (int i = 0; i < MAX_HOOK; ++i)
if (::hookman[i].Address() == info.address)
::hookman[i].ClearHook();
RemoveHook(info.address);
}
break;
case HOST_COMMAND_DETACH:
@ -96,18 +94,6 @@ void ConsoleOutput(LPCSTR text)
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)
{
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