shit ton of refactoring and bugfixes

This commit is contained in:
Akash Mozumdar 2018-07-18 23:40:44 -04:00
parent 904804de28
commit 2065359a4e
18 changed files with 77 additions and 241 deletions

View File

@ -15,13 +15,13 @@ set(CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION ON)
execute_process(COMMAND "cmd" " /C date /T" OUTPUT_VARIABLE FULLDATE)
# set(DATE "07/13/2018")
string(SUBSTRING ${FULLDATE} 0 10 BUILD_DATE)
string(SUBSTRING ${FULLDATE} 4 10 BUILD_DATE)
set(BUILD_DATE ${BUILD_DATE})
set(CPACK_GENERATOR "ZIP")
set(CPACK_PACKAGE_VERSION_MAJOR 1)
set(CPACK_PACKAGE_VERSION_MINOR 0)
set(CPACK_PACKAGE_VERSION_PATCH 3)
set(CPACK_PACKAGE_VERSION_PATCH 4)
set(CPACK_SOURCE_GENERATOR "ZIP")
set(CPACK_SOURCE_IGNORE_FILES "/CVS/;/\\\\.svn/;/\\\\.bzr/;/\\\\.hg/;/\\\\.git/;\\\\.swp$;\\\\.#;/#" ".*\\\\.user$" "\\\\.gitignore$" "\\\\.gitmodules$" "\\\\.git$")
include(CPack)

View File

@ -143,19 +143,24 @@ DWORD ProfileManager::CountProfiles()
return profile_tree.size();
}
DWORD SaveProcessProfile(DWORD pid)
DWORD SaveProcessProfile(TextThread* thread)
{
std::wstring path = GetProcessPath(pid);
ThreadParameter tp = thread->GetThreadParameter();
std::wstring path = GetProcessPath(tp.pid);
if (path.empty())
return 0;
pugi::xml_document doc;
pugi::xml_node profile_node = doc.append_child(L"Profile");
man->GetProfile(pid, profile_node);
Profile* pf = pfman->GetProfile(pid);
Profile* pf = pfman->GetProfile(tp.pid);
if (pf != NULL)
pf->Clear();
else
pf = pfman->CreateProfile(pid);
pf = pfman->CreateProfile(tp.pid);
pf->AddHook(hook_ptr(new HookProfile(man->GetHookParam(tp.pid, tp.hook), man->GetHookName(tp.pid, tp.hook))));
pf->AddThread(thread_ptr(new ThreadProfile(man->GetHookName(tp.pid, tp.hook), tp.retn, tp.spl, tp.hook, 0, THREAD_MASK_RETN | THREAD_MASK_SPLIT, L"")));
pf->XmlReadProfile(profile_node);
return 0;
}

View File

@ -299,6 +299,6 @@ std::wstring GetEntryString(TextThread* thread)
std::wstring buffer;
buffer.resize(200);
buffer.resize(swprintf(&buffer[0], L"%.4X:%.4d:0x%08X:0x%08X:0x%08X:", thread->Number(), tp.pid, tp.hook, tp.retn, tp.spl));
buffer += man->GetHook(tp.pid, tp.hook).name;
buffer += man->GetHookName(tp.pid, tp.hook);
return buffer;
}

View File

@ -83,7 +83,7 @@ BOOL InitInstance(HINSTANCE hInstance, DWORD nAdmin, RECT* rc)
return TRUE;
}
DWORD SaveProcessProfile(DWORD pid); // ProfileManager.cpp
DWORD SaveProcessProfile(TextThread* thread); // ProfileManager.cpp
BOOL CALLBACK OptionDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
@ -318,10 +318,10 @@ void ClickButton(HWND hWnd, HWND h)
else if (h == hwndSave)
{
WCHAR str[32];
if (GetWindowText(hwndProcessComboBox, str, 32))
if (GetWindowText(hwndCombo, str, 32))
{
DWORD pid = std::stoul(str);
SaveProcessProfile(pid);
TextThread* current = man->FindSingle(std::stoul(str, nullptr, 16));
SaveProcessProfile(current);
}
pfman->SaveProfiles();
}
@ -356,7 +356,7 @@ bool GetHookParam(DWORD pid, DWORD hook_addr, HookParam& hp)
{
if (!pid)
return false;
hp = man->GetHook(pid, hook_addr).hp;
hp = man->GetHookParam(pid, hook_addr);
return true;
}
@ -367,7 +367,7 @@ std::wstring CreateEntryWithLink(ThreadParameter tp, std::wstring& entry)
entryWithLink += L"ConsoleOutput";
HookParam hp = {};
if (GetHookParam(tp.pid, tp.hook, hp))
entryWithLink += L" (" + GetCode(hp, tp.hook) + L")";
entryWithLink += L" (" + GetCode(hp, tp.pid) + L")";
return entryWithLink;
}
@ -432,12 +432,6 @@ DWORD ThreadReset(TextThread* thread)
return 0;
}
DWORD AddRemoveLink(TextThread* thread)
{
AddToCombo(*thread, true);
return 0;
}
bool IsUnicodeHook(const ProcessRecord& pr, DWORD hook);
DWORD ThreadCreate(TextThread* thread)
@ -470,7 +464,7 @@ bool IsUnicodeHook(const ProcessRecord& pr, DWORD hook)
{
bool res = false;
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const OldHook*)pr.hookman_map;
auto hooks = (const Hook*)pr.hookman_map;
for (DWORD i = 0; i < MAX_HOOK; i++)
{
if (hooks[i].Address() == hook)
@ -562,8 +556,6 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
AddToCombo(*console, false);
man->RegisterProcessAttachCallback(RegisterProcess);
man->RegisterProcessDetachCallback(RemoveProcessList);
//man->RegisterProcessNewHookCallback(RefreshProfileOnNewHook); Artikash 5/30/2018 TODO: Finish implementing this.
man->RegisterAddRemoveLinkCallback(AddRemoveLink);
OpenHost();
{
static const WCHAR program_name[] = L"NextHooker beta v";

View File

@ -257,7 +257,7 @@ std::wstring GetHookNameByAddress(const ProcessRecord& pr, DWORD hook_address)
{
std::wstring hook_name;
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const OldHook*)pr.hookman_map;
auto hooks = (const Hook*)pr.hookman_map;
for (int i = 0; i < MAX_HOOK; ++i)
{
auto& hook = hooks[i];

View File

@ -11,7 +11,6 @@ set(vnrhost_src
hookman.h
host.h
textthread.h
textthread_p.h
hookman.cc
host.cc
pipe.cc
@ -33,11 +32,7 @@ target_compile_options(vnrhost PRIVATE
#STRING(REPLACE "/EHsc" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})
target_link_libraries(vnrhost
#ithsys
profile
#${WDK_HOME}/lib/wxp/i386/ntdll.lib
)
target_link_libraries(vnrhost)
target_compile_definitions(vnrhost
PRIVATE

View File

@ -13,10 +13,7 @@
#include "vnrhook/include/defs.h"
#include "vnrhook/include/types.h"
#include <stdio.h>
//#include <emmintrin.h>
#include "profile/Profile.h"
#include "profile/pugixml.h"
#include "profile/misc.h"
#include <atlbase.h>
#define HM_LOCK CriticalSectionLocker locker(hmcs) // Synchronized scope for accessing private data
@ -174,7 +171,7 @@ void HookManager::AddConsoleOutput(LPCWSTR text)
if (text)
{
int len = wcslen(text) * 2;
TextThread *console = textThreadsByParams[{0, -1UL, -1UL, -1UL}];
TextThread *console = textThreadsByParams[{ 0, -1UL, -1UL, -1UL }];
console->AddSentence(std::wstring(text));
}
}
@ -201,93 +198,38 @@ HANDLE HookManager::GetHostPipe(DWORD pid)
return processRecordsByIds[pid] ? processRecordsByIds[pid]->hostPipe : nullptr;
}
Hook HookManager::GetHook(DWORD processId, DWORD addr)
HookParam HookManager::GetHookParam(DWORD pid, DWORD addr)
{
HM_LOCK;
return hooksByAddresses[{ processId, addr, 0, 0}];
HookParam ret = {};
ProcessRecord* pr = GetProcessRecord(pid);
if (pr == nullptr) return ret;
WaitForSingleObject(pr->hookman_mutex, 0);
const Hook* hooks = (const Hook*)pr->hookman_map;
for (int i = 0; i < MAX_HOOK; ++i)
if (hooks[i].Address() == addr)
ret = hooks[i].hp;
ReleaseMutex(pr->hookman_mutex);
return ret;
}
void HookManager::SetHook(DWORD processId, DWORD addr, Hook hook)
std::wstring HookManager::GetHookName(DWORD pid, DWORD addr)
{
HM_LOCK;
hooksByAddresses[{ processId, addr, 0, 0}] = hook;
}
void AddHooksToProfile(Profile& pf, const ProcessRecord& pr);
DWORD AddThreadToProfile(Profile& pf, const ProcessRecord& pr, TextThread* thread);
void MakeHookRelative(const ProcessRecord& pr, HookParam& hp);
void HookManager::GetProfile(DWORD pid, pugi::xml_node profile_node)
{
const ProcessRecord* pr = GetProcessRecord(pid);
if (pr == NULL)
return;
Profile pf(L"serialize");
AddHooksToProfile(pf, *pr);
AddThreadsToProfile(pf, *pr, pid);
pf.XmlWriteProfile(profile_node);
}
void AddHooksToProfile(Profile& pf, const ProcessRecord& pr)
{
WaitForSingleObject(pr.hookman_mutex, 0);
auto hooks = (const OldHook*)pr.hookman_map;
for (DWORD i = 0; i < MAX_HOOK; ++i)
std::string buffer;
ProcessRecord* pr = GetProcessRecord(pid);
if (pr == nullptr) return L"";
WaitForSingleObject(pr->hookman_mutex, 0);
USES_CONVERSION;
const Hook* hooks = (const Hook*)pr->hookman_map;
for (int i = 0; i < MAX_HOOK; ++i)
{
if (hooks[i].Address() == 0)
continue;
auto& hook = hooks[i];
DWORD type = hook.Type();
if ((type & HOOK_ADDITIONAL) && (type & HOOK_ENGINE) == 0)
if (hooks[i].Address() == addr)
{
std::unique_ptr<CHAR[]> name(new CHAR[hook.NameLength()]);
if (ReadProcessMemory(pr.process_handle, hook.Name(), name.get(), hook.NameLength(), NULL))
{
if (hook.hp.module)
{
HookParam hp = hook.hp;
MakeHookRelative(pr, hp);
pf.AddHook(hook_ptr(new HookProfile(hp, toUnicodeString(name.get()))));
}
else
pf.AddHook(hook_ptr(new HookProfile(hook.hp, toUnicodeString(name.get()))));
}
buffer.resize(hooks[i].NameLength());
ReadProcessMemory(pr->process_handle, hooks[i].Name(), &buffer[0], hooks[i].NameLength(), nullptr);
}
}
ReleaseMutex(pr.hookman_mutex);
}
void MakeHookRelative(const ProcessRecord& pr, HookParam& hp)
{
MEMORY_BASIC_INFORMATION info;
VirtualQueryEx(pr.process_handle, (LPCVOID)hp.address, &info, sizeof(info));
hp.address -= (DWORD)info.AllocationBase;
hp.function = 0;
}
void HookManager::AddThreadsToProfile(Profile& pf, const ProcessRecord& pr, DWORD pid)
{
HM_LOCK;
AddThreadToProfile(pf, pr, current);
}
DWORD AddThreadToProfile(Profile& pf, const ProcessRecord& pr, TextThread* thread)
{
ThreadParameter tp = thread->GetThreadParameter();
std::wstring hook_name = GetHookNameByAddress(pr, tp.hook);
if (hook_name.empty())
return -1;
auto thread_profile = new ThreadProfile(hook_name, tp.retn, tp.spl, 0, 0,
THREAD_MASK_RETN | THREAD_MASK_SPLIT, L"");
DWORD threads_size = pf.Threads().size();
int thread_profile_index = pf.AddThread(thread_ptr(thread_profile));
if (thread_profile_index == threads_size) // new thread
{
WORD iw = thread_profile_index & 0xFFFF;
if (thread->Status() & CURRENT_SELECT)
pf.SelectedIndex() = iw;
}
return thread_profile_index; // in case more than one thread links to the same thread
}
ReleaseMutex(pr->hookman_mutex);
return std::wstring(A2W(buffer.c_str()));
}
// EOF

View File

@ -11,11 +11,6 @@
#include <string>
#include "vnrhook/include/types.h"
namespace pugi {
class xml_node;
}
class Profile;
struct ProcessRecord {
HANDLE process_handle;
HANDLE hookman_mutex;
@ -24,12 +19,6 @@ struct ProcessRecord {
HANDLE hostPipe;
};
struct Hook
{
HookParam hp;
std::wstring name;
};
typedef DWORD(*ProcessEventCallback)(DWORD pid);
typedef DWORD(*ThreadEventCallback)(TextThread*);
@ -48,8 +37,6 @@ public:
~HookManager();
TextThread *FindSingle(DWORD number);
ProcessRecord *GetProcessRecord(DWORD pid);
Hook GetHook(DWORD processId, DWORD addr);
void SetHook(DWORD processId, DWORD addr, Hook hook);
void ClearCurrent();
void SelectCurrent(DWORD num);
void SetCurrent(TextThread *it);
@ -61,6 +48,8 @@ public:
void RemoveSingleHook(DWORD pid, DWORD addr);
void RegisterProcess(DWORD pid, HANDLE hostPipe);
void UnRegisterProcess(DWORD pid);
HookParam GetHookParam(DWORD pid, DWORD addr);
std::wstring GetHookName(DWORD pid, DWORD addr);
//void SetName(DWORD);
HANDLE GetHostPipe(DWORD pid);
@ -73,11 +62,8 @@ public:
void SetSplitInterval(unsigned int splitDelay) { this->splitDelay = splitDelay; }
void GetProfile(DWORD pid, pugi::xml_node profile_node);
private:
std::unordered_map<ThreadParameter, TextThread*, ThreadParameterHasher> textThreadsByParams;
std::unordered_map<ThreadParameter, Hook, ThreadParameterHasher> hooksByAddresses; // Artikash 7/17/2018: retn and spl should always be zero when accessing this!
std::unordered_map<DWORD, ProcessRecord*> processRecordsByIds;
CRITICAL_SECTION hmcs;
@ -92,8 +78,6 @@ private:
new_thread_number;
unsigned int splitDelay;
void HookManager::AddThreadsToProfile(Profile& pf, const ProcessRecord& pr, DWORD pid);
};
// EOF

View File

@ -1,24 +1,14 @@
// host.cc
// 8/24/2013 jichi
// Branch IHF/main.cpp, rev 111
// 8/24/2013 TODO: Clean up this file
//#ifdef _MSC_VER
//# pragma warning(disable:4800) // C4800: forcing value to bool (performance warning)
//#endif // _MSC_VER
//#include "customfilter.h"
#include "growl.h"
#include "host.h"
#include "vnrhook/include/const.h"
#include "vnrhook/include/defs.h"
#include "vnrhook/include/types.h"
#include <commctrl.h>
#include <string>
#include "extensions/Extensions.h"
#define DEBUG "vnrhost/host.cc"
HANDLE preventDuplicationMutex;
HookManager* man;
@ -31,7 +21,7 @@ namespace
void GetDebugPrivileges()
{ // Artikash 5/19/2018: Is it just me or is this function 100% superfluous?
HANDLE processToken;
TOKEN_PRIVILEGES Privileges = {1, {0x14, 0, SE_PRIVILEGE_ENABLED}};
TOKEN_PRIVILEGES Privileges = { 1, {0x14, 0, SE_PRIVILEGE_ENABLED} };
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &processToken);
AdjustTokenPrivileges(processToken, FALSE, &Privileges, 0, nullptr, nullptr);
@ -56,8 +46,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID unused)
dummyWindow = CreateWindowW(L"Button", L"InternalWindow", 0, 0, 0, 0, 0, 0, 0, hinstDLL, 0);
break;
case DLL_PROCESS_DETACH:
if (::running)
CloseHost();
if (::running) CloseHost();
DestroyWindow(dummyWindow);
break;
default:
@ -100,10 +89,7 @@ DLLEXPORT void CloseHost()
DLLEXPORT bool InjectProcessById(DWORD processId, DWORD timeout)
{
if (processId == GetCurrentProcessId())
{
return false;
}
if (processId == GetCurrentProcessId()) return false;
CloseHandle(CreateMutexW(nullptr, FALSE, (ITH_HOOKMAN_MUTEX_ + std::to_wstring(processId)).c_str()));
if (GetLastError() == ERROR_ALREADY_EXISTS)
@ -167,8 +153,7 @@ DLLEXPORT DWORD InsertHook(DWORD pid, const HookParam *hp, std::string name)
DLLEXPORT DWORD RemoveHook(DWORD pid, DWORD addr)
{
HANDLE commandPipe = man->GetHostPipe(pid);
if (commandPipe == nullptr)
return -1;
if (commandPipe == nullptr) return -1;
HANDLE hookRemovalEvent = CreateEventW(nullptr, TRUE, FALSE, ITH_REMOVEHOOK_EVENT);
BYTE buffer[sizeof(DWORD) * 2] = {};

View File

@ -64,16 +64,7 @@ DWORD WINAPI TextReceiver(LPVOID lpThreadParameter)
USES_CONVERSION;
switch (*(DWORD*)(buffer + 4)) // Artikash 7/17/2018: Notification type
{
case HOST_NOTIFICATION_NEWHOOK:
man->SetHook(processId,
((HookParam*)(buffer + sizeof(DWORD) * 2))->address, // Hook address
{
*(HookParam*)(buffer + sizeof(DWORD) * 2), // Hook parameter
std::wstring(A2W(
(const char*)buffer + sizeof(DWORD) * 2 + sizeof(HookParam) // Hook name
))
}
);
case HOST_NOTIFICATION_NEWHOOK: // Artikash 7/18/2018: Useless for now, but could be used to implement smth later
break;
case HOST_NOTIFICATION_TEXT:
man->AddConsoleOutput(A2W((LPCSTR)(buffer + sizeof(DWORD) * 2))); // Text

View File

@ -1,18 +1,13 @@
// textthread.cc
// 8/24/2013 jichi
// Branch IHF/TextThread.cpp, rev 133
// 8/24/2013 TODO: Clean up this file
#ifdef _MSC_VER
# pragma warning (disable:4100) // C4100: unreference formal parameter
#endif // _MSC_VER
#include "host.h"
#include "textthread.h"
//#include "wintimer/wintimer.h"
#include "vnrhook/include/const.h"
#include "vnrhook/include/types.h"
#include <stdio.h>
#include "extensions/Extensions.h"
#include "winmutex/winmutex.h"
@ -45,12 +40,6 @@ void TextThread::Reset()
storage.clear();
}
std::wstring TextThread::GetStore()
{
TT_LOCK;
return storage;
}
void TextThread::AddSentence()
{
TT_LOCK;

View File

@ -5,12 +5,11 @@
// Branch: ITH/TextThread.h, rev 120
#include <Windows.h>
#include "config.h"
#include <intrin.h> // require _InterlockedExchange
#include <string>
#include <vector>
struct ThreadParameter {
struct ThreadParameter
{
DWORD pid; // jichi: 5/11/2014: The process ID
DWORD hook; // Artikash 6/6/2018: The start address of the hook
DWORD retn; // jichi 5/11/2014: The return address of the hook
@ -30,7 +29,7 @@ typedef void(*ThreadOutputCallback)(TextThread*, std::wstring data);
//extern DWORD split_time,repeat_count,global_filter,cyclic_remove;
class DLLEXPORT TextThread
class TextThread
{
public:
TextThread(ThreadParameter tp, unsigned int threadNumber, unsigned int splitDelay);
@ -41,11 +40,10 @@ public:
void AddSentence();
void AddSentence(std::wstring sentence);
std::wstring GetStore();
std::wstring GetStore() { return storage; }
DWORD &Status() { return status; }
WORD Number() const { return threadNumber; }
ThreadParameter GetThreadParameter() { return tp; }
//LPCWSTR GetComment() { return comment; }
void RegisterOutputCallBack(ThreadOutputCallback cb) { output = cb; }

View File

@ -74,7 +74,7 @@ struct SendParam {
HookParam hp;
};
struct OldHook { // size: 0x80
struct Hook { // size: 0x80
HookParam hp;
LPSTR hook_name;
int name_length;

View File

@ -870,66 +870,23 @@ bool DetermineEngineType()
#endif // ITH_DISABLE_ENGINE
}
// __asm
// {
// mov eax,seh_recover
// mov recv_eip,eax
// push ExceptHandler
// push fs:[0]
// mov fs:[0],esp
// pushad
// mov recv_esp,esp
// }
// DetermineEngineType();
// status++;
// __asm
// {
//seh_recover:
// popad
// mov eax,[esp]
// mov fs:[0],eax
// add esp,8
// }
// if (status == 0)
// ConsoleOutput("Fail to identify engine type.");
// else
// ConsoleOutput("Initialized successfully.");
//}
//
} // unnamed
HANDLE hijackThread;
DWORD WINAPI hijackThreadProc(LPVOID unused)
DWORD InsertDynamicHook(LPVOID addr, DWORD frame, DWORD stack)
{
// Initialize shared process name and path
GetModuleFileNameW(nullptr, processPath, MAX_PATH);
processName = wcsrchr(processPath, L'\\') + 1;
DetermineEngineType();
return 0;
return trigger_fun_ ? !trigger_fun_(addr, frame, stack) : 0;
}
}} // namespace Engine unnamed
void Hijack()
{
GetModuleFileNameW(nullptr, processPath, MAX_PATH);
processName = wcsrchr(processPath, L'\\') + 1;
DetermineEngineType();
}
} // namespace Engine
// - API -
DWORD Engine::InsertDynamicHook(LPVOID addr, DWORD frame, DWORD stack)
{ return trigger_fun_ ? !trigger_fun_(addr, frame, stack) : 0; }
void Engine::hijack()
{
if (!hijackThread) {
ConsoleOutput("vnreng: hijack process");
hijackThread = CreateThread(nullptr, 0, hijackThreadProc, 0, 0, nullptr);
}
}
void Engine::terminate()
{
if (hijackThread) {
WaitForSingleObject(hijackThread, TIMEOUT);
CloseHandle(hijackThread);
hijackThread = 0;
}
}
// EOF

View File

@ -12,7 +12,7 @@
namespace Engine {
// jichi 10/21/2014: Return whether found the engine
void hijack();
void Hijack();
void terminate();
// jichi 10/21/2014: Return 0 if failed

View File

@ -26,7 +26,7 @@ void InitFilterTable();
// jichi 9/25/2013: This class will be used by NtMapViewOfSectionfor
// interprocedure communication, where constructor/destructor will NOT work.
class TextHook : public OldHook
class TextHook : public Hook
{
int UnsafeInsertHookCode();
DWORD UnsafeSend(DWORD dwDataBase, DWORD dwRetn);

View File

@ -121,8 +121,6 @@ BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID unused)
//ITH_TRY {
::running = false;
Engine::terminate();
if (pipeThread) {
WaitForSingleObject(pipeThread, TIMEOUT);
CloseHandle(pipeThread);
@ -169,7 +167,7 @@ DWORD NewHook(const HookParam &hp, LPCSTR name, DWORD flag)
if (::hookman[current].InsertHook() == 0) {
ConsoleOutput("vnrcli:NewHook: hook inserted");
NotifyHookInsert(hp, name);
NotifyHookInsert(hp, str);
} else
ConsoleOutput("vnrcli:NewHook:WARNING: failed to insert hook");
}

View File

@ -56,7 +56,7 @@ DWORD WINAPI PipeManager(LPVOID unused)
ReleaseMutex(pipeAcquisitionMutex);
CloseHandle(pipeAcquisitionMutex);
Engine::hijack();
Engine::Hijack();
ConsoleOutput("vnrcli:WaitForPipe: pipe connected");
while (::running)