-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSyringeDebugger.cpp
More file actions
1336 lines (1094 loc) · 37.5 KB
/
SyringeDebugger.cpp
File metadata and controls
1336 lines (1094 loc) · 37.5 KB
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
#include "SyringeDebugger.h"
#include "CRC32.h"
#include "FindFile.h"
#include "Handle.h"
#include "Log.h"
#include "Support.h"
#include <algorithm>
#include <array>
#include <fstream>
#include <memory>
#include <numeric>
#include <DbgHelp.h>
#include <Psapi.h>
//using namespace std;
std::vector<std::string> SyringeDebugger::IgnoredDll;
std::map<std::string, SyringeDebugger::DllPatcher*> SyringeDebugger::PatcherMap;
bool SyringeDebugger::LoggerOptions::LogLoadLibFunc = false;
bool SyringeDebugger::LoggerOptions::LogHookRemove = false;
#pragma pack(push, 1)
// 8-bit relative jump.
typedef struct _JMP_REL_SHORT {
UINT8 opcode; // EB xx: JMP +2+xx
UINT8 operand;
static constexpr inline size_t size() {
return sizeof(_JMP_REL_SHORT);
}
} JMP_REL_SHORT, * PJMP_REL_SHORT;
// 32-bit direct relative jump/call.
typedef struct _JMP_REL {
UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx
UINT32 operand; // Relative destination address
static constexpr inline size_t size() {
return sizeof(_JMP_REL);
}
} JMP_REL, * PJMP_REL, CALL_REL;
// 32-bit direct relative conditional jumps.
typedef struct _JCC_REL {
UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx
UINT8 opcode1;
UINT32 operand; // Relative destination address
static constexpr inline size_t size() {
return sizeof(_JCC_REL);
}
} JCC_REL;
#pragma pack(pop)
struct Assembly {
static constexpr BYTE INIT = 0x00,
INT3 = 0xCC,
NOP = 0x90,
CALL = 0xE8,
JMP = 0xE9,
JLE = 0x7E;
static constexpr BYTE const this2fastcall[] = {
0x8B, 0x54, 0xE4, 0x08, //MOV EDX, [ESP + 8]
0x58, // POP EAX
0x89, 0x44, 0xE4, 0x04, // MOV [ESP + 4], EAX
0x89, 0xC8, // MOV EAX, ECX
0x59, // POP ECX
0xFF, 0xE0 // JMP EAX
};
static constexpr auto sizeof_this2fastcall = sizeof(this2fastcall);
static constexpr BYTE const jmp_code_[] = {
0x58, // POP EAX
0x83, 0xC4, 0x04, // ADD ESP, 4
0xFF, 0xE0 // JMP EAX
};
static constexpr size_t sizeof_jmp_code_ = sizeof(jmp_code_);
static constexpr BYTE const load_library[] = {
0x50, // push eax
0x51, // push ecx
0x52, // push edx
0x68, INIT, INIT, INIT, INIT, // push offset pdLibName
0xFF, 0x15, INIT, INIT, INIT, INIT, // call pImLoadLibrary
0x85, 0xC0, // test eax, eax
0x74, 0x0C, // jz
0x68, INIT, INIT, INIT, INIT, // push offset pdProcName
0x50, // push eax
0xFF, 0x15, INIT, INIT, INIT, INIT, // call pdImGetProcAddress
0xA3, INIT, INIT, INIT, INIT, // mov pdProcAddress, eax
0x5A, // pop edx
0x59, // pop ecx
0x58, // pop eax
INT3, NOP // int3 and some padding
};
static constexpr size_t sizeof_load_library = sizeof(load_library);
static constexpr BYTE const load_library_NoProc[] = {
0x68, INIT, INIT, INIT, INIT, // push offset pdLibName
0xFF, 0x15, INIT, INIT, INIT, INIT, // call pImLoadLibrary
//INT3, NOP , NOP , NOP , NOP , NOP , // int3 and some padding
//NOP, NOP, NOP, NOP, NOP, NOP, NOP,
//NOP, NOP, NOP, NOP, NOP, NOP, NOP,
//NOP, NOP, NOP, NOP, NOP, NOP, NOP ,
//NOP, NOP
};
static constexpr size_t sizeof_load_library_NoProc = sizeof(load_library_NoProc);
//constexpr static BYTE const hook_code_call_old[] = {
// 0x60, 0x9C, // PUSHAD, PUSHFD
// 0x68, INIT, INIT, INIT, INIT, // PUSH HookAddress
// 0x54, // PUSH ESP
// 0xE8, INIT, INIT, INIT, INIT, // CALL ProcAddress
// 0x83, 0xC4, 0x08, // ADD ESP, 8
// 0xA3, INIT, INIT, INIT, INIT, // MOV ds:JmpBack, EAX
// 0x9D, 0x61, // POPFD, POPAD
// 0x83, 0x3D, INIT, INIT, INIT, INIT, 0x00, // CMP ds:JmpBack, 0
// 0x74, 0x06, // JZ .proceed
// 0xFF, 0x25, INIT, INIT, INIT, INIT, // JMP ds:JmpBack
//};
//static constexpr size_t sizeof_hook_code_call_old = sizeof(hook_code_call_old);
constexpr static BYTE const hook_code_call[] = {
0x60, 0x9C, // PUSHAD, PUSHFD
0x68, INIT, INIT, INIT, INIT, // PUSH HookAddress
0x54, // PUSH ESP
CALL, INIT, INIT, INIT, INIT, // insert E8 (CALL) ProcAddress
0x83, 0xC4, 0x08, // ADD ESP, 8
0x89, 0x44, 0x24, 0xFC,// MOV ds:JmpBack, EAX
0x9D, 0x61, // POPFD, POPAD
0x83, 0x7C, 0x24, 0xD8, INIT, 0x74,// CMP ds:JmpBack, 0
0x04, 0xFF, // JZ .proceed
0x64, 0x24, 0xD8 , INIT , INIT , INIT// JMP ds:JmpBack
};
static constexpr size_t sizeof_hook_code_call = sizeof(hook_code_call);
static_assert(sizeof_hook_code_call == 36u, "Invalid Size!");
//constexpr static BYTE const hoke_code_call_DP[] = {
// 0x60, 0x9C, //PUSHAD, PUSHFD
// 0x68, INIT, INIT, INIT, INIT, //PUSH HookAddress
// 0x83, 0xEC, 0x04,//SUB ESP, 4
// 0x8D, 0x44, 0x24, 0x04,//LEA EAX,[ESP + 4]
// 0x50, //PUSH EAX
// 0xE8, INIT, INIT, INIT, INIT, //CALL ProcAddress
// 0x83, 0xC4, 0x0C, //ADD ESP, 0Ch
// 0x89, 0x44, 0x24, 0xF8,//MOV ss:[ESP - 8], EAX
// 0x9D, 0x61, //POPFD, POPAD
// 0x83, 0x7C, 0x24, 0xD4, 0x00,//CMP ss:[ESP - 2Ch], 0
// 0x74, 0x04, //JZ .proceed
// 0xFF, 0x64, 0x24, 0xD4 //JMP ss:[ESP - 2Ch]
//};
//static constexpr size_t sizeof_hoke_code_call_DP = sizeof(hoke_code_call_DP);
//constexpr static BYTE const jmp[] = { 0xE9, INIT, INIT, INIT, INIT };
//static constexpr size_t sizeof_jmp = sizeof(jmp);
//constexpr static BYTE const call[] = { 0xE8, INIT, INIT, INIT, INIT };
//static constexpr size_t sizeof_call = sizeof(call);
struct JumpStruct {
uintptr_t From;
uintptr_t To;
uintptr_t getOffset() const {
return To - From - JMP_REL::size();
}
};
//template<typename T>
//static bool ReadFromAddr(uintptr_t address, T& obj) {
// BYTE mem[sizeof(T)];
// bool ret = SyringeDebugger::ReadMem((void*)address, mem, sizeof(T));
// std::memcpy(obj, mem, sizeof(T));
// return ret;
//}
};
void SyringeDebugger::ApplyPatches() { }
//TODO : Other Type of hook supports !
/*
* Apply patch:
* Type -> raw
* -> address
*/
void SyringeDebugger::DebugProcess(std::string_view const arguments) {
STARTUPINFO startupInfo{ sizeof(startupInfo) };
SetEnvironmentVariable("_NO_DEBUG_HEAP", "1");
auto command_line = '"' + exe + "\" ";
command_line += arguments;
if (CreateProcess(
exe.c_str(), command_line.data(), nullptr, nullptr, false,
DEBUG_ONLY_THIS_PROCESS | CREATE_SUSPENDED,
nullptr, nullptr, &startupInfo, &pInfo) == FALSE)
{
throw_lasterror_or(ERROR_ERRORS_ENCOUNTERED, exe);
}
}
bool SyringeDebugger::PatchMem(void* address, void const* buffer, DWORD size) {
BOOL result = WriteProcessMemory(pInfo.hProcess, address, buffer, size, nullptr);
if (result == FALSE) {
DWORD oldprotect_flag;
VirtualProtectEx(pInfo.hProcess, address, size, PAGE_EXECUTE_READWRITE, &oldprotect_flag);
result = WriteProcessMemory(pInfo.hProcess, address, buffer, size, nullptr);
VirtualProtectEx(pInfo.hProcess, address, size, oldprotect_flag, &oldprotect_flag);
} else {
return true;
}
if (result != FALSE) {
return true;
}
Log::WriteLine(
__FUNCTION__ "[%x] Error [%s] ", (uintptr_t)address, std::system_category().message(GetLastError()).c_str());
return false;
}
bool SyringeDebugger::ReadMem(void const* address, void* destinationbuffer, DWORD size) {
const auto result = ReadProcessMemory(pInfo.hProcess, address, destinationbuffer, size, nullptr);
if (result != FALSE)
{
return true;
}
Log::WriteLine(
__FUNCTION__ "[%x] Error [%s]", (uintptr_t)address, std::system_category().message(GetLastError()).c_str());
//throw_lasterror_or(ERROR_ERRORS_ENCOUNTERED, exe);
return false;
}
VirtualMemoryHandle SyringeDebugger::AllocMem(void* address, size_t size) {
if (VirtualMemoryHandle res{ pInfo.hProcess, address, size })
{
return res;
}
throw_lasterror_or(ERROR_ERRORS_ENCOUNTERED, exe);
}
bool SyringeDebugger::SetBP(void* address) {
// save overwritten code and set INT 3
if (auto& opcode = Breakpoints[address].original_opcode; opcode == 0x00)
{
auto const buffer = Assembly::INT3;
ReadMem(address, &opcode, 1);
return PatchMem(address, &buffer, 1);
}
return true;
}
DWORD __fastcall SyringeDebugger::GetRelativeOffset(void const* pFrom, void const* pTo) {
auto const from = reinterpret_cast<DWORD>(pFrom);
auto const to = reinterpret_cast<DWORD>(pTo);
return to - from;
}
//void __declspec(noinline) SyringeDebugger::WriteHooks(MemoryHelper& tempmemory, eipptr breakpoints_entry, BreakpointInfo& breakpoins_breaks, const HooksAccumulateData& hooks_, int idx) {
//
//
//}
DWORD SyringeDebugger::HandleException(DEBUG_EVENT const& dbgEvent) {
auto const exceptCode = dbgEvent.u.Exception.ExceptionRecord.ExceptionCode;
auto const exceptAddr = dbgEvent.u.Exception.ExceptionRecord.ExceptionAddress;
switch (exceptCode)
{
case EXCEPTION_BREAKPOINT:
{
auto& threadInfo = Threads[dbgEvent.dwThreadId];
HANDLE currentThread = threadInfo.Thread;
CONTEXT context;
context.ContextFlags = CONTEXT_CONTROL;
GetThreadContext(currentThread, &context);
// entry breakpoint
if (bEntryBP)
{
bEntryBP = false;
return DBG_CONTINUE;
}
// fix single step repetition issues
if (context.EFlags & 0x100)
{
auto const buffer = Assembly::INT3;
context.EFlags &= ~0x100;
PatchMem(threadInfo.lastBP, &buffer, 1);
}
// load DLLs and retrieve proc addresses
if (!bDLLsLoaded)
{
// restore
PatchMem(exceptAddr, &Breakpoints[exceptAddr].original_opcode, 1);
if (loop_LoadLibrary == v_AllHooks.end())
{
loop_LoadLibrary = v_AllHooks.begin();
}
else
{
auto const& hook = *loop_LoadLibrary;
ReadMem(&GetData()->ProcAddress, &hook->proc_address, 4);
if (!hook->proc_address)
{
Log::WriteLine(
__FUNCTION__ ": Could not retrieve ProcAddress for: %s "
"- %s", hook->lib, hook->proc);
}
++loop_LoadLibrary;
}
if (loop_LoadLibrary != v_AllHooks.end())
{
auto const& hook = *loop_LoadLibrary;
auto pData = this->GetData();
PatchMem(&pData->LibName, hook->lib, MaxNameLength);
if (_strcmpi(hook->lib , "cncnet5.dll") == 0) {
char dllMain[] = { "DllMain" };
PatchMem(&pData->ProcName, dllMain, sizeof(dllMain));
//
// std::array<BYTE, Assembly::sizeof_load_library> dummy;
// ApplyPatch(dummy.data(), Assembly::load_library_NoProc);
// ApplyPatch(dummy.data() + 0x01, &pData->LibName);
// ApplyPatch(dummy.data() + 0x07, this->pImLoadLibrary);
//
// if (!PatchMem(&pData->LoadLibraryFunc, dummy.data(), Assembly::sizeof_load_library)
// ) {
// Log::WriteLine(__FUNCTION__ ": LoadLibrary patching failed !");
// } else {
// Log::WriteLine(__FUNCTION__ ": Dll[%s] Has no proper proc_addres of [%s] patching the LoadLibrary to alternative version !", hook->lib , hook->proc);
// }
} else {
PatchMem(&pData->ProcName, hook->proc, MaxNameLength);
}
context.Eip = reinterpret_cast<DWORD>(&pData->LoadLibraryFunc);
if (SyringeDebugger::LoggerOptions::LogLoadLibFunc)
Log::WriteLine(__FUNCTION__ ": Executing LoadLibraryFunc [proc : %s - Lib :%s]", hook->proc, hook->lib);
}
else
{
Log::WriteLine(__FUNCTION__ ": Finished retrieving proc addresses.");
bDLLsLoaded = true;
context.Eip = reinterpret_cast<DWORD>(pcEntryPoint);
}
// single step mode
context.EFlags |= 0x100;
context.ContextFlags = CONTEXT_CONTROL;
SetThreadContext(currentThread, &context);
threadInfo.lastBP = exceptAddr;
return DBG_CONTINUE;
}
if (exceptAddr == pcEntryPoint)
{
if (!bHooksCreated)
{
Log::WriteLine(__FUNCTION__ ": Creating code hooks.");
//temporary vector for code Byte
MemoryHelper tempmemory{};
MemoryHelper overridenMem{};
for (auto& [breakpoints_entry, breakpoins_breaks] : Breakpoints)
{
tempmemory.clear();
overridenMem.clear();
if (breakpoints_entry == nullptr || breakpoints_entry == pcEntryPoint)
{
continue;
}
// count = how much hook is present
// overridden = number of overriden of the hook
HooksAccumulateData hooks_{ 0u , 0u };
// normalize the numOverriden
for (const auto& hook : breakpoins_breaks.hooks)
{
if (hook.proc_address && ((uintptr_t)hook.proc_address) != 0x0)
{
if (hooks_.numOverriden < hook.num_overridden)
{
hooks_.numOverriden = hook.num_overridden;
}
hooks_.count++;
}
}
if (hooks_.count <= 0)
{
continue;
}
//Formulate the hook function
//calculate final sizes
const auto totalHookSize = hooks_.count * Assembly::sizeof_hook_code_call;
const auto sz = totalHookSize + JMP_REL::size() + hooks_.numOverriden;
tempmemory.resize(sz);
BYTE* memoryptr = tempmemory.data();
// hook address to be called
breakpoins_breaks.p_caller_code = AllocMem(nullptr, sz);
bool checked = false;
bool needProtect = false;
//MessageBoxA(
// nullptr, "Syringe Is halted before run",
// reinterpret_cast<LPCSTR>("TEST"), MB_OK | MB_ICONINFORMATION);
for (size_t i = 0; i < hooks_.count; ++i)
{
const auto& hook = breakpoins_breaks.hooks[i];
if (hook.proc_address)
{
if (!checked && hook.num_overridden > 0)
{
//read the overriden bytes
overridenMem.resize(hook.num_overridden);
ReadMem(breakpoints_entry, overridenMem.data(), hooks_.numOverriden);
//found jump or call opcode
if (overridenMem[0] == Assembly::CALL || overridenMem[0] == Assembly::JMP || overridenMem[0] == Assembly::JLE)
{
Log::WriteLine(
__FUNCTION__ ":Hook at [0x%x = %s , %d] Possibly destroying jmp or call", breakpoints_entry, hook.proc, hook.num_overridden);
needProtect = true;
}
checked = true;
}
else if (!hook.num_overridden)
{
Log::WriteLine(
__FUNCTION__ ":Hook at [0x%x = %s , %d] cannot be identified because it 0 overriden jmp or call", breakpoints_entry, hook.proc, hook.num_overridden);
}
// write hook caller code
ApplyPatch(memoryptr, Assembly::hook_code_call, 33u); // code
//replace the code that needed
ApplyPatch(memoryptr + 0x03, breakpoints_entry); // PUSH HookAddress
const auto hook_call_rel = GetRelativeOffset(
breakpoins_breaks.p_caller_code.get() + (memoryptr - tempmemory.data() + 0x0D)
, hook.proc_address
);
//MessageBoxA(
// nullptr, "Syringe Is halted before run",
// reinterpret_cast<LPCSTR>("TEST"), MB_OK | MB_ICONINFORMATION);
CALL_REL relative_call{ Assembly::CALL , hook_call_rel };
//on the original syringe source this was 0x09
// replaced to 0x08 since the operand from CALL_REL will be copied too
ApplyPatch(memoryptr + 0x08, relative_call);
memoryptr += 0x21; //advance the iterator
}
}
// write overridden bytes to the end
// this for return 0 case ,..
if (!overridenMem.empty())
{
// temporary memory data is on top
// dont need to read , just move the data
ApplyPatch_NoMove(memoryptr, overridenMem.data(), overridenMem.size());
memoryptr += overridenMem.size();
}
// write the jump back for return
const auto jmp_back_rel = GetRelativeOffset(
breakpoins_breaks.p_caller_code.get() + (memoryptr - tempmemory.data() + JMP_REL::size()),
static_cast<BYTE*>(breakpoints_entry) + std::max(hooks_.numOverriden, JMP_REL::size()));
JMP_REL jmp_back{ Assembly::JMP , jmp_back_rel };
ApplyPatch(memoryptr, jmp_back);
//ApplyPatch(memoryptr + 0x01, jmp_back_rel);
//write finished hook data to reserved memory
PatchMem(breakpoins_breaks.p_caller_code.get(), tempmemory.data(), tempmemory.size());
// replace the original instruction with hook call
tempmemory.resize(sz);
// move the hook data to temp memory
ReadMem(breakpoins_breaks.p_caller_code.get(), tempmemory.data(), sz);
const auto p_original_code = static_cast<BYTE*>(breakpoints_entry);
const auto originalcode_rel = GetRelativeOffset(p_original_code + JMP_REL::size(), breakpoins_breaks.p_caller_code.get());
//resize the temp memory then fill it with NOP
tempmemory.assign(std::max(hooks_.numOverriden, JMP_REL::size()), Assembly::NOP);
//apply the jump opcode
JMP_REL hookjmpOpcode{ Assembly::JMP , originalcode_rel };
ApplyPatch(tempmemory.data(), hookjmpOpcode);
//insert the jump back address
//ApplyPatch(tempmemory.data() + 0x01, originalcode_rel);
//patch the memory to the destination
PatchMem(p_original_code, tempmemory.data(), tempmemory.size());
}
Log::Flush();
bHooksCreated = true;
}
// restore
PatchMem(exceptAddr, &Breakpoints[exceptAddr].original_opcode, 1);
// single step mode
context.EFlags |= 0x100;
--context.Eip;
context.ContextFlags = CONTEXT_CONTROL;
SetThreadContext(currentThread, &context);
threadInfo.lastBP = exceptAddr;
return DBG_CONTINUE;
}
else
{
// could be a Debugger class breakpoint to call a patching function!
context.ContextFlags = CONTEXT_CONTROL;
SetThreadContext(currentThread, &context);
return DBG_EXCEPTION_NOT_HANDLED;
}
}
case EXCEPTION_SINGLE_STEP:
{
BYTE buffer = Assembly::INT3;
auto const& threadInfo = Threads[dbgEvent.dwThreadId];
PatchMem(threadInfo.lastBP, &buffer, 1);
HANDLE hThread = threadInfo.Thread;
CONTEXT context;
context.ContextFlags = CONTEXT_CONTROL;
GetThreadContext(hThread, &context);
context.EFlags &= ~0x100;
context.ContextFlags = CONTEXT_CONTROL;
SetThreadContext(hThread, &context);
return DBG_CONTINUE;
}
default:
{
if (!bAVLogged)
{
Log::WriteLine(__FUNCTION__ ": Exception Code: 0x%08X at 0x%08X!", exceptCode, exceptAddr);
auto const& threadInfo = Threads[dbgEvent.dwThreadId];
HANDLE currentThread = threadInfo.Thread;
char const* access = "";
switch (dbgEvent.u.Exception.ExceptionRecord.ExceptionInformation[0])
{
case 0: access = "read from"; break;
case 1: access = "write to"; break;
case 8: access = "execute"; break;
}
Log::WriteLine("\tThe process tried to %s 0x%08X.",
access,
dbgEvent.u.Exception.ExceptionRecord.ExceptionInformation[1]);
if (pInfo.hProcess != INVALID_HANDLE_VALUE)
{
// Enumerate the loaded modules in the process
HMODULE hModules[1024];
DWORD cbNeeded;
if (EnumProcessModules(pInfo.hProcess , hModules, sizeof(hModules), &cbNeeded))
{
const int moduleCount = static_cast<int>(cbNeeded / sizeof(HMODULE));
for (int i = 0; i < moduleCount; ++i)
{
// Get the base name of the module
CHAR moduleName[MAX_PATH] = { 0 };
if (GetModuleBaseNameA(pInfo.hProcess , hModules[i], moduleName, sizeof(moduleName)))
{
// Get information about the module
MODULEINFO info = { 0 };
if (GetModuleInformation(pInfo.hProcess , hModules[i], &info, sizeof(info)))
{
_strlwr_s(moduleName);
moduleName[0] &= ~0x20; // LOL HACK to uppercase a letter
Log::WriteLine("Loaded Module for [%d] %d[%s - %x]" , pInfo.dwProcessId , i ,moduleName , (uintptr_t)info.lpBaseOfDll);
}
}
}
}
}
CONTEXT context;
context.ContextFlags = CONTEXT_FULL;
GetThreadContext(currentThread, &context);
Log::WriteLine();
Log::WriteLine("Registers:");
Log::WriteLine("\tEAX = 0x%08X\tECX = 0x%08X\tEDX = 0x%08X",
context.Eax, context.Ecx, context.Edx);
Log::WriteLine("\tEBX = 0x%08X\tESP = 0x%08X\tEBP = 0x%08X",
context.Ebx, context.Esp, context.Ebp);
Log::WriteLine("\tESI = 0x%08X\tEDI = 0x%08X\tEIP = 0x%08X",
context.Esi, context.Edi, context.Eip);
Log::WriteLine();
Log::WriteLine("\tStack dump:");
auto const esp = reinterpret_cast<DWORD*>(context.Esp);
for (auto p = esp; p < &esp[0x100]; ++p)
{
DWORD dw;
if (ReadMem(p, &dw, 4))
{
Log::WriteLine("\t0x%08X:\t0x%08X", p, dw);
}
else
{
Log::WriteLine("\t0x%08X:\t(could not be read)", p);
}
}
Log::WriteLine();
bAVLogged = true;
}
return DBG_EXCEPTION_NOT_HANDLED;
}
}
return DBG_CONTINUE;
}
void SyringeDebugger::Run(std::string_view const arguments) {
constexpr auto AllocDataSize = sizeof(AllocData);
Log::WriteLine(
__FUNCTION__ ": Running process to debug. cmd = \"%s %.*s\"",
exe.c_str(), printable(arguments));
DebugProcess(arguments);
BYTE buffer;
if (!((DWORD)this->pcEntryPoint) || !ReadMem(this->pcEntryPoint, &buffer, 1u))
{
Log::WriteLine(
__FUNCTION__ ": Invalid EntryPoint Address");
return;
}
Log::WriteLine(__FUNCTION__ ": Allocating 0x%u bytes...", AllocDataSize);
pAlloc = AllocMem(nullptr, AllocDataSize);
const auto pData = this->GetData();
Log::WriteLine(__FUNCTION__ ": pAlloc = 0x%08X", pData);
// write DLL loader code
Log::WriteLine(__FUNCTION__ ": Writing DLL loader & caller code...");
std::array<BYTE, AllocDataSize> dummy;
ApplyPatch(dummy.data(), Assembly::load_library);
ApplyPatch(dummy.data() + 0x04, &pData->LibName);
ApplyPatch(dummy.data() + 0x0A, pImLoadLibrary);
ApplyPatch(dummy.data() + 0x13, &pData->ProcName);
ApplyPatch(dummy.data() + 0x1A, pImGetProcAddress);
ApplyPatch(dummy.data() + 0x1F, &pData->ProcAddress);
//BYTE buffer;
if (!PatchMem(pData, dummy.data(), AllocDataSize)
//|| !*((DWORD*)this->pcEntryPoint)
//|| !ReadMem(this->pcEntryPoint, &buffer, 1u)
)
{
Log::WriteLine(__FUNCTION__ ": LoadLibrary patching failed !");
return;
}
Log::WriteLine(__FUNCTION__ ": pcLoadLibrary = 0x%08X", &pData->LoadLibraryFunc);
// breakpoints for DLL loading and proc address retrieving
bDLLsLoaded = false;
bHooksCreated = false;
loop_LoadLibrary = v_AllHooks.end();
// set breakpoint
SetBP(pcEntryPoint); //add break point list
DEBUG_EVENT dbgEvent;
ResumeThread(pInfo.hThread);
bAVLogged = false;
Log::WriteLine(__FUNCTION__ ": Entering debug loop...");
auto exit_code = static_cast<DWORD>(-1);
for (;;)
{
WaitForDebugEvent(&dbgEvent, INFINITE);
DWORD continueStatus = DBG_CONTINUE;
bool wasBP = false;
switch (dbgEvent.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
pInfo.hProcess = dbgEvent.u.CreateProcessInfo.hProcess;
pInfo.dwThreadId = dbgEvent.dwProcessId;
pInfo.hThread = dbgEvent.u.CreateProcessInfo.hThread;
pInfo.dwThreadId = dbgEvent.dwThreadId;
Threads.emplace(dbgEvent.dwThreadId, dbgEvent.u.CreateProcessInfo.hThread);
CloseHandle(dbgEvent.u.CreateProcessInfo.hFile);
break;
case CREATE_THREAD_DEBUG_EVENT:
Threads.emplace(dbgEvent.dwThreadId, dbgEvent.u.CreateThread.hThread);
break;
case EXIT_THREAD_DEBUG_EVENT:
if (auto const it = Threads.find(dbgEvent.dwThreadId); it != Threads.end())
{
it->second.Thread.release();
Threads.erase(it);
}
break;
case EXCEPTION_DEBUG_EVENT:
continueStatus = HandleException(dbgEvent);
wasBP = (dbgEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT);
break;
case LOAD_DLL_DEBUG_EVENT:
CloseHandle(dbgEvent.u.LoadDll.hFile);
break;
case OUTPUT_DEBUG_STRING_EVENT:
break;
}
if (dbgEvent.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
{
exit_code = dbgEvent.u.ExitProcess.dwExitCode;
break;
}
else if (dbgEvent.dwDebugEventCode == RIP_EVENT)
{
break;
}
ContinueDebugEvent(dbgEvent.dwProcessId, dbgEvent.dwThreadId, continueStatus);
}
CloseHandle(pInfo.hProcess);
Log::WriteLine(
__FUNCTION__ ": Done with exit code %X (%u).", exit_code, exit_code);
Log::WriteLine();
}
void SyringeDebugger::RemoveBP(LPVOID const address, bool const restoreOpcode) {
if (auto const i = Breakpoints.find(address); i != Breakpoints.end())
{
if (restoreOpcode)
{
if (PatchMem(address, &i->second.original_opcode, 1))
Log::WriteLine("Syringe Attempt to Remove[%X] Break points", address);
}
Breakpoints.erase(i);
}
}
void SyringeDebugger::RetrieveInfo() {
Log::WriteLine(
__FUNCTION__ ": Retrieving info from the executable file...");
try
{
PortableExecutable pe{ exe };
auto const dwImageBase = pe.GetImageBase();
// creation time stamp
dwTimeStamp = pe.GetPEHeader().FileHeader.TimeDateStamp;
// entry point
pcEntryPoint = reinterpret_cast<void*>(dwImageBase + pe.GetPEHeader().OptionalHeader.AddressOfEntryPoint);
// get imports
pImLoadLibrary = nullptr;
pImGetProcAddress = nullptr;
for (auto const& import : pe.GetImports())
{
if (_strcmpi(import.Name.c_str(), "KERNEL32.DLL") == 0)
{
for (auto const& thunk : import.vecThunkData)
{
if (_strcmpi(thunk.Name.c_str(), "GETPROCADDRESS") == 0)
{
pImGetProcAddress = reinterpret_cast<void*>(dwImageBase + thunk.Address);
}
else if (_strcmpi(thunk.Name.c_str(), "LOADLIBRARYA") == 0)
{
pImLoadLibrary = reinterpret_cast<void*>(dwImageBase + thunk.Address);
}
}
}
}
} catch (...)
{
Log::WriteLine(__FUNCTION__ ": Failed to open the executable!");
throw;
}
if (!pImGetProcAddress || !pImLoadLibrary)
{
Log::WriteLine(
__FUNCTION__ ": ERROR: Either a LoadLibraryA or a GetProcAddress "
"import could not be found!");
throw_lasterror_or(ERROR_PROC_NOT_FOUND, exe);
}
// read meta information: size and checksum
if (std::ifstream is{ exe, std::ifstream::binary })
{
is.seekg(0, std::ifstream::end);
dwExeSize = static_cast<DWORD>(is.tellg());
is.seekg(0, std::ifstream::beg);
CRC32 crc;
char buffer[0x1000];
while (auto const read = is.read(buffer, std::size(buffer)).gcount())
{
crc.compute(buffer, read);
}
dwExeCRC = crc.value();
}
Log::WriteLine(__FUNCTION__ ": Executable information successfully retrieved.");
Log::WriteLine(__FUNCTION__ ": Opening %s to determine imports.", exe.c_str());
Log::WriteLine("\texe = %s", exe.c_str());
Log::WriteLine("\tpImLoadLibrary = 0x%08X", pImLoadLibrary);
Log::WriteLine("\tpImGetProcAddress = 0x%08X", pImGetProcAddress);
Log::WriteLine("\tpcEntryPoint = 0x%08X", pcEntryPoint);
Log::WriteLine("\tdwExeSize = 0x%08X", dwExeSize);
Log::WriteLine("\tdwExeCRC = 0x%08X", dwExeCRC);
Log::WriteLine("\tdwTimestamp = 0x%08X", dwTimeStamp);
Log::WriteLine();
}
#include <sstream>
std::string convert_int(int n) {
std::stringstream ss;
ss << n;
return ss.str();
}
void SyringeDebugger::FindDLLs() {
Breakpoints.clear();
HookOverrideBuffer buffer_remove;
for (auto file = FindFile("*.dll"); file; ++file)
{
std::string_view const fn(file->cFileName);
if (!IgnoredDll.empty())
{
const auto Iter = std::find_if(IgnoredDll.begin(), IgnoredDll.end(), [&](const auto& nStr) { return nStr == fn; });
if (Iter != IgnoredDll.end())
{
Log::WriteLine(__FUNCTION__ ": Ignoring DLL: \"%.*s\"", printable(fn));
continue;
}
}
//Log::WriteLine(
// __FUNCTION__ ": Potential DLL: \"%.*s\"", printable(fn));
try
{
PortableExecutable const DLL{ fn };
HookBuffer buffer;
bool canLoad = false;
if (auto const hooks = DLL.FindSection(".syhks00"))
{
canLoad = ParseHooksSection(DLL, *hooks, buffer);
}
if (canLoad)
{
Log::WriteLine(
__FUNCTION__ ": Recognized DLL: \"%.*s\"", printable(fn));
if (auto const hooks = DLL.FindSection(".syhks01"))
{
if (ParseOverrideHooksSection(DLL, *hooks, buffer_remove, buffer))
Log::WriteLine(
__FUNCTION__ ": Found Override Hook Section : \"%.*s\"", printable(fn));
}
if (auto const res = Handshake(
DLL.GetFilename(), static_cast<int>(buffer.count),
buffer.checksum.value()))
{
canLoad = res;
}
else if (auto const hosts = DLL.FindSection(".syexe00"))
{
canLoad = CanHostDLL(DLL, *hosts);
}
}
if (canLoad)
{
for (auto const& [eip, hooks] : buffer.hooks)
{
auto& h = Breakpoints[eip];
h.p_caller_code.clear();
h.original_opcode = 0x00;
h.hooks.insert(h.hooks.end(), hooks.begin(), hooks.end());
}
}
else if (!buffer.hooks.empty())
{
Log::WriteLine(
__FUNCTION__ ": DLL load was prevented: \"%.*s\"",
printable(fn));
}
} catch (...)
{
Log::WriteLine(
__FUNCTION__ ": DLL Parse failed: \"%.*s\"", printable(fn));
}
}
// summarize all hooks
v_AllHooks.clear();
SyringeDebugger::RemoveBreakPoints(Breakpoints, buffer_remove);
for (auto& it : Breakpoints)
{
for (auto& data : it.second.hooks)
{
auto const nTempData = convert_int(data.hookaddr);