This repository has been archived by the owner on Jun 11, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 172
/
PolyHook.hpp
1752 lines (1532 loc) · 48.6 KB
/
PolyHook.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef POLYHOOK_H
#define POLYHOOK_H
#include <windows.h>
#include "../Capstone/include/capstone.h"
#include <DbgHelp.h>
#include <string>
#include <vector>
#include <mutex>
#include <algorithm>
#include <utility>
#include <TlHelp32.h>
#include <assert.h>
#pragma comment(lib,"Dbghelp.lib")
#pragma comment(lib,"capstone.lib")
#define PLH_SHOW_DEBUG_MESSAGES 1 //To print messages even in release
namespace PLH {
namespace Tools
{
inline void XTrace(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#if defined(_DEBUG) || defined(PLH_SHOW_DEBUG_MESSAGES)
vfprintf_s(stdout, fmt, args);
#endif
va_end(args);
}
class ThreadHandle
{
public:
//Thread ID, OpenThread's AccessFlag
ThreadHandle(DWORD ThreadId, DWORD DesiredAccessFlags) : m_ThreadId(ThreadId), m_IsSuspended(false)
{
m_hThread = OpenThread(DesiredAccessFlags, FALSE, ThreadId);
if(m_hThread == NULL)
throw "PolyHook: Failed to open thread in class ThreadHandle";
}
//Only allow once instance to control a handle
ThreadHandle(const ThreadHandle& other) = delete; //copy
ThreadHandle& operator=(const ThreadHandle& other) = delete; //copy assignment
//Move
ThreadHandle(ThreadHandle &&other) noexcept
: m_IsSuspended(other.m_IsSuspended)
, m_hThread(other.m_hThread)
, m_ThreadId(other.m_ThreadId)
{
other.m_hThread = nullptr;
other.m_IsSuspended = false;
}
//Move assignment
ThreadHandle& operator=(ThreadHandle &&other) noexcept
{
if (this != &other)
{
m_IsSuspended = other.m_IsSuspended;
m_hThread = other.m_hThread;
m_ThreadId = other.m_ThreadId;
other.m_hThread = nullptr;
other.m_IsSuspended = false;
}
return *this;
}
//false resumes, true suspends
void ToggleSuspend(bool Suspend)
{
if (Suspend && !m_IsSuspended)
{
if(SuspendThread(m_hThread) != -1)
m_IsSuspended = true;
}else if (!Suspend && m_IsSuspended){
if(ResumeThread(m_hThread) != -1)
m_IsSuspended = false;
}
}
~ThreadHandle()
{
if (m_IsSuspended)
ToggleSuspend(false);
if (m_hThread)
CloseHandle(m_hThread);
}
private:
bool m_IsSuspended;
HANDLE m_hThread;
DWORD m_ThreadId;
};
class ThreadManager
{
public:
void SuspendThreads()
{
UpdateThreadList(GetCurrentThreadId());
for (ThreadHandle& ThreadInstance : m_SuspendedThreads)
{
ThreadInstance.ToggleSuspend(true);
}
}
void ResumeThreads()
{
for (ThreadHandle& ThreadInstance : m_SuspendedThreads)
{
ThreadInstance.ToggleSuspend(false);
}
}
private:
void UpdateThreadList(DWORD CallingThreadId)
{
m_SuspendedThreads.clear();
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (h == INVALID_HANDLE_VALUE)
return;
THREADENTRY32 te;
te.dwSize = sizeof(te);
BOOL Result = FALSE;
//Loop threads
for (Result = Thread32First(h, &te), te.dwSize = sizeof(te); Result == TRUE && Thread32Next(h, &te); )
{
//Verify size field was set properly
if (te.dwSize < RTL_SIZEOF_THROUGH_FIELD(THREADENTRY32, th32OwnerProcessID))
continue;
if (te.th32ThreadID != CallingThreadId && te.th32OwnerProcessID == GetCurrentProcessId())
m_SuspendedThreads.emplace_back(te.th32ThreadID, THREAD_SUSPEND_RESUME);
}
CloseHandle(h);
}
std::vector<Tools::ThreadHandle> m_SuspendedThreads;
};
inline void* Allocate_2GB_IMPL(uint8_t* pStart,size_t Size,int_fast64_t Delta)
{
/*These lambda's let us use a single for loop for both the forward and backward loop conditions.
I passed delta variable as a parameter instead of capturing it because it is faster, it allows
the compiler to optimize the lambda into a function pointer rather than constructing
an anonymous class and incur the extra overhead that involves (negligible overhead but why not optimize)*/
auto Incrementor = [](int_fast64_t Delta,MEMORY_BASIC_INFORMATION& mbi) -> uintptr_t{
if (Delta > 0)
return (uintptr_t)mbi.BaseAddress + mbi.RegionSize;
else
return (uintptr_t)mbi.BaseAddress - 1; //TO-DO can likely jump much more than 1 byte, figure out what the max is
};
auto Comparator = [](long long int Delta,uintptr_t Addr, uintptr_t End)->bool {
if (Delta > 0)
return Addr < End;
else
return Addr > End;
};
//Start at pStart, search 2GB around it (up/down depending on Delta)
MEMORY_BASIC_INFORMATION mbi;
for (uintptr_t Addr = (uintptr_t)pStart; Comparator(Delta,Addr, (uintptr_t)pStart + Delta); Addr = Incrementor(Delta,mbi))
{
if (!VirtualQuery((LPCVOID)Addr, &mbi, sizeof(mbi)))
break;
assert(mbi.RegionSize != 0);
if (mbi.State != MEM_FREE)
continue;
//VirtualAlloc requires 64k aligned addresses
void* PageBase = (uint8_t*)mbi.BaseAddress - LOWORD(mbi.BaseAddress);
if (void* Allocated = (uint8_t*)VirtualAlloc(PageBase, Size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE))
return Allocated;
}
return nullptr;
}
inline void* AllocateWithin2GB(uint8_t* pStart, size_t Size, size_t& AllocationDelta)
{
static const size_t MaxAllocationDelta = 0x80000000; //2GB
//Attempt to allocate +-2GB from pStart
AllocationDelta = 0;
void* Allocated = nullptr;
Allocated = Tools::Allocate_2GB_IMPL(pStart, Size, (~MaxAllocationDelta) + 1); //Search down first (-2GB)
//If search down found nothing
if (Allocated == nullptr)
Allocated = Tools::Allocate_2GB_IMPL(pStart, Size, MaxAllocationDelta); //Search up (+2GB)
//Sanity check the delta is less than 2GB
if (Allocated != nullptr)
{
AllocationDelta = std::abs(pStart - Allocated);
if (AllocationDelta > MaxAllocationDelta)
{
//Out of range, free then return
VirtualFree(Allocated, 0, MEM_RELEASE);
return nullptr;
}
}
return Allocated;
}
}
class ASMHelper
{
public:
enum DISP
{
D_INT64 = 8,
D_INT32 = 4,
D_INT16 = 2,
D_INT8 = 1,
D_INVALID = -1
};
DISP GetDisplacementType(const uint8_t DispVal)
{
switch (DispVal)
{
case 1:
return DISP::D_INT8;
case 2:
return DISP::D_INT16;
case 4:
return DISP::D_INT32;
case 8:
return DISP::D_INT64;
default:
return DISP::D_INVALID;
}
}
bool IsConditionalJump(const uint8_t* bytes,const uint16_t Size)
{
//http://unixwiz.net/techtips/x86-jumps.html
if (Size < 1)
return false;
if (bytes[0] == 0x0F && Size > 1)
{
if (bytes[1] >= 0x80 && bytes[1] <= 0x8F)
return true;
}
if (bytes[0] >= 0x70 && bytes[0] <= 0x7F)
return true;
if (bytes[0] == 0xE3)
return true;
return false;
}
template<typename T>
T GetDisplacement(uint8_t* Instruction, const uint32_t Offset)
{
T Disp;
memset(&Disp, 0x00, sizeof(T));
memcpy(&Disp, &Instruction[Offset], sizeof(T));
return Disp;
}
};
class RuntimeError
{
public:
enum class Severity
{
Warning, //Might have an issue
Critical, //Definitely have an issue, but it's not serious
UnRecoverable, //Definitely have an issue, it's serious
NoError //Default
};
RuntimeError();
RuntimeError(Severity Sev, const std::string& Msg);
virtual ~RuntimeError() = default;
const Severity GetSeverity() const;
const std::string GetString() const;
private:
Severity m_Severity;
std::string m_Message;
};
enum class HookType
{
X86Detour,
X64Detour,
VFuncSwap,
VFuncDetour,
VTableSwap,
IAT,
VEH,
UNKNOWN
};
class IHook
{
public:
IHook() = default;
IHook(IHook&& other) = default; //move
IHook& operator=(IHook&& other) = default;//move assignment
IHook(const IHook& other) = delete; //copy
IHook& operator=(const IHook& other) = delete; //copy assignment
virtual ~IHook() = default;
virtual bool Hook() = 0;
virtual void UnHook() = 0;
virtual HookType GetType() = 0;
virtual RuntimeError GetLastError() const;
virtual void PrintError(const RuntimeError& Err) const;
protected:
virtual void PostError(const RuntimeError& Err);
RuntimeError m_LastError;
};
class AbstractDetour :public IHook
{
public:
AbstractDetour();
AbstractDetour(const AbstractDetour& other) = delete;
AbstractDetour& operator=(const AbstractDetour& other) = delete;
virtual ~AbstractDetour();
template<typename T>
void SetupHook(T* Src, T* Dest)
{
SetupHook((uint8_t*)Src, (uint8_t*)Dest);
}
void SetupHook(uint8_t* Src, uint8_t* Dest);
virtual void UnHook() override;
template<typename T>
T GetOriginal()
{
return (T)m_Trampoline;
}
protected:
template<typename T>
T CalculateRelativeDisplacement(uintptr_t From,uintptr_t To, uint_fast32_t InsSize)
{
if (To < From)
return 0 - (From - To) - InsSize;
return To - (From + InsSize);
}
uint_fast32_t CalculateLength(uint8_t* Src, uint_fast32_t NeededLength);
void RelocateASM(uint8_t* Code, uint_fast32_t* CodeSize, const uintptr_t From, const uintptr_t To);
void _Relocate(cs_insn* CurIns, const uintptr_t From, const uintptr_t To, const uint8_t DispSize, const uint8_t DispOffset);
void RelocateConditionalJMP(cs_insn* CurIns, uint_fast32_t* CodeSize, const uintptr_t From, const uintptr_t To, const uint8_t DispSize, const uint8_t DispOffset);
virtual x86_reg GetIpReg() = 0;
virtual void FreeTrampoline() = 0;
virtual void WriteJMP(uintptr_t From, uintptr_t To) = 0;
virtual int GetJMPSize() = 0;
void FlushSrcInsCache();
void Initialize(cs_mode Mode);
csh m_CapstoneHandle;
ASMHelper m_ASMInfo;
uint8_t m_OriginalCode[64];
uint_fast32_t m_OriginalLength;
uint8_t* m_Trampoline;
bool m_NeedFree;
bool m_Hooked;
uint8_t* m_hkSrc;
uint8_t* m_hkDest;
uint_fast32_t m_hkLength;
cs_mode m_CapMode;
};
#ifndef _WIN64
#define Detour X86Detour
//x86 5 Byte Detour
class X86Detour :public AbstractDetour
{
public:
friend class VFuncDetour;
X86Detour();
X86Detour(X86Detour&& other) = default; //move
X86Detour& operator=(X86Detour&& other) = default;//move assignment
X86Detour(const X86Detour& other) = delete; //copy
X86Detour& operator=(const X86Detour& other) = delete; //copy assignment
virtual ~X86Detour();
virtual bool Hook() override;
virtual HookType GetType() override;
protected:
virtual x86_reg GetIpReg() override;
virtual void FreeTrampoline();
virtual void WriteJMP(uintptr_t From, uintptr_t To);
virtual int GetJMPSize();
private:
void WriteRelativeJMP(uintptr_t Destination, uintptr_t JMPDestination);
void WriteAbsoluteJMP(uintptr_t Destination, uintptr_t JMPDestination);
};
#else
#define Detour X64Detour
//X64 6 Byte Detour
class X64Detour :public AbstractDetour
{
public:
friend class VFuncDetour;
//Credits DarthTon, evolution536
X64Detour();
X64Detour(X64Detour&& other) = default; //move
X64Detour& operator=(X64Detour&& other) = default;//move assignment
X64Detour(const X64Detour& other) = delete; //copy
X64Detour& operator=(const X64Detour& other) = delete; //copy assignment
virtual ~X64Detour();
virtual bool Hook() override;
virtual HookType GetType() override;
protected:
virtual x86_reg GetIpReg() override;
virtual void FreeTrampoline() override;
virtual void WriteJMP(const uintptr_t From,const uintptr_t To) override;
virtual int GetJMPSize() override;
private:
void WriteAbsoluteJMP(const uintptr_t Destination,const uintptr_t JMPDestination);
};
#endif //END _WIN64 IFDEF
//Swap Virtual Function Pointer to Destination
class VFuncSwap : public IHook
{
public:
VFuncSwap();
VFuncSwap(VFuncSwap&& other) = default;
VFuncSwap& operator=(VFuncSwap&& other) = default;
VFuncSwap(const VFuncSwap& other) = delete;
VFuncSwap& operator=(const VFuncSwap& other) = delete;
virtual ~VFuncSwap();
virtual bool Hook() override;
virtual void UnHook() override;
virtual HookType GetType() override;
void SetupHook(uint8_t** Vtable, const uint_fast16_t Index, uint8_t* Dest);
template<typename T>
T GetOriginal()
{
return (T)m_OrigVFunc;
}
private:
uint8_t** m_hkVtable;
uint8_t* m_hkDest;
uint8_t* m_OrigVFunc;
uint_fast16_t m_hkIndex;
bool m_Hooked;
};
//Detour the Function the VTable Points to
class VFuncDetour :public IHook
{
public:
VFuncDetour();
VFuncDetour(VFuncDetour&& other) = default; //move
VFuncDetour& operator=(VFuncDetour&& other) = default;//move assignment
VFuncDetour(const VFuncDetour& other) = delete; //copy
VFuncDetour& operator=(const VFuncDetour& other) = delete; //copy assignment
virtual ~VFuncDetour();
virtual bool Hook() override;
virtual void UnHook() override;
virtual HookType GetType() override;
void SetupHook(uint8_t** Vtable, const uint_fast16_t Index, uint8_t* Dest);
template<typename T>
T GetOriginal()
{
return m_Detour->GetOriginal<T>();
}
virtual RuntimeError GetLastError() const override;
protected:
virtual void PostError(const RuntimeError& Err) override;
private:
std::unique_ptr<Detour> m_Detour;
/*We don't need an m_Hooked bool because this
detour object above handles the unhook on destruction by itself*/
};
//Credit to Dogmatt on unknowncheats.me for IsValidPtr
#ifdef _WIN64
#define _PTR_MAX_VALUE ((void*)0x000F000000000000)
#else
#define _PTR_MAX_VALUE ((void*)0xFFF00000)
#endif
inline bool IsValidPtr(void* p) { return (p >= (void*)0x10000) && (p < _PTR_MAX_VALUE) && p != nullptr; }
class VTableSwap : public IHook
{
public:
VTableSwap();
VTableSwap(VTableSwap&& other) = default; //move
VTableSwap& operator=(VTableSwap&& other) = default;//move assignment
VTableSwap(const VTableSwap& other) = delete; //copy
VTableSwap& operator=(const VTableSwap& other) = delete; //copy assignment
virtual ~VTableSwap();
virtual bool Hook() override;
virtual HookType GetType() override;
template<typename T>
T HookAdditional(const uint_fast16_t Index, uint8_t* Dest)
{
//The makes sure we called Hook first
if (!m_NeedFree)
return nullptr;
m_NewVtable[Index] = Dest;
return (T)m_OrigVtable[Index];
}
virtual void UnHook() override;
void SetupHook(uint8_t* pClass, const uint_fast16_t Index, uint8_t* Dest);
template<typename T>
T GetOriginal()
{
return (T)m_hkOriginal;
}
private:
uint_fast16_t GetVFuncCount(uint8_t** pVtable);
void FreeNewVtable();
uint8_t** m_NewVtable;
uint8_t** m_OrigVtable;
uint8_t*** m_phkClass;
uint8_t* m_hkDest;
uint8_t* m_hkOriginal;
uint_fast16_t m_hkIndex;
uint_fast16_t m_VFuncCount;
bool m_NeedFree;
bool m_Hooked;
};
#define ResolveRVA(base,rva) (( (uint8_t*)base) +rva)
class IATHook:public IHook
{
public:
IATHook();
IATHook(IATHook&& other) = default; //move
IATHook& operator=(IATHook&& other) = default;//move assignment
IATHook(const IATHook& other) = delete; //copy
IATHook& operator=(const IATHook& other) = delete; //copy assignment
virtual ~IATHook();
virtual bool Hook() override;
virtual void UnHook() override;
virtual HookType GetType() override;
template<typename T>
T GetOriginal()
{
return (T)m_pIATFuncOrig;
}
void SetupHook(const char* LibraryName,const char* SrcFunc, uint8_t* Dest,const char* Module = "");
private:
bool FindIATFunc(const char* LibraryName,const char* FuncName,PIMAGE_THUNK_DATA* pFuncThunkOut,const char* Module = "");
std::string m_hkSrcFunc;
std::string m_hkLibraryName;
std::string m_hkModuleName;
uint8_t* m_hkDest;
void* m_pIATFuncOrig;
bool m_Hooked;
};
template<typename Func>
class FinalAction {
public:
FinalAction(Func f) :FinalActionFunc(std::move(f)) {}
~FinalAction()
{
FinalActionFunc();
}
private:
Func FinalActionFunc;
/*Uses RAII to call a final function on destruction
C++ 11 version of java's finally (kindof)*/
};
template <typename F>
FinalAction<F> finally(F f) {
return FinalAction<F>(f);
}
class MemoryProtect
{
public:
MemoryProtect(void* Address, size_t Size, DWORD ProtectionFlags);
~MemoryProtect();
private:
bool Protect(void* Address, size_t Size, DWORD ProtectionFlags);
void* m_Address;
size_t m_Size;
DWORD m_Flags;
DWORD m_OldProtection;
};
class VEHHook : public IHook
{
public:
enum class VEHMethod
{
INT3_BP,
HARDWARE_BP,
GUARD_PAGE,
ERROR_TYPE
};
VEHHook();
VEHHook(VEHHook&& other) = default; //move
VEHHook& operator=(VEHHook&& other) = default;//move assignment
VEHHook(const VEHHook& other) = delete; //copy
VEHHook& operator=(const VEHHook& other) = delete; //copy assignment
virtual ~VEHHook();
virtual bool Hook() override;
virtual void UnHook() override;
virtual HookType GetType() override;
template<typename T>
T GetOriginal()
{
return (T)m_ThisCtx.m_Src;
}
void SetupHook(uint8_t* Src, uint8_t* Dest, VEHMethod Method);
auto GetProtectionObject()
{
//Return an object to restore INT3_BP after callback is done
return finally([&]() {
if (m_ThisCtx.m_Type == VEHMethod::INT3_BP)
{
MemoryProtect Protector(m_ThisCtx.m_Src, 1, PAGE_EXECUTE_READWRITE);
*m_ThisCtx.m_Src = 0xCC;
}else if (m_ThisCtx.m_Type == VEHMethod::GUARD_PAGE) {
DWORD OldProtection;
VirtualProtect(m_ThisCtx.m_Src, 1, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &OldProtection);
}
});
}
protected:
struct HookCtx {
VEHMethod m_Type;
uint8_t* m_Src;
uint8_t* m_Dest;
uint8_t m_StorageByte;
/*Different methods store different things in this byte,
INT3_BP = hold the byte overwritten
HARDWARE_BP = the index of the debug register we used
GUARD_PAGE = unused*/
HookCtx(uint8_t* Src, uint8_t* Dest, VEHMethod Method)
{
m_Dest = Dest;
m_Src = Src;
m_Type = Method;
}
HookCtx()
{
m_Type = VEHMethod::ERROR_TYPE;
}
friend bool operator==(const HookCtx& Ctx1, const HookCtx& Ctx2)
{
if (Ctx1.m_Dest == Ctx2.m_Dest && Ctx1.m_Src == Ctx2.m_Src && Ctx1.m_Type == Ctx2.m_Type)
return true;
return false;
}
};
private:
static bool AreInSamePage(const uint8_t* Addr1,const uint8_t* Addr2);
static LONG CALLBACK VEHHandler(EXCEPTION_POINTERS* ExceptionInfo);
static std::vector<HookCtx> m_HookTargets;
static std::mutex m_TargetMutex;
HookCtx m_ThisCtx;
DWORD m_PageSize;
bool m_Hooked;
};
}
////////////////////////////////BEGIN IMPLEMENTATION////////////////////////////////
/*Until C++xy release modules I will keep the implementation in the header. This is
a design decision to make it easier for a user to include PolyHook. Since polyhook
relies on capstone, which requires .lib and .h files of it's own, i want to avoid
compiling polyhook into a .lib. This way a user simply includes polyhook.h, and sets
their dependency directories to point to capstone. If compilation speed is an issue
it is trivial to separate the implementation by manually C&P-ing the below lines
into a seperate .cpp.*/
PLH::RuntimeError::RuntimeError()
{
m_Message = "";
m_Severity = Severity::NoError;
}
PLH::RuntimeError::RuntimeError(Severity Sev, const std::string& Msg)
{
m_Severity = Sev;
m_Message = Msg;
}
const std::string PLH::RuntimeError::GetString() const
{
return m_Message;
}
const PLH::RuntimeError::Severity PLH::RuntimeError::GetSeverity() const
{
return m_Severity;
}
void PLH::IHook::PostError(const RuntimeError& Err)
{
m_LastError = Err;
PLH::Tools::XTrace("Posted Error [SEVERITY:%d]:\n"
"%s\n", Err.GetSeverity(), Err.GetString().c_str());
}
void PLH::IHook::PrintError(const RuntimeError& Err) const
{
std::string Severity = "";
switch (Err.GetSeverity())
{
case PLH::RuntimeError::Severity::Warning:
Severity = "Warning";
break;
case PLH::RuntimeError::Severity::Critical:
Severity = "Critical";
break;
case PLH::RuntimeError::Severity::UnRecoverable:
Severity = "UnRecoverable";
break;
case PLH::RuntimeError::Severity::NoError:
Severity = "No Error";
break;
default:
Severity = "Unknown";
}
PLH::Tools::XTrace("SEVERITY:[%s] %s\n", Severity.c_str(),
Err.GetString().c_str());
}
PLH::RuntimeError PLH::IHook::GetLastError() const
{
return m_LastError;
}
PLH::AbstractDetour::AbstractDetour() :IHook(), m_NeedFree(false), m_Hooked(false)
{
#ifdef _WIN64
Initialize(CS_MODE_64);
#else
Initialize(CS_MODE_32);
#endif // _WIN64
}
PLH::AbstractDetour::~AbstractDetour()
{
cs_close(&m_CapstoneHandle);
}
void PLH::AbstractDetour::SetupHook(uint8_t* Src, uint8_t* Dest)
{
m_hkSrc = Src;
m_hkDest = Dest;
}
void PLH::AbstractDetour::UnHook()
{
MemoryProtect Protector(m_hkSrc, m_hkLength, PAGE_EXECUTE_READWRITE);
memcpy(m_hkSrc, m_OriginalCode, m_OriginalLength); //Copy original from trampoline back to src
FlushSrcInsCache();
FreeTrampoline();
m_Hooked = false;
}
uint_fast32_t PLH::AbstractDetour::CalculateLength(uint8_t* Src, uint_fast32_t NeededLength)
{
//Grab First 100 bytes of function, disasm until invalid instruction
cs_insn* InstructionInfo;
size_t InstructionCount = cs_disasm(m_CapstoneHandle, Src, 0x100, (uintptr_t)Src, 0, &InstructionInfo);
//Loop over instructions until we have at least NeededLength's Size
PLH::Tools::XTrace("\nORIGINAL:\n");
uint_fast32_t InstructionSize = 0;
bool BigEnough = false;
for (uint_fast32_t i = 0; i < InstructionCount && !BigEnough; i++)
{
cs_insn* CurIns = (cs_insn*)&InstructionInfo[i];
InstructionSize += CurIns->size;
if (InstructionSize >= NeededLength)
BigEnough = true;
PLH::Tools::XTrace("%I64X [%d]: ", CurIns->address, CurIns->size);
for (uint_fast32_t j = 0; j < CurIns->size; j++)
PLH::Tools::XTrace("%02X ", CurIns->bytes[j]);
PLH::Tools::XTrace("%s %s\n", CurIns->mnemonic, CurIns->op_str);
}
if (!BigEnough)
InstructionSize = 0;
cs_free(InstructionInfo, InstructionCount);
return InstructionSize;
}
void PLH::AbstractDetour::RelocateASM(uint8_t* Code, uint_fast32_t* CodeSize, const uintptr_t From, const uintptr_t To)
{
cs_insn* InstructionInfo;
size_t InstructionCount = cs_disasm(m_CapstoneHandle, Code, *CodeSize, (uintptr_t)Code, 0, &InstructionInfo);
PLH::Tools::XTrace("\nTrampoline:\n");
for (uint_fast32_t i = 0; i < InstructionCount; i++)
{
cs_insn* CurIns = (cs_insn*)&InstructionInfo[i];
cs_x86* x86 = &(CurIns->detail->x86);
PLH::Tools::XTrace("%I64X: ", CurIns->address);
for (uint_fast32_t j = 0; j < CurIns->size; j++)
PLH::Tools::XTrace("%02X ", CurIns->bytes[j]);
PLH::Tools::XTrace("%s %s\n", CurIns->mnemonic, CurIns->op_str);
for (uint_fast32_t j = 0; j < x86->op_count; j++)
{
cs_x86_op* op = &(x86->operands[j]);
if (op->type == X86_OP_MEM)
{
//MEM are types like lea rcx,[rip+0xdead]
if (op->mem.base == X86_REG_INVALID)
continue;
//Are we relative to instruction pointer?
if (op->mem.base != GetIpReg())
continue;
_Relocate(CurIns, From, To, x86->offsets.displacement_size, x86->offsets.displacement_offset);
}
else if (op->type == X86_OP_IMM) {
//IMM types are like call 0xdeadbeef
if (x86->op_count > 1) //exclude types like sub rsp,0x20
continue;
char* mnemonic = CurIns->mnemonic;
if (m_ASMInfo.IsConditionalJump(CurIns->bytes, CurIns->size))
{
RelocateConditionalJMP(CurIns, CodeSize, From, To, x86->offsets.imm_size, x86->offsets.imm_offset);
continue;
}
//types like push 0x20 slip through, check mnemonic
if (strcmp(mnemonic, "call") != 0 && strcmp(mnemonic, "jmp") != 0) //probably more types than just these, update list as they're found
continue;
_Relocate(CurIns, From, To, x86->offsets.imm_size, x86->offsets.imm_offset);
}
}
}
PLH::Tools::XTrace("\nFixed Trampoline\n");
InstructionCount = cs_disasm(m_CapstoneHandle, Code, *CodeSize, (uint64_t)Code, 0, &InstructionInfo);
for (int i = 0; i < InstructionCount; i++)
{
cs_insn* CurIns = (cs_insn*)&InstructionInfo[i];
PLH::Tools::XTrace("%I64X: ", CurIns->address);
for (int j = 0; j < CurIns->size; j++)
PLH::Tools::XTrace("%02X ", CurIns->bytes[j]);
PLH::Tools::XTrace("%s %s\n", CurIns->mnemonic, CurIns->op_str);
}
cs_free(InstructionInfo, InstructionCount);
}
void PLH::AbstractDetour::_Relocate(cs_insn* CurIns, const uintptr_t From, const uintptr_t To, const uint8_t DispSize, const uint8_t DispOffset)
{
PLH::Tools::XTrace("Relocating...\n");
ASMHelper::DISP DispType = m_ASMInfo.GetDisplacementType(DispSize);
if (DispType == ASMHelper::DISP::D_INT8)
{
int8_t Disp = m_ASMInfo.GetDisplacement<int8_t>(CurIns->bytes, DispOffset);
Disp -= (To - From);
*(int8_t*)(CurIns->address + DispOffset) = Disp;
}
else if (DispType == ASMHelper::DISP::D_INT16) {
int16_t Disp = m_ASMInfo.GetDisplacement<int16_t>(CurIns->bytes, DispOffset);
Disp -= (To - From);
*(int16_t*)(CurIns->address + DispOffset) = Disp;
}
else if (DispType == ASMHelper::DISP::D_INT32) {
int32_t Disp = m_ASMInfo.GetDisplacement<int32_t>(CurIns->bytes, DispOffset);
Disp -= (To - From);
*(int32_t*)(CurIns->address + DispOffset) = Disp;
}
}
void PLH::AbstractDetour::FlushSrcInsCache()
{
/*This method is just a precaution, on x86/x64 it is usually a no-op,
on other platforms it may be required (ARM i believe?)*/
//Flush overwritten original
FlushInstructionCache(GetCurrentProcess(), m_hkSrc, m_OriginalLength);
//Flush trampoline
FlushInstructionCache(GetCurrentProcess(), m_Trampoline, m_hkLength);
}
void PLH::AbstractDetour::Initialize(cs_mode Mode)
{
if (cs_open(CS_ARCH_X86, Mode, &m_CapstoneHandle) != CS_ERR_OK)
PLH::Tools::XTrace("Error Initializing Capstone x86\n");
cs_option(m_CapstoneHandle, CS_OPT_DETAIL, CS_OPT_ON);
}
void PLH::AbstractDetour::RelocateConditionalJMP(cs_insn* CurIns, uint_fast32_t* CodeSize, const uintptr_t From, const uintptr_t To, const uint8_t DispSize, const uint8_t DispOffset)
{
/*This function automatically begins to build a jump table at the end of the trampoline to allow relative jumps to function properly:
-Changes relative jump to point to an absolute jump
-Absolute jump then does the long distance to jump to where the relative jump originally went
*/
ASMHelper::DISP DispType = m_ASMInfo.GetDisplacementType(DispSize);
uintptr_t TrampolineEnd = To + (*CodeSize);
if (DispType == ASMHelper::DISP::D_INT8)
{
int8_t Disp = m_ASMInfo.GetDisplacement<int8_t>(CurIns->bytes, DispOffset);
uintptr_t OriginalDestination = CurIns->address + (Disp - (To - From)) + CurIns->size;
WriteJMP(TrampolineEnd, OriginalDestination);
Disp = CalculateRelativeDisplacement<int8_t>(CurIns->address, TrampolineEnd, CurIns->size); //set relative jmp to go to our absolute
*(int8_t*)(CurIns->address + DispOffset) = Disp;
(*CodeSize) += GetJMPSize();
}
else if (DispType == ASMHelper::DISP::D_INT16) {
int16_t Disp = Disp = m_ASMInfo.GetDisplacement<int16_t>(CurIns->bytes, DispOffset);
uintptr_t OriginalDestination = CurIns->address + (Disp - (To - From)) + CurIns->size;
WriteJMP(TrampolineEnd, OriginalDestination);
Disp = CalculateRelativeDisplacement<int16_t>(CurIns->address, TrampolineEnd, CurIns->size);
*(int16_t*)(CurIns->address + DispOffset) = Disp;
(*CodeSize) += GetJMPSize();
}
else if (DispType == ASMHelper::DISP::D_INT32) {
int32_t Disp = Disp = m_ASMInfo.GetDisplacement<int32_t>(CurIns->bytes, DispOffset);
uintptr_t OriginalDestination = CurIns->address + (Disp - (To - From)) + CurIns->size;
WriteJMP(TrampolineEnd, OriginalDestination);
Disp = CalculateRelativeDisplacement<int32_t>(CurIns->address, TrampolineEnd, CurIns->size);
*(int32_t*)(CurIns->address + DispOffset) = Disp;
(*CodeSize) += GetJMPSize();
}
}
/*----------------------------------------------*/
#ifndef _WIN64
PLH::X86Detour::X86Detour() : AbstractDetour()
{
}
PLH::X86Detour::~X86Detour()
{
if (m_Hooked)
UnHook();
if (m_NeedFree)
FreeTrampoline();
}
PLH::HookType PLH::X86Detour::GetType()
{
return PLH::HookType::X86Detour;
}
bool PLH::X86Detour::Hook()
{
DWORD OldProtection;
m_hkLength = CalculateLength(m_hkSrc, 5);
m_OriginalLength = m_hkLength;
if (m_hkLength == 0)
{
PLH::Tools::XTrace("Function to small to hook\n");
return false;
}
//TODO: Add single step support in case processes EIP is on/in the section we write to
Tools::ThreadManager ThreadMngr;
ThreadMngr.SuspendThreads();
m_Trampoline = new uint8_t[m_hkLength + 30]; //Allocate Space for original plus extra to jump back and for jmp table
m_NeedFree = true;
VirtualProtect(m_Trampoline, m_hkLength + 30, PAGE_EXECUTE_READWRITE, &OldProtection); //Allow Execution
memcpy(m_OriginalCode, m_hkSrc, m_hkLength);
memcpy(m_Trampoline, m_hkSrc, m_hkLength); //Copy original into allocated space
WriteAbsoluteJMP((uintptr_t)&m_Trampoline[m_hkLength], (uintptr_t)m_hkSrc + m_hkLength); //JMP back to original code, use absolute so we don't accidentally relocate it
m_hkLength += 6; //Size of above jump