-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathxhook.h
1331 lines (1178 loc) · 45.2 KB
/
xhook.h
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
/**
\file xhook.h
\brief 用于 windows hook 。
\version 0.0.2.230818
\note only for windows .
\author triones
\date 2022-06-02
\section more 额外说明
- 由于链接器的【增量链接】可能会造成在使用 Hook 时出现一些莫名其妙的状况,请将之关闭!
\section history 版本记录
- 2022-06-02 新建 xhook 。
- 2023-02-27 修正 UEF 在 x86/x64 下的错误。
- 2023-02-28 修正 x64 下 hook offset 时的 shellcode 错误。
- 2023-03-17 Opcodes 使用 vector ,避免 shellcode < 0x10 不申请内存的错误。
- 2023-08-04 修正 x64 下 hook normal 时,栈未对齐的错误。
- 2023-08-18 改进 x64 下中转实现。
*/
#ifndef _XLIB_XHOOK_H_
#define _XLIB_XHOOK_H_
#ifdef _WIN32
#include <memory>
#include <vector>
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
#undef WIN32_LEAN_AND_MEAN
namespace xlib {
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/// Hook 错误码。
enum HOOK_ERROR_ENUM {
XHE_NoError,
XHE_ReCoverProtect, //< Crack 还原页属性失败。
XHE_OK,
XHE_ModifyProtect, //< Crack 修改页属性失败。
XHE_Write, //< Crack 修改内存失败。
XHE_0Size, //< hooksize 0 大小。
XHE_BadHookMem, //< hookmem 指向内存不可读。
XHE_BadRoutine, //< routine 指向内存不可读。
XHE_UEFCover, //< UEF 回调被覆盖。
XHE_Restored, //< Hook 已被第三方还原。
XHE_BeCovered, //< Hook 已被第三方覆盖。
XHE_UnHooked, //< 已 UnHook 。
XHE_SetTrans, //< 中转位置写入失败。
XHE_AddDisp, //< x64 下,偏移无效。
};
/// 判定 Hook 错误码是否成功。(有些错误对成功不造成影响)
inline bool IsHookOK(const HOOK_ERROR_ENUM e) { return XHE_OK >= e; }
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
指定内存位置,写入数据。
\param mem 需要写入数据的内存位置。
\param code 写入数据指针。
\param size 写入数据大小。
\code
// 接受指定长度数据。
auto e = Crack(0, (void*)"\x90\x90", 2);
auto e = Crack((void*)0, u8"\x90\x90", 2);
// 接受顺序容器。
auto e = Crack(nullptr, std::string("\x90\x90"));
auto e = Crack(0, std::array<char, 2>{'\x90', '\x90'});
// 接受字符串字面量。
auto e = Crack(0, "\x90\x90");
auto e = Crack(0, u8"\x90\x90");
\endcode
*/
template <typename P, typename T>
HOOK_ERROR_ENUM Crack(P mem, const T* code, const size_t size) {
auto m = (LPVOID)mem;
auto c = (const void*)code;
auto s = sizeof(T) * size;
DWORD oldprotect;
if (FALSE == VirtualProtect(m, s, PAGE_EXECUTE_READWRITE, &oldprotect)) {
return XHE_ModifyProtect;
}
bool ok = true;
try {
memcpy(m, c, s);
} catch (...) {
ok = false;
}
// 不管成功与否,都应该还原页属性。
if (FALSE == VirtualProtect(m, s, oldprotect, &oldprotect)) {
if (ok) {
return XHE_ReCoverProtect;
}
}
return ok ? XHE_NoError : XHE_Write;
}
template <typename P>
auto Crack(P mem, const void* code, const size_t size) {
return Crack(mem, (const char*)code, size);
}
template <typename P, class T>
auto Crack(P mem, const T& o)
-> std::enable_if_t<std::is_pointer_v<decltype(o.data())>, HOOK_ERROR_ENUM> {
return Crack(mem, o.data(), o.size());
}
template <typename P, typename T, size_t size>
auto Crack(P mem, T const (&data)[size]) {
return Crack(mem, data, size - 1);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**·
CPU 状态标志寄存器
英特尔 64 和 IA-32 架构软件 developer’s 手册,第 1 卷、基本架构 [PDF] 。
文件名: 25366521.pdf ,大小: 3170961 字节,日期: 2006 年 9 月, Vol.1,3-21 & 3-24 。
- O one
- Z zero
- S Indicates a Status Flag
- C Indicates a Control Flag
- X Indicates a System Flag
*/
struct CPU_FLAGS {
size_t CF : 1; //< S Carry Flag
size_t O1 : 1;
size_t PF : 1; //< S Parity Flag
size_t Z3 : 1;
size_t AF : 1; //< S Auxiliary Carry Flag
size_t Z5 : 1;
size_t ZF : 1; //< S Zero Flag
size_t SF : 1; //< S Sign Flag
size_t TF : 1; //< X Trap Flag
size_t IF : 1; //< X Interrupt Enable Flag
size_t DF : 1; //< C Direction Flag
size_t OF : 1; //< S Overflow Flag
size_t IOPL : 2; //< X I/O Privilege Level
size_t NT : 1; //< X Nested Task (NT)
size_t Z15 : 1;
size_t RF : 1; //< X Resume Flag
size_t VM : 1; //< X Virtual-8086 Mode
size_t AC : 1; //< X Alignment Check
size_t VIF : 1; //< X Virtual Interrupt Flag
size_t VIP : 1; //< X Virtual Interrupt Pending
size_t ID : 1; //< X ID Flag
size_t Z22 : 1;
size_t Z23 : 1;
size_t Z24 : 1;
size_t Z25 : 1;
size_t Z26 : 1;
size_t Z27 : 1;
size_t Z28 : 1;
size_t Z29 : 1;
size_t Z30 : 1;
size_t Z31 : 1;
#ifdef _WIN64
size_t ZReserved : 32; //< x64 下高 32 位保留 。
#endif
};
/// 标准回调函数使用的 CPU 结构。
struct CPU_ST {
#ifndef _WIN64
DWORD regEdi;
DWORD regEsi;
DWORD regEbp;
const DWORD regEsp; //< 注意 esp 不能修改,改了也没意义。
DWORD regEbx;
DWORD regEdx;
DWORD regEcx;
DWORD regEax;
CPU_FLAGS regflag;
DWORD regEip;
#else // _WIN64
DWORD64 regRcx;
DWORD64 regRdx;
DWORD64 regR8;
DWORD64 regR9;
DWORD64 regRax;
DWORD64 regRbx;
const DWORD64 regRsp;
DWORD64 regRbp;
DWORD64 regRsi;
DWORD64 regRdi;
DWORD64 regR10;
DWORD64 regR11;
DWORD64 regR12;
DWORD64 regR13;
DWORD64 regR14;
DWORD64 regR15;
CPU_FLAGS regflag;
DWORD64 regRip;
#endif // _WIN64
CPU_ST() = delete;
CPU_ST(const CPU_ST&) = delete;
CPU_ST& operator=(const CPU_ST&) = delete;
};
// 跨平台寄存器宏。
#ifndef _WIN64
#define regXdi regEdi
#define regXsi regEsi
#define regXbp regEbp
#define regXsp regEsp
#define regXbx regEbx
#define regXdx regEdx
#define regXcx regEcx
#define regXax regEax
#define regXip regEip
#else // _WIN64
#define regXcx regRcx
#define regXdx regRdx
#define regXax regRax
#define regXbx regRbx
#define regXsp regRsp
#define regXbp regRbp
#define regXsi regRsi
#define regXdi regRdi
#define regXip regRip
#endif // _WIN64
/// 回调函数格式。
#ifndef _WIN64
#define HookCalling __stdcall
#else
#define HookCalling
#endif
using HookRoutine = void(HookCalling*)(CPU_ST* lpcpu);
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/// shellcode 缓冲分配器。
template <class T>
struct ShellCodeAllocator {
using value_type = T;
ShellCodeAllocator() = default;
template <class U>
constexpr ShellCodeAllocator(const ShellCodeAllocator<U>&) noexcept {}
T* allocate(std::size_t n) {
auto p = VirtualAlloc(nullptr, n * sizeof(T), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (nullptr != p) return (T*)p;
throw std::bad_alloc();
}
void deallocate(T* p, std::size_t) noexcept {
VirtualFree(p, 0, MEM_RELEASE);
}
};
template <class T, class U>
bool operator==(const ShellCodeAllocator<T>&, const ShellCodeAllocator<U>&) {
return true;
}
template <class T, class U>
bool operator!=(const ShellCodeAllocator<T>&, const ShellCodeAllocator<U>&) {
return false;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
相当于给 std::string 增加了三种 << 操作。
\code
// 接受顺序容器。
Opcodes << std::string("\x90");
Opcodes << std::array<char, 2>{'\x90', '\x90'});
// 接受 数值、指针等。
Opcodes << 0;
Opcodes << (void*)0;
// 接受字符串字面量。
Opcodes << "\x90\x90"
\endcode
*/
template <class Allocator>
class Opcodes : public std::vector<uint8_t, Allocator> {
public:
Opcodes() {};
Opcodes(const Opcodes&) = delete;
Opcodes& operator=(const Opcodes&) = delete;
public:
template <typename T, size_t size>
Opcodes(T const (&data)[size]) {
this->operator<<(data);
}
public:
template <class T>
auto operator<<(const T& v)
-> std::enable_if_t<std::is_pointer_v<decltype(v.data())>, Opcodes&> {
this->insert(this->end(),
(const uint8_t*)v.data(), (const uint8_t*)(v.data() + v.size()));
return *this;
}
template <class T>
std::enable_if_t<!std::is_class_v<T>, Opcodes&> operator<<(const T& v) {
this->insert(this->end(), (const uint8_t*)&v, (const uint8_t*)&v + sizeof(v));
return *this;
}
template <typename T, size_t size>
Opcodes& operator<<(T const (&data)[size]) {
this->insert(this->end(),
(const uint8_t*)data, (const uint8_t*)(data + size - 1));
return *this;
}
};
using opcodes = Opcodes<std::allocator<uint8_t>>;
using shellcodes = Opcodes<ShellCodeAllocator<uint8_t>>;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/// xHook 用于指定 hook 位置 与 回调,生成对应钩子。
class xHook {
public:
/// 地址偏移, x86 与 x64 都是 4 byte 。
using AddrDisp = uint32_t;
using UEFRoutine = LPTOP_LEVEL_EXCEPTION_FILTER;
public:
/// 判定 HOOK 对象是否有效。
bool IsOK() const { return IsHookOK(_e); }
operator bool() const { return IsOK(); }
/// 因为卸载钩子会有一些异常情况,强制卸载极可能会造成崩溃,所以允许指定错误时停止。
HOOK_ERROR_ENUM UnHook(const bool safe) {
// 无效的对象,不执行卸载流程。
if (!IsOK()) return _e;
// 尝试清除 UEF 。
if ((UEFRoutine)-1 != _oldUEFHandling) {
auto nowuef = SetUnhandledExceptionFilter(_oldUEFHandling);
if (safe && (UEFRoutine)_uefshellcode.data() != nowuef) {
SetUnhandledExceptionFilter(nowuef);
return XHE_UEFCover;
}
}
if (safe) {
if (0 == memcmp(_hookmem, _oldcode.data(), _oldcode.size())) {
return XHE_Restored;
}
if (0 != memcmp(_hookmem, _hookcode.data(), _hookcode.size())) {
return XHE_BeCovered;
}
}
// 中转位置的数据,记得还原。
if (nullptr != _transfer) Crack(_transfer, _transferdata);
_e = Crack(_hookmem, _oldcode);
if (!IsOK()) return _e;
// 正确卸载时,写入错误码,避免析构时重复卸载。
return _e = XHE_UnHooked;
}
protected:
/// 检测 写入位置。
bool check_hookmem(void* hookmem, const size_t hooksize) {
if (0 == hooksize) {
_e = XHE_0Size;
return false;
}
if (TRUE == IsBadReadPtr(hookmem, hooksize)) {
_e = XHE_BadHookMem;
return false;
}
_hookmem = hookmem;
_hooksize = hooksize;
_oldcode.assign((const uint8_t*)hookmem, (const uint8_t*)hookmem + hooksize);
return true;
}
/// 检测 回调。
bool check_routine(HookRoutine routine) {
if (TRUE == IsBadReadPtr(routine, 1)) {
_e = XHE_BadRoutine;
return false;
}
_routine = routine;
return true;
}
#ifdef _WIN64
/// 设置中转 。
bool fix_transfer(void* p_transfer, const bool as_pointer) {
if (nullptr == p_transfer) return true;
const size_t addrdisp = CalcOffset((const char*)_hookmem, p_transfer);
if (!IsValidAddrDisp(addrdisp)) {
_e = XHE_AddDisp;
return false;
}
if (as_pointer) {
_transferdata.assign(
(const uint8_t*)p_transfer,
(const uint8_t*)p_transfer + sizeof(void*));
auto ret = Crack(p_transfer, (void*)&_lpshellcode, sizeof(_lpshellcode));
if (!IsHookOK(ret)) {
_e = XHE_SetTrans;
return false;
}
} else {
#pragma pack(push, 1)
struct transfer_shellcode_st {
uint8_t _ff;
uint8_t _25;
AddrDisp _addrdisp;
const void* _transfer;
};
#pragma pack(pop)
const transfer_shellcode_st st = { 0xFF, 0x25, 0, _lpshellcode };
_transferdata.assign(
(const uint8_t*)p_transfer,
(const uint8_t*)p_transfer + sizeof(st));
auto ret = Crack(p_transfer, (void*)&st, sizeof(st));
if (!IsHookOK(ret)) {
_e = XHE_SetTrans;
return false;
}
}
_transfer = p_transfer;
return true;
}
#endif // _WIN64
/// UEF 回调。
static inline LONG __cdecl UEFHandling(_EXCEPTION_POINTERS* ExceptionInfo,
const xHook* o) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_BREAKPOINT) {
#ifndef _WIN64
if ((DWORD)o->_hookmem == ExceptionInfo->ContextRecord->Eip) {
ExceptionInfo->ContextRecord->Eip = (DWORD)(o->_lpshellcode);
return EXCEPTION_CONTINUE_EXECUTION;
}
#else
if ((DWORD64)o->_hookmem == ExceptionInfo->ContextRecord->Rip) {
ExceptionInfo->ContextRecord->Rip = (DWORD64)(o->_lpshellcode);
return EXCEPTION_CONTINUE_EXECUTION;
}
#endif
}
if (nullptr == o->_oldUEFHandling) return EXCEPTION_CONTINUE_SEARCH;
return o->_oldUEFHandling(ExceptionInfo);
}
/// 实现 UEF shellcode 。
void mkuef() {
_uefshellcode.clear();
_hookcode.clear();
#ifndef _WIN64
/*
mov ecx, [esp + 4]
mov edx, this
mov eax, UEFHandling
push edx
push ecx
call eax
pop ecx
pop edx
retn 4
*/
_uefshellcode
<< "\x8B\x4C\x24\x04"
<< '\xBA' << this
<< "\xB8" << &UEFHandling
<< "\x52\x51\xFF\xD0\x59\x5A\xC2\x04\x00";
#else
/*
// rcx 已经准备好。
mov rdx, this
mov rax, UEFHandling
jmp rax
// 注意到,仿造 x86 的 push ,UEFHandling 内部会出现奇怪的异常。(可能是 x64 栈对齐原因)
*/
_uefshellcode
<< "\x48\xBA" << this
<< "\x48\xB8" << &UEFHandling
<< "\xFF\xE0";
#endif
_oldUEFHandling = SetUnhandledExceptionFilter((UEFRoutine)_uefshellcode.data());
_hookcode << '\xCC';
}
public:
xHook() = delete;
xHook(const xHook&) = delete;
xHook& operator=(const xHook&) = delete;
~xHook() { UnHook(false); }
/**
普通 Hook 函数。指定 内存位置 与 回调函数,执行 Hook 操作。
- x86 情况下:\n
- 当 hooksize == 1 ~ 4 :采用 UEF ,钩子不能被覆盖;
- 5 :采用 jmp XXX ,钩子不能被覆盖;
- 6 以上:采用 jmp dword ptr [XXX] ,允许钩子覆盖。
- x64 情况下:\n
- 当 hooksize == 1 ~ 4 :采用 UEF ,钩子不能被覆盖;
- 忽略中转参数。
- 5 :采用 jmp XXX ,偏移超出采用 UEF 。钩子不能被覆盖;
- 中转请提供 0xE byte 空间。
- 6-13 :采用 jmp qword ptr [XXX] ,允许钩子覆盖。偏移超出采用 UEF ,钩子不能被覆盖;
- 中转请提供 0x8 byte 空间。
- 14 以上:采用 jmp qword ptr [XXX] ,允许钩子覆盖。
- 忽略中转参数。
\param hookmem 指定 hook 内存的位置。
\param hooksize hook 长度 [1, 30] 。
\param routine 指定的回调函数(声明请参考 HookRoutine )
\param routinefirst true :回调先行, false :覆盖代码先行。
\param p_transfer 指定中转位置。\n
x86 下仅兼容,参数被忽略。\n
x64 下用于避免偏移超出而自动采用 UEF 。
\code
#include "hook.h"
void HookCalling Routine(CPU_ST* lpcpu) { return; }
// 在 0x401000 下 5 byte JMP XXX 钩子,代码先行。
xHook node(0x401000, 5, Routine, false);
// 在 0x401000 下6 byte JMP [XXX] 钩子,回调先行。
xHook node(0x401000, 6, Routine, true);
// 在 0x401000 下 1 byte UEF 钩子,回调先行。
xHook node(0x401000, 1, Routine, true);
if(node) {
cout << "下钩子出错,错误码:" << node._e;
}
\endcode
\note
- 在 hook 位置复用时,注意根据需要特别注意先后行的选择。
- Routine 由于设计及安全上的考虑, Esp/Rsp 值不可改变(强改也失效)。
其它改变都是允许的,但需要保证程序的继续运行,否则进程崩溃。
- 在 Routine 内部期望修改 EIP/RIP 以达到流程控制效果时,谨慎选择前后行,
推荐使用 "代码先行" ,否则在 EIP/RIP 被修改的情况下覆盖代码将不被执行。
- 采用异常处理实现存在一定风险。在于:当顶层异常处理被其它处理覆盖时,
钩子可能失效,并且这时恢复钩子,将破坏当前处理。(当然,概率较小)
- 罕见使用:当希望使用 UEF 却又需要覆盖 hooksize >= 5 时,
请在回调函数中设置 EIP/RIP 一样可以实现效果,而不能使 hooksize >= 5 实现 UEF 。
- 由于没有添加偏移修正, Hook 范围内不能存在偏移地址,否则旧代码执行出错。
- Hook 保证所有寄存器前后一致,除非回调内部特意修改。
*/
xHook(void* hookmem,
const size_t hooksize,
HookRoutine routine,
const bool routinefirst,
void* p_transfer = nullptr) {
//////////////////////////////////////////////////////////////// 基本检查 及 初始化。
#ifndef _WIN64
UNREFERENCED_PARAMETER(p_transfer);
#endif
if (!check_hookmem(hookmem, hooksize)) return;
if (!check_routine(routine)) return;
_ip = (const void*)((const char*)hookmem + hooksize);
_lpshellcode = nullptr;
_lpfixshellcode = (void*)ShellCodeNormal.data();
_transfer = nullptr;
_oldUEFHandling = (UEFRoutine)-1;
//////////////////////////////////////////////////////////////// 设计 shellcode 。
if (!routinefirst) {
_shellcode << _oldcode; // 代码前行需要先写原始代码。
}
#ifndef _WIN64
_shellcode
<< '\x68' << (AddrDisp)_ip
<< '\x68' << (AddrDisp)_routine
<< "\xFF\x15" << (AddrDisp)&_lpfixshellcode;
if (routinefirst) {
_shellcode << _oldcode; // 代码后行后写原始代码。
}
_shellcode << "\xFF\x25" << (AddrDisp)&(_ip);
#else // _WIN64
_shellcode
<< '\xEB' << '\x18' << _ip << _routine << _lpfixshellcode
<< "\xFF\x35\xE2\xFF\xFF\xFF\xFF\x35\xE4\xFF\xFF\xFF\xFF\x15\xE6\xFF\xFF\xFF";
if (routinefirst) {
_shellcode << _oldcode; // 代码后行后写原始代码。
_shellcode << "\xFF\x25" << (AddrDisp)(0xFFFFFFD0 - hooksize);
} else {
_shellcode << "\xFF\x25" << (AddrDisp)0xFFFFFFD0;
}
#endif // _WIN64
_lpshellcode = _shellcode.data();
//////////////////////////////////////////////////////////////// 设置中转 。
#ifdef _WIN64
switch (_hooksize) {
case 1: case 2: case 3: case 4: break;
case 5:
if (!fix_transfer(p_transfer, false)) return;
break;
case 6: case 7: case 8: case 9:
case 10: case 11: case 12: case 13:
if (!fix_transfer(p_transfer, true)) return;
break;
default: break;
}
#endif // _WIN64
//////////////////////////////////////////////////////////////// 计算 hookcode 。
switch (_hooksize) {
case 1: case 2: case 3: case 4:
mkuef(); break;
#ifndef _WIN64
case 5: {
const size_t addrdisp =
CalcOffset((const char*)_hookmem + 1, _lpshellcode);
_hookcode << '\xE9' << (AddrDisp)addrdisp;
break;
}
default:
_hookcode << "\xFF\x25" << (AddrDisp)&_lpshellcode;
break;
#else // _WIN64
case 5: {
const size_t addrdisp = CalcOffset(
(const char*)_hookmem + 1,
nullptr == _transfer ? _lpshellcode : _transfer);
if (!IsValidAddrDisp(addrdisp)) {
mkuef();
break;
}
_hookcode << '\xE9' << (AddrDisp)addrdisp;
break;
}
case 6: case 7: case 8: case 9:
case 10: case 11: case 12: case 13: {
const size_t addrdisp = CalcOffset(
(const char*)_hookmem + 2,
nullptr == _transfer ? _lpshellcode : _transfer);
if (!IsValidAddrDisp(addrdisp)) {
mkuef();
break;
}
_hookcode << "\xFF\x25" << (AddrDisp)addrdisp;
break;
}
default:
_hookcode << "\xFF\x25" << (AddrDisp)0 << _lpshellcode;
break;
#endif // _WIN64
}
////////////////////////////////////////////////////////////////
_e = Crack(_hookmem, _hookcode);
}
template <typename T>
xHook(T hookmem,
const size_t hooksize,
HookRoutine routine,
const bool routinefirst,
void* p_transfer = nullptr)
: xHook((void*)hookmem, hooksize, routine, routinefirst, p_transfer) {
// 注意,不能在函数体 xHook ,性质不同。必须在初始化列表中初始化。
}
/**
指定 跳转表 或 call 偏移位置,执行 Hook 操作。
\param hookmem 跳转表位置或 call 偏移位置
\param routine 指定的回调函数(声明请参考 HookRoutine )。
\param calltable_offset 指明是跳转表或 call 偏移。
\param routinefirst true: 回调先行, false: 覆盖函数先行。
\param p_transfer 指定中转位置。\n
x64 下用于避免偏移超出而无法 HOOK 。\n
x86 下仅兼容,忽略此参数。\n
跳转表 忽略此参数;\n
call 偏移请提供 0xE byte 空间。
\param expandargc 覆盖函数可能存在参数过多的现象,以调整栈平衡。
\code
int __stdcall Test(int a, int b) { return a + b; }
using func = int (__stdcall *)(int a, int b);
func oldfunc = Test;
void __stdcall Routine(CPU_ST* lpcpu) {
// ...
}
auto x = xHook((void*)&oldfunc, Routine, true, false);
if(!x.IsOK()) {
cout << "下钩子出错,错误码:" << x._e;
}
\endcode
\note
- 覆盖跳转表或 call 偏移位置时,无视覆盖函数的调用格式。
- 注意, routinefirst == true 时, EIP/RIP 为覆盖函数地址, Routine 可选择改变之,但此时请特别注意原函数的调用格式,改变 EIP/RIP 可跳过原函数的执行。routinefirst == false 时, EIP/RIP 为返回地址, Routine 也可选择改变之。
- routinefirst == true 时, Hook 保证寄存器前后一致。 routinefirst == false 时, Hook 保证除 Esp/Rsp 外的寄存器在原函数调用前一致,局部环境一致。 Routine 调用寄存器前后一致。出 Hook 时寄存器一致,局部环境一致。(不因 Hook 而造成任何寄存器变动及栈飘移。)
- 未特殊说明的情况,参考 Hook 函数声明。
*/
xHook(void* hookmem,
HookRoutine routine,
const bool calltable_offset,
const bool routinefirst,
void* p_transfer = nullptr,
const intptr_t expandargc = 0) {
//////////////////////////////////////////////////////////////// 基本检查 及 初始化。
#ifndef _WIN64
UNREFERENCED_PARAMETER(p_transfer);
#endif
const size_t hooksize =
calltable_offset ? sizeof(hookmem) : sizeof(AddrDisp);
if (!check_hookmem(hookmem, hooksize)) return;
if (!check_routine(routine)) return;
_ip = calltable_offset ? *(void**)hookmem
: (void*)(*(AddrDisp*)(hookmem) + (size_t)hookmem + sizeof(AddrDisp));
_lpshellcode = nullptr;
_lpfixshellcode = (void*)ShellCodeCtOff.data();
_transfer = nullptr;
_oldUEFHandling = (UEFRoutine)-1;
//////////////////////////////////////////////////////////////// 设计 shellcode 。
constexpr intptr_t default_argc = 0x8; // 默认参数 8 个。
intptr_t hookargc = default_argc + expandargc;
if (hookargc <= 0) hookargc = default_argc; // 检测不让堆栈错误。
#ifndef _WIN64
_shellcode
<< '\x68' << _ip
<< '\x68' << _routine
<< '\x68' << hookargc
<< '\x6A' << (uint8_t)routinefirst
<< "\xFF\x25" << (AddrDisp)&_lpfixshellcode;
#else
_shellcode
<< "\xEB\x28"
<< _ip << _routine << hookargc
<< (void*)routinefirst << (void*)&_lpfixshellcode
<< "\xFF\x35\xD2\xFF\xFF\xFF\xFF\x35\xD4\xFF\xFF\xFF\xFF\x35\xD6\xFF\xFF\xFF"
"\xFF\x35\xD8\xFF\xFF\xFF\xFF\x35\xDA\xFF\xFF\xFF"
"\x48\x87\x3C\x24\x48\x8B\x3F\x48\x87\x3C\x24\xC3";
#endif
_lpshellcode = _shellcode.data();
//////////////////////////////////////////////////////////////// 设置中转 。
#ifdef _WIN64
if (!calltable_offset) {
if (!fix_transfer(p_transfer, calltable_offset)) return;
}
#endif // _WIN64
//////////////////////////////////////////////////////////////// 计算 hookcode 。
if (calltable_offset) {
_hookcode << _lpshellcode;
} else {
const size_t addrdisp = CalcOffset(
_hookmem,
nullptr == _transfer ? _lpshellcode : _transfer);
if (!IsValidAddrDisp(addrdisp)) {
_e = XHE_AddDisp;
return;
}
_hookcode << (AddrDisp)addrdisp;
}
////////////////////////////////////////////////////////////////
_e = Crack(_hookmem, _hookcode);
}
template <typename T>
xHook(T hookmem,
HookRoutine routine,
const bool calltable_offset,
const bool routinefirst,
void* p_transfer = nullptr,
const intptr_t expandargc = 0)
: xHook((void*)hookmem, routine, calltable_offset, routinefirst, p_transfer, expandargc) {}
public:
/// 偏移计算。
static inline size_t CalcOffset(const void* mem, const void* dest) {
return (size_t)dest - (size_t)mem - sizeof(AddrDisp);
}
/// x64 检测是否有效的 AddrDisp , x86 永远返回 true 。
static inline bool IsValidAddrDisp(const size_t addrdisp) {
#ifdef _WIN64
if ((intptr_t)addrdisp <= (intptr_t)(0x00000000FFFFFFFF) &&
(intptr_t)addrdisp >= (intptr_t)(0xFFFFFFFF80000000)) {
return true;
}
return false;
#else
UNREFERENCED_PARAMETER(addrdisp);
return true;
#endif
}
public:
HOOK_ERROR_ENUM _e; //< 错误码。
void* _hookmem; //< hook 内存位置。
size_t _hooksize; //< hook 写入长度。
HookRoutine _routine; //< 回调地址。
const void* _ip; //< eip/rip 。
const void* _lpshellcode; //< 指向 shellcode 。
const void* _lpfixshellcode; //< 指向 fixshellcode 。
shellcodes _shellcode; //< shellcode 缓冲。
opcodes _oldcode; //< 覆盖前的数据(用于卸载时还原判定)。
opcodes _hookcode; //< 覆盖后的数据(用于卸载时覆盖判定)。
void* _transfer; //< 中转位置。
opcodes _transferdata; //< 中转位置原数据。
UEFRoutine _oldUEFHandling; //< UEF 旧回调。
shellcodes _uefshellcode; //< UEF shellcode 。
private:
#ifndef _WIN64
static inline constexpr size_t ShellcodeNormalPrefix = 0x1C;
static inline constexpr size_t ShellcodeCtOffPrefix = 0x1D;
/**
要求前置 shellcode 如下:
\code
--前置覆盖代码--
$ ==> > 68 XXXXXXXX push EIP
$+5 > 68 XXXXXXXX push Routinue
$+A > FF15 XXXXXXXX call dword ptr [ShellCodeNormal]
--后置覆盖代码--
$+10 > FF25 XXXXXXXX jmp [EIP]
$+16
\endcode
```c++
static __declspec(naked) void ShellCodeNormal() {
__asm {
push dword ptr [esp + 4 * 2] // 参数 EIP 。 ->ret routine
pushfd
pushad
add dword ptr [esp + 4 * 3], 4 * 5// 修正 esp 。 ->edi esi ebp ->fd eip ret routine eip
push esp
call dword ptr [esp + 4 * 12] // 调用 Routine 。 ->esp ad fd eip ret
mov eax, dword ptr [esp + 4 * 9] // 获取参数 EIP 。 ->ad fd
cmp eax, dword ptr [esp + 4 * 12] // 检测是否修改。 ->ad fd eip ret routine
mov dword ptr [esp + 4 * 12], eax // 修改 EIP 。 ->ad fd eip ret routine
popad
jz HookShellCode_Normal_Next
popfd
lea esp, dword ptr [esp + 4 * 3] // 修改则跳过。 ->eip ret
routine retn
HookShellCode_Normal_Next :
popfd
lea esp, dword ptr [esp + 4 * 1] // 仅跳过 EIP ,返回执行可能存在的代码。
retn 4 * 2
add byte ptr [eax], al // 做 0 结尾。
}
}
```
*/
static inline const shellcodes ShellCodeNormal{
"\xFF\x74\x24\x08\x9C\x60\x83\x44\x24\x0C\x14\x54\xFF\x54\x24\x30"
"\x8B\x44\x24\x24\x3B\x44\x24\x30\x89\x44\x24\x30\x61\x74\x06\x9D"
"\x8D\x64\x24\x0C\xC3\x9D\x8D\x64\x24\x04\xC2\x08"};
/**
要求前置 shellcode 如下:
\code
$ ==> > 68 XXXXXXXX push CoverCall
$+5 > 68 XXXXXXXX push Routinue
$+A > 68 XXXXXXXX push HookArgc
$+F > 6A 00|01 push routinefirst
$+11 > FF25 XXXXXXXX jmp dword ptr [ShellCodeCtOff]
$+17
\endcode
```c++
static __declspec(naked) void ShellCodeCtOff() {
__asm {
pushfd
xchg eax, dword ptr [esp] // eax 为 fd ,原始值入栈。
xchg eax, dword ptr [esp + 4 * 1] // eax 为 routinefirst , fd 向下移。
test eax, eax // 判定 routinefirst 。
pop eax // 还原 eax 。
jnz HookShellCode_CtOff_Transit
popfd
push 0x01230814 // 做特征。
push esp
push 0x42104210
mov dword ptr [esp + 4 * 1], esp // 修正特征指向。
pushfd
pushad // 这里不用修正 esp ,修正也没意义。
mov esi, esp
mov ecx, dword ptr [esp + 4 * 12] // 获取 argc 。 ->ad fd # esp #
mov edx, ecx shl ecx, 2
mov ebx, dword ptr [esp + 4 * 14] // 取得 CoverCall 。->ad fd # esp # argc routine
sub esp, ecx // 扩展局部栈。
mov edi, esp
xor ecx, ecx
mov cl, 9 // 复制寄存器保护。
rep movsd
mov cl, 7 // 跳过。 -># esp # argc ro cov ret rep lodsd
mov ecx, edx // 参数复制。
rep movsd
push ebx
pop ebx // 存放临时 CoverCall 。
popad
popfd
call dword ptr [esp - 4 * 10] // call CoverCall ->fd ad CoverCall
push edi
push esi
push ecx
pushfd // 环境保护。
mov edi, esp // edi 指向状态保护。
jmp HookShellCode_CtOff_Chk
HookShellCode_CtOff_Transit:
jmp HookShellCode_CtOff_Base
HookShellCode_CtOff_Chk:
add esp, 4
cmp dword ptr [esp], 0x42104210
jnz HookShellCode_CtOff_Chk
cmp dword ptr [esp + 4], esp
jnz HookShellCode_CtOff_Chk
cmp dword ptr [esp + 8], 0x01230814
jnz HookShellCode_CtOff_Chk
lea esi, dword ptr [esp + 4 * 6] // esi 指向 ret 。 -># esp # argc ro cov
mov ecx, dword ptr [esp + 4 * 3] // 提取 argc 。 -># esp #
shl ecx, 2
add ecx, 4 * 11 // 计算位移。 ->fd ecx esi edi # esp # argc ro cov ret
lea esp, dword ptr [edi + ecx] // esp 指向 real_call_ret 。
push dword ptr [esi - 4 * 0] // ret 。
push dword ptr [esi - 4 * 2] // routine 。
push dword ptr [esi - 4 * 3] // argc 。
xchg edi, esp
popfd // 恢复环境。
pop ecx
pop esi
xchg edi, esp
mov edi, dword ptr [edi]
pushfd
HookShellCode_CtOff_Base:
popfd
push dword ptr [esp + 4 * 2] // 参数 CoverCall 。->argc routine
pushfd
pushad
add dword ptr [esp + 4 * 3], 4 * 5// 修正 esp 。 ->edi esi ebp ->fd eip argc routine eip
push esp
call dword ptr [esp + 4 * 12] // 调用 Routine 。 ->esp ad fd eip argc
popad
popfd
push eax
mov eax, dword ptr [esp + 4 * 1] // 提取参数 CoverCall 。
mov dword ptr [esp + 4 * 4], eax // 重写可能已被修改的 CoverCall 。
pop eax
lea esp, dword ptr [esp + 4 * 3] // 跳过。 ->CoverCall argc routine
retn
add byte ptr [eax], al // 做 0 结尾。
}
}
```
*/