-
Notifications
You must be signed in to change notification settings - Fork 80
/
Debugger.pas
2228 lines (1930 loc) · 69.7 KB
/
Debugger.pas
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
unit Debugger;
interface
uses Windows, SysUtils, Classes, Utils, TlHelp32, Generics.Collections, Dumper, Patcher, Tracer;
type
THWBPType = (hwExecute, hwWrite, hwReserved, hwAccess);
TBreakpoint = record
Address: NativeUInt;
BType: THWBPType;
Disabled: Boolean;
procedure Change(AAddress: NativeUInt; AType: THWBPType);
function IsSet: Boolean;
end;
TMemoryRegion = record
Address: NativeUInt;
Size: Cardinal;
function Contains(Addr: NativeUInt): Boolean;
end;
TEFLRecord = record
Address: NativeUInt;
Original: TBytes;
end;
TDebugger = class(TThread)
private
FExecutable, FParameters: string;
FCreateDataSections: Boolean;
FProcess: TProcessInformation;
FImageBase, FBaseOfData: NativeUInt;
FPESections: array of TImageSectionHeader;
FMajorLinkerVersion: Byte;
FHideThreadEnd: Boolean;
FWow64: LongBool;
FHW1, FHW2, FHW3, FHW4: TBreakpoint;
FThreads: TDictionary<Cardinal, THandle>;
FCurrentThreadID: Cardinal;
FMemRegions: array of TMemoryRegion;
FSoftBPs: TDictionary<Pointer, Byte>;
FSoftBPReenable: Cardinal;
// Themida
FImageBoundary: NativeUInt;
FBaseAccessCount: Integer;
FCompressed: Boolean;
TMSect: PByte;
TMSectR: TMemoryRegion;
Base1, RepEIP, NtQIP: NativeUInt;
CloseHandleAPI, AllocMemAPI, AllocHeapAPI, KiFastSystemCall, NtSIT, NtQIP64, VirtualProtectAPI: Pointer;
CmpImgBase, MagicJump, MagicJumpV1: Pointer;
BaseAccessed, NewVer, AncientVer: Boolean;
AllocMemCounter: Integer;
IJumper, MJ_1, MJ_2, MJ_3, MJ_4: NativeUInt;
EFLs: array[0..2] of TEFLRecord;
FThemidaV3, FThemidaV2BySections, FIsVMOEP: Boolean;
FTracedAPI: NativeUInt;
FSleepAPI, FlstrlenAPI: NativeUInt;
FTraceStartSP: NativeUInt;
FTraceInVM: Boolean;
FGuardStart, FGuardEnd: NativeUInt;
FGuardProtection: Integer;
FGuardStepping: Boolean;
FGuardAddrs: TList<NativeUInt>;
FTLSAddressesOfCallbacks: Cardinal;
FTLSCounter, FTLSTotal: Cardinal;
function PEExecute: Boolean;
procedure FetchMemoryRegions;
function OnCreateThreadDebugEvent(var DebugEv: TDebugEvent): DWORD;
function OnCreateProcessDebugEvent(var DebugEv: TDebugEvent): DWORD;
function OnExitThreadDebugEvent(var DebugEv: TDebugEvent): DWORD;
function OnLoadDllDebugEvent(var DebugEv: TDebugEvent): DWORD;
function OnExitProcessDebugEvent(var DebugEv: TDebugEvent): DWORD;
function OnUnloadDllDebugEvent(var DebugEv: TDebugEvent): DWORD;
function OnOutputDebugStringEvent(var DebugEv: TDebugEvent): DWORD;
function OnRipEvent(var DebugEv: TDebugEvent): DWORD;
function OnHardwareBreakpoint(var DebugEv: TDebugEvent): DWORD;
function OnSoftwareBreakpoint(var DebugEv: TDebugEvent): DWORD;
function RPM(Address: NativeUInt; Buf: Pointer; BufSize: NativeUInt): Boolean;
function FindDynamicTM(const APattern: AnsiString; AOff: Cardinal = 0): Cardinal;
function FindStaticTM(const APattern: AnsiString; AOff: Cardinal = 0): Cardinal;
procedure SelectThemidaSection(EIP: NativeUInt);
procedure TMInit(var hPE: THandle);
function TMFinderCheck(C: PContext): Boolean;
procedure TMIATFix(EIP: NativeUInt);
procedure TMIATFix2;
procedure TMIATFix3(EIP: NativeUInt);
procedure TMIATFix4;
procedure TMIATFix5(Eax: NativeUInt);
procedure TMIATFixThemidaV1(BaseCompare1: NativeUInt);
function GetIATBPAddressNew(var Res: NativeUInt): Boolean;
function InstallEFLPatch(EIP: Pointer; var C: TContext; var Rec: TEFLRecord): Boolean;
procedure InstallCodeSectionGuard(Protection: Cardinal);
function IsGuardedAddress(Address: NativeUInt): Boolean;
function ProcessGuardedAccess(hThread: THandle; var ExcRecord: TExceptionRecord): Cardinal;
procedure RestoreStolenOEPForMSVC6(hThread: THandle; var OEP: NativeUInt);
procedure CheckVirtualizedOEP(OEP: NativeUInt);
function TryFindCorrectOEP(OEP: NativeUInt): NativeUInt;
function IsTMExceptionHandler(Address: NativeUInt): Boolean;
procedure FixupAPICallSites(IAT: NativeUInt);
function DetermineIATAddress(OEP: NativeUInt; Dumper: TDumper): NativeUInt;
procedure TraceImports(IAT: NativeUInt);
function TraceIsAtAPI(Tracer: TTracer; var C: TContext): Boolean;
procedure FinishUnpacking(OEP: NativeUInt);
procedure SetBreakpoint(Address: NativeUInt; BType: THWBPType = hwExecute);
function DisableBreakpoint(Address: Pointer): Boolean;
procedure EnableBreakpoints;
function IsHWBreakpoint(Address: Pointer): Boolean;
procedure ResetBreakpoint(Address: Pointer);
procedure UpdateDR(hThread: THandle);
procedure SoftBPClear;
protected
procedure Execute; override;
public
constructor Create(const AExecutable, AParameters: string; ACreateData: Boolean);
destructor Destroy; override;
end;
implementation
uses BeaEngineDelphi32, ShellAPI, AntiDumpFix, Math;
{ TDebugger }
constructor TDebugger.Create(const AExecutable, AParameters: string; ACreateData: Boolean);
begin
FExecutable := AExecutable;
FParameters := AParameters;
FCreateDataSections := ACreateData;
FThreads := TDictionary<Cardinal, THandle>.Create(32);
FSoftBPs := TDictionary<Pointer, Byte>.Create;
FGuardAddrs := TList<NativeUInt>.Create;
inherited Create(False);
end;
destructor TDebugger.Destroy;
begin
FThreads.Free;
FSoftBPs.Free;
FGuardAddrs.Free;
inherited;
end;
procedure TDebugger.Execute;
var
Ev: TDebugEvent;
Status: Cardinal;
begin
if not PEExecute then
begin
try
RaiseLastOSError;
except
Log(ltFatal, 'Creating the process failed: ' + ExceptObject.ToString);
end;
Exit;
end;
//KM.SetPID(FProcess.dwProcessId);
try
Status := DBG_CONTINUE;
while True do
begin
if not WaitForDebugEvent(Ev, INFINITE) then
begin
try
RaiseLastOSError;
except
Log(ltFatal, 'OS Error: ' + ExceptObject.ToString);
end;
Exit;
end;
//Writeln(Ev.dwDebugEventCode);
FCurrentThreadID := Ev.dwThreadId;
case Ev.dwDebugEventCode of
EXCEPTION_DEBUG_EVENT:
begin
Status := DBG_EXCEPTION_NOT_HANDLED;
case Ev.Exception.ExceptionRecord.ExceptionCode of
EXCEPTION_ACCESS_VIOLATION:
if IsGuardedAddress(Ev.Exception.ExceptionRecord.ExceptionInformation[1]) then
Status := ProcessGuardedAccess(FThreads[Ev.dwThreadId], Ev.Exception.ExceptionRecord)
else
Log(ltInfo, Format('Access violation at 0x%p [0x%X]', [Ev.Exception.ExceptionRecord.ExceptionAddress, Ev.Exception.ExceptionRecord.ExceptionInformation[1]]));
EXCEPTION_BREAKPOINT: // First chance: Display the current instruction and register values.
begin
if FSoftBPs.ContainsKey(Ev.Exception.ExceptionRecord.ExceptionAddress) then
begin
Status := OnSoftwareBreakpoint(Ev);
end
else
Log(ltInfo, 'Random int3');
end;
EXCEPTION_DATATYPE_MISALIGNMENT: ;
// First chance: Pass this on to the system.
// Last chance: Display an appropriate error.
EXCEPTION_SINGLE_STEP:
Status := OnHardwareBreakpoint(Ev);
DBG_CONTROL_C: ;
// First chance: Pass this on to the system.
// Last chance: Display an appropriate error.
else // Handle other exceptions.
begin
if Ev.Exception.dwFirstChance = 0 then
begin
Log(ltFatal, 'dwFirstChance = 0');
Exit;
end;
Log(ltInfo, Format('Code 0x%.8X at 0x%p', [Ev.Exception.ExceptionRecord.ExceptionCode, Ev.Exception.ExceptionRecord.ExceptionAddress]));
Status := DBG_EXCEPTION_NOT_HANDLED;
end;
end;
end;
CREATE_THREAD_DEBUG_EVENT:
// As needed, examine or change the thread's registers
// with the GetThreadContext and SetThreadContext functions;
// and suspend and resume thread execution with the
// SuspendThread and ResumeThread functions.
Status := OnCreateThreadDebugEvent(Ev);
CREATE_PROCESS_DEBUG_EVENT:
// As needed, examine or change the registers of the
// process's initial thread with the GetThreadContext and
// SetThreadContext functions; read from and write to the
// process's virtual memory with the ReadProcessMemory and
// WriteProcessMemory functions; and suspend and resume
// thread execution with the SuspendThread and ResumeThread
// functions. Be sure to close the handle to the process image
// file with CloseHandle.
Status := OnCreateProcessDebugEvent(Ev);
EXIT_THREAD_DEBUG_EVENT:
// Display the thread's exit code.
Status := OnExitThreadDebugEvent(Ev);
EXIT_PROCESS_DEBUG_EVENT:
begin
Status := OnExitProcessDebugEvent(Ev);
ContinueDebugEvent(Ev.dwProcessId, Ev.dwThreadId, Status);
Break;
end;
LOAD_DLL_DEBUG_EVENT:
// Read the debugging information included in the newly
// loaded DLL. Be sure to close the handle to the loaded DLL
// with CloseHandle.
Status := OnLoadDllDebugEvent(Ev);
UNLOAD_DLL_DEBUG_EVENT:
// Display a message that the DLL has been unloaded.
Status := OnUnloadDllDebugEvent(Ev);
OUTPUT_DEBUG_STRING_EVENT:
// Display the output debugging string.
Status := OnOutputDebugStringEvent(Ev);
RIP_EVENT:
Status := OnRipEvent(Ev);
end;
// Resume executing the thread that reported the debugging event.
ContinueDebugEvent(Ev.dwProcessId, Ev.dwThreadId, Status);
end;
except
Log(ltFatal, ExceptObject.ToString);
end;
end;
function TDebugger.OnCreateThreadDebugEvent(var DebugEv: TDebugEvent): DWORD;
begin
Log(ltInfo, Format('[%.4d] Thread started (%p).', [DebugEv.dwThreadId, DebugEv.CreateThread.lpStartAddress]));
FThreads.Add(DebugEv.dwThreadId, DebugEv.CreateThread.hThread);
UpdateDR(DebugEv.CreateThread.hThread);
Result := DBG_CONTINUE;
end;
function TDebugger.OnCreateProcessDebugEvent(var DebugEv: TDebugEvent): DWORD;
var
pbi: TProcessBasicInformation;
Buf: Cardinal;
x: NativeUInt;
begin
Log(ltInfo, Format('CreateProcess (%.4d, %.4d)', [DebugEv.dwProcessId, DebugEv.dwThreadId]));
NtQueryInformationProcess(FProcess.hProcess, 0, @pbi, SizeOf(pbi), nil);
Log(ltInfo, Format('PEB: %.8X', [Cardinal(pbi.PebBaseAddress)]));
Buf := 0;
if ReadProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + 2, @Buf, 1, x) then
begin
if Buf = 1 then
begin
Log(ltGood, 'Patching PEB.BeingDebugged');
Buf := 0;
WriteProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + 2, @Buf, 1, x);
if ReadProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + $68, @Buf, 4, x) then
begin
Log(ltInfo, 'NtGlobalFlags: ' + IntToStr(Buf));
Buf := 0;
WriteProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + $68, @Buf, 4, x);
end;
end;
end
else
Log(ltFatal, 'Reading PEB failed');
if ReadProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + 8, @FImageBase, 4, x) then
begin
Log(ltInfo, 'Process Image Base: ' + IntToHex(FImageBase, 8));
end;
if ReadProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + $1E8, @Buf, 4, x) and (Buf <> 0) then
begin
Buf := 0;
if WriteProcessMemory(FProcess.hProcess, PByte(pbi.PebBaseAddress) + $1E8, @Buf, 4, x) then
Log(ltInfo, 'Cleared PEB.pShimData to prevent apphelp hooks');
end;
FThreads.Add(DebugEv.dwThreadId, DebugEv.CreateProcessInfo.hThread);
CloseHandleAPI := GetProcAddress(GetModuleHandle(kernel32), 'CloseHandle');
FHW1.Address := Cardinal(CloseHandleAPI);
if FileExists('InjectorCLIx86.exe') then
begin
Log(ltGood, 'Applying ScyllaHide');
ShellExecute(0, 'open', 'InjectorCLIx86.exe', PChar(Format('pid:%d %s nowait', [FProcess.dwProcessId, ExtractFilePath(ParamStr(0)) + 'HookLibraryx86.dll'])), nil, SW_HIDE);
end
else
begin
NtSIT := GetProcAddress(GetModuleHandle('ntdll.dll'), 'ZwSetInformationThread');
FHW3.Address := Cardinal(NtSIT);
KiFastSystemCall := GetProcAddress(GetModuleHandle('ntdll.dll'), 'KiFastSystemCall');
if not (IsWow64Process(FProcess.hProcess, FWow64) and FWow64) then
begin
VirtualProtectEx(FProcess.hProcess, KiFastSystemCall, 1, PAGE_EXECUTE_READWRITE, @x);
Buf := $CC;
WriteProcessMemory(FProcess.hProcess, KiFastSystemCall, @Buf, 1, x);
FSoftBPs.Add(KiFastSystemCall, $8B);
NtQIP := PCardinal(Cardinal(GetProcAddress(GetModuleHandle('ntdll.dll'), 'ZwQueryInformationProcess')) + 1)^;
end
else
begin
NtQIP64 := GetProcAddress(GetModuleHandle('ntdll.dll'), 'ZwQueryInformationProcess');
FHW4.Address := Cardinal(NtQIP64);
end;
end;
VirtualProtectAPI := GetProcAddress(GetModuleHandle(kernel32), 'VirtualProtect');
FSleepAPI := NativeUInt(GetProcAddress(GetModuleHandle(kernel32), 'Sleep'));
FlstrlenAPI := NativeUInt(GetProcAddress(GetModuleHandle(kernel32), 'lstrlen'));
UpdateDR(DebugEv.CreateProcessInfo.hThread);
//FetchMemoryRegions;
TMInit(DebugEv.CreateProcessInfo.hFile);
Result := DBG_CONTINUE;
CloseHandle(DebugEv.CreateProcessInfo.hFile);
//CloseHandle(DebugEv.CreateProcessInfo.hProcess);
//CloseHandle(DebugEv.CreateProcessInfo.hThread);
end;
function TDebugger.OnExitThreadDebugEvent(var DebugEv: TDebugEvent): DWORD;
begin
if not FHideThreadEnd then
Log(ltInfo, Format('[%.4d] Thread ended (code %d).', [DebugEv.dwThreadId, DebugEv.ExitThread.dwExitCode]));
FThreads.Remove(DebugEv.dwThreadId);
Result := DBG_CONTINUE;
end;
const
STATUS_PORT_NOT_SET = $C0000353;
function TDebugger.OnHardwareBreakpoint(var DebugEv: TDebugEvent): DWORD;
var
EIP: Pointer;
hThread: THandle;
C: TContext;
Buf, Buf2, BPA, OldProt, WriteBuf, InfoClass: Cardinal;
Resume: Boolean;
x: NativeUInt;
CC: Byte;
begin
Resume := False;
Result := DBG_EXCEPTION_NOT_HANDLED;
EIP := DebugEv.Exception.ExceptionRecord.ExceptionAddress;
hThread := FThreads[DebugEv.dwThreadId];
C.ContextFlags := CONTEXT_FULL or CONTEXT_DEBUG_REGISTERS;
GetThreadContext(hThread, C);
if EIP = CloseHandleAPI then
begin
RPM(C.Esp, @Buf, 4);
if Buf < FImageBoundary then
begin
ResetBreakpoint(EIP);
if FCompressed then
SetBreakpoint(FImageBase + $1000, hwAccess)
else
SetBreakpoint(Cardinal(AllocMemAPI));
end;
Resume := True;
end
else if EIP = AllocMemAPI then
begin
// NT-Layer ZwAllocateVirtualMemory <- kernelbase.VirtualAllocEx <- kernelbase.VirtualAlloc
// ^^^ not for NT 6.3
RPM(C.Ebp, @Buf, 4);
if Abs(Buf - C.Ebp) < $40 then
RPM(Buf + 4, @Buf, 4)
else
RPM(C.Ebp + 4, @Buf, 4);
Log(ltInfo, Format('AllocMem called from %.8X', [Buf]));
if Buf shr 31 <> 0 then // Kernel address, can't be right
WaitForSingleObject(Self.Handle, INFINITE);
if Buf < FImageBoundary then
begin
Inc(AllocMemCounter);
if AllocMemCounter = IfThen(FCompressed, 4, 5) then
begin
ResetBreakpoint(AllocMemAPI);
if not FThemidaV3 then
begin
Log(ltGood, 'IAT fixing started.');
TMIATFix(Buf);
end
else
InstallCodeSectionGuard(PAGE_NOACCESS);
end;
end;
Resume := True;
end
else if EIP = CmpImgBase then
begin
ResetBreakpoint(CmpImgBase);
TMIATFix3(NativeUInt(EIP));
Resume := True;
end
else if EIP = MagicJump then
begin
ResetBreakpoint(MagicJump);
TMIATFix4;
Resume := True;
end
else if EIP = Pointer(MJ_1) then
begin
ResetBreakpoint(Pointer(MJ_1));
TMIATFix5(C.Eax);
Resume := True;
end
else if EIP = MagicJumpV1 then
begin
ResetBreakpoint(MagicJumpV1);
TMIATFixThemidaV1(UIntPtr(MagicJumpV1));
Resume := True;
end
else if EIP = AllocHeapAPI then
begin
Log(ltFatal, 'Special IAT fix failed, perhaps not needed for this binary');
ResetBreakpoint(AllocHeapAPI);
SoftBPClear;
InstallCodeSectionGuard(PAGE_NOACCESS);
Resume := True;
end
else if EIP = VirtualProtectAPI then
begin
{RPM(C.Esp + 4, @Buf, 4);
RPM(C.Esp + 8, @Buf2, 4);
Log(ltInfo, Format('[%d] Protect: %X %X', [FCurrentThreadId, Buf, Buf2]));}
// Ensure we break on execution in case it's still on PAGE_READONLY.
InstallCodeSectionGuard(PAGE_NOACCESS);
Resume := True;
end
else if EIP = NtSIT then
begin
Resume := True;
if RPM(C.Esp, @Buf, 4) and (Buf < FImageBoundary) and RPM(C.Esp + 8, @InfoClass, 4) and (InfoClass = 17) then
begin
Log(ltGood, 'Ignoring NtSetInformationThread(ThreadHideFromDebugger)');
Inc(C.Esp, 5 * 4); // 4 paramaters + ret
C.Eip := Buf;
C.Eax := STATUS_SUCCESS;
C.ContextFlags := CONTEXT_FULL;
if not SetThreadContext(hThread, C) then
Log(ltFatal, '[NtSetInformationThread] SetContextThread');
end;
end
else if FWow64 and (EIP = NtQIP64) then
begin
Resume := True;
if RPM(C.Esp, @Buf, 4) and RPM(C.Esp + 8, @InfoClass, 4) and ((InfoClass = 7) or (InfoClass = 30)) then
begin
if InfoClass = 7 then
Log(ltGood, 'Faking ProcessDebugPort')
else
Log(ltGood, 'Faking ProcessDebugObjectHandle');
RPM(C.Esp + 12, @Buf2, 4);
WriteBuf := 0; // Debug Port/Debug Object Handle
WriteProcessMemory(FProcess.hProcess, Pointer(Buf2), @WriteBuf, 4, x);
Inc(C.Esp, 6 * 4); // 5 parameters + ret
C.Eip := Buf;
if InfoClass = 7 then
C.Eax := STATUS_SUCCESS
else
C.Eax := STATUS_PORT_NOT_SET;
C.ContextFlags := CONTEXT_FULL;
if not SetThreadContext(hThread, C) then
Log(ltFatal, '[KiFastSystemCall] SetContextThread');
end;
end
else
begin
// Check if Single-step execution mode (bit 14)
if (((C.Dr6 shr 14) and 1) = 0) and (FHW1.IsSet or FHW2.IsSet or FHW3.IsSet or FHW4.IsSet) then
begin
BPA := 0;
case C.Dr6 and $F of
1: BPA := FHW1.Address;
2: BPA := FHW2.Address;
4: BPA := FHW3.Address;
8: BPA := FHW4.Address;
else Log(ltFatal, 'Multisignal : ' + IntToStr(C.Dr6 and $F));
end;
if BPA = FImageBase + $1000 then
begin
Inc(FBaseAccessCount);
Log(ltGood, Format('Accessed text base from %p', [EIP]));
if not BaseAccessed then
begin
ResetBreakpoint(Pointer(FImageBase + $1000));
SetBreakpoint(FImageBase + $1000, hwWrite);
BaseAccessed := True;
end
else
begin
if TMFinderCheck(@C) then
begin
ResetBreakpoint(Pointer(FImageBase + $1000));
SetBreakpoint(Cardinal(AllocMemAPI), hwExecute);
RepEIP := C.Eip;
end
else if (FBaseAccessCount = 3) and not FThemidaV2BySections then // hackish, but seems ok so far
begin
FThemidaV3 := True;
Log(ltInfo, 'Assuming Themida v3');
SelectThemidaSection(C.Eip);
ResetBreakpoint(Pointer(FImageBase + $1000));
SetBreakpoint(Cardinal(AllocMemAPI), hwExecute);
end;
end;
end
else
begin
Log(ltInfo, Format('Accessed %x from %p', [BPA, EIP]));
end;
Exit(DBG_CONTINUE);
end
else if FSoftBPReenable <> 0 then
begin
CC := $CC;
WriteProcessMemory(FProcess.hProcess, PByte(FSoftBPReenable), @CC, 1, x);
FSoftBPReenable := 0;
Exit(DBG_CONTINUE);
end
else if FGuardStepping then
begin
VirtualProtectEx(FProcess.hProcess, Pointer(FGuardStart), FGuardEnd - FGuardStart, FGuardProtection, OldProt);
FGuardStepping := False;
Exit(DBG_CONTINUE);
end
else
begin
EnableBreakpoints;
Result := DBG_CONTINUE;
end;
end;
if Resume then
begin
if DisableBreakpoint(EIP) then
begin
UpdateDR(hThread);
C.ContextFlags := CONTEXT_CONTROL;
C.EFlags := C.EFlags or $100;
SetThreadContext(hThread, C);
end;
Result := DBG_CONTINUE;
end;
end;
function TDebugger.OnSoftwareBreakpoint(var DebugEv: TDebugEvent): DWORD;
var
B: Byte;
x, Jumper, Res: NativeUInt;
hThread: THandle;
C: TContext;
EIP: Pointer;
mK32, mU32, mA32: HMODULE;
bs: array[0..40] of Byte;
Buf: PByte;
i: Integer;
WriteBuf, InfoClass: Cardinal;
begin
Result := DBG_CONTINUE;
EIP := DebugEv.Exception.ExceptionRecord.ExceptionAddress;
if not FWow64 and (EIP = KiFastSystemCall) then
begin
hThread := FThreads[DebugEv.dwThreadId];
C.ContextFlags := CONTEXT_FULL;
GetThreadContext(hThread, C);
if (C.Eax = NtQIP) and RPM(C.Esp, @Res, 4) and RPM(C.Esp + 12, @InfoClass, 4) and ((InfoClass = 7) or (InfoClass = 30)) then
begin
if InfoClass = 7 then
Log(ltGood, 'Faking ProcessDebugPort')
else
Log(ltGood, 'Faking ProcessDebugObjectHandle');
RPM(C.Esp + 16, @x, 4);
WriteBuf := 0; // Debug Port
WriteProcessMemory(FProcess.hProcess, Pointer(x), @WriteBuf, 4, x);
Inc(C.Esp, 4); // 5 paramaters + ret
C.Eip := Res;
if InfoClass = 7 then
C.Eax := STATUS_SUCCESS
else
C.Eax := STATUS_PORT_NOT_SET;
end
else
begin
C.Edx := C.Esp;
C.Eip := NativeUInt(KiFastSystemCall) + 2;
end;
if not SetThreadContext(hThread, C) then
Log(ltFatal, '[KiFastSystemCall] SetContextThread');
Exit;
end;
Log(ltInfo, Format('Software breakpoint at %p', [EIP]));
// Should only be called during IAT patching
// eax should hold a module base now
hThread := FThreads[DebugEv.dwThreadId];
C.ContextFlags := CONTEXT_FULL;
GetThreadContext(hThread, C);
Dec(C.Eip);
C.ContextFlags := CONTEXT_CONTROL;
SetThreadContext(hThread, C);
mK32 := GetModuleHandle(kernel32);
if not NewVer then
begin
mU32 := GetModuleHandle(user32);
mA32 := GetModuleHandle(advapi32);
if (C.Eax <> mK32) and (C.Eax <> mU32) and (C.Eax <> mA32) then
begin
// Rare path in certain weird binaries.
Log(ltInfo, Format('eax: %.8X', [C.Eax]));
if not IsHWBreakpoint(AllocHeapAPI) then
SetBreakpoint(Cardinal(AllocHeapAPI), hwExecute);
// Restore original byte and single step.
FSoftBPReenable := C.Eip;
B := FSoftBPs[EIP];
WriteProcessMemory(FProcess.hProcess, EIP, @B, 1, x);
FlushInstructionCache(FProcess.hProcess, EIP, 1);
C.EFlags := C.EFlags or $100;
SetThreadContext(hThread, C);
Exit; // DBG_CONTINUE
end;
SoftBPClear;
Jumper := 5 + C.Eip + PCardinal(TMSect + C.Eip + 1 - TMSectR.Address)^;
Res := Cardinal(VirtualAllocEx(FProcess.hProcess, nil, 128, MEM_COMMIT, PAGE_EXECUTE_READWRITE));
Log(ltInfo, 'IAT patch location: ' + IntTOHex(Res, 8));
Buf := @bs;
PWord(Buf)^ := $F881; // cmp eax
PCardinal(Buf + 2)^ := mK32;
PCardinal(Buf + 6)^ := $F8811574;
PCardinal(Buf + 10)^ := mA32;
PCardinal(Buf + 14)^ := $F8810D74;
PCardinal(Buf + 18)^ := mU32;
PWord(Buf + 22)^ := $0574;
PByte(Buf + 24)^ := $E9;
PCardinal(Buf + 25)^ := Jumper - (Res + 24) - 5;
PUInt64(Buf + 29)^ := $E9000002872404C7;
PCardinal(Buf + 37)^ := Jumper - (Res + 36) - 5;
WriteProcessMemory(FProcess.hProcess, Pointer(Res), Buf, 41, x);
FlushInstructionCache(FProcess.hProcess, Pointer(Res), 41);
Buf^ := $E9;
PCardinal(Buf + 1)^ := Res - C.Eip - 5;
WriteProcessMemory(FProcess.hProcess, Pointer(C.Eip), Buf, 5, x);
FlushInstructionCache(FProcess.hProcess, Pointer(C.Eip), 5);
Log(ltGood, 'Special IAT patch was successfully written!');
end
else // Teflon time!
begin
B := FSoftBPs[EIP];
WriteProcessMemory(FProcess.hProcess, EIP, @B, 1, x);
FlushInstructionCache(FProcess.hProcess, EIP, 1);
FSoftBPs.Remove(EIP);
for i := 0 to High(EFLs) do
begin
if EFLs[i].Address = 0 then
begin
EFLs[i].Address := Cardinal(EIP);
if InstallEFLPatch(EIP, C, EFLs[i]) then
Exit
else
Break;
end;
end;
SoftBPClear;
Log(ltInfo, 'Found no base in registers!');
Log(ltGood, 'Special >> NEW << IAT Patch was written!');
end;
InstallCodeSectionGuard(PAGE_READONLY); // Not using PAGE_NOACCESS here is a performance optimization for some targets (esp. MC1.14).
Log(ltInfo, 'Please wait, call site tracing might take a while...');
end;
function DisasmCheck(var Dis: _Disasm): Integer;
begin
Result := Disasm(Dis);
if (Result = BeaEngineDelphi32.UNKNOWN_OPCODE) or (Result = BeaEngineDelphi32.OUT_OF_BLOCK) then
raise Exception.CreateFmt('Disasm result: %d (EIP = %X)', [Result, Dis.EIP]);
end;
function TDebugger.InstallEFLPatch(EIP: Pointer; var C: TContext; var Rec: TEFLRecord): Boolean;
var
Bases: array[0..2] of HMODULE;
HookDest: Pointer;
bs: array[0..127] of Byte;
Buf, OrigOps: PByte;
Dis: _Disasm;
M, FoundBase: HMODULE;
RegComp: Word;
TotalSize, x: NativeUInt;
begin
Bases[0] := GetModuleHandle(kernel32);
Bases[1] := GetModuleHandle(user32);
Bases[2] := GetModuleHandle(advapi32);
FillChar(Dis, SizeOf(Dis), 0);
Dis.EIP := Cardinal(TMSect) + Cardinal(EIP) - TMSectR.Address;
if DisasmCheck(Dis) = 5 then
if (TMSect + (Cardinal(EIP) - TMSectR.Address))^ = $E9 then
raise Exception.Create('efl oldstyle');
FoundBase := 0;
RegComp := 0;
for M in Bases do
begin
if C.Eax = M then
RegComp := $F881
else if C.Ecx = M then
RegComp := $F981
else if C.Edx = M then
RegComp := $FA81
else if C.Ebx = M then
RegComp := $FB81
else if C.Ebp = M then
RegComp := $FD81
else if C.Esi = M then
RegComp := $FE81
else if C.Edi = M then
RegComp := $FF81
else
Continue;
FoundBase := M;
Break;
end;
if FoundBase = 0 then
Exit(False);
HookDest := VirtualAllocEx(FProcess.hProcess, nil, 128, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Buf := @bs;
PWord(Buf)^ := RegComp;
PCardinal(Buf + 2)^ := Bases[0];
PWord(Buf + 6)^ := $2874;
PWord(Buf + 8)^ := RegComp;
PCardinal(Buf + 10)^ := Bases[1];
PWord(Buf + 14)^ := $2074;
PWord(Buf + 16)^ := RegComp;
PCardinal(Buf + 18)^ := Bases[2];
PWord(Buf + 22)^ := $1874;
PWord(Buf + 24)^ := $1DEB; // jmp to OrigOps
PUInt64(Buf + $30)^ := $90000002462404C7; // mov [esp], 0x246 (EFL Patch)
OrigOps := Buf + $37;
TotalSize := 0;
Dis.EIP := Cardinal(TMSect) + Cardinal(EIP) - TMSectR.Address;
while TotalSize < 5 do
begin
x := DisasmCheck(Dis);
Inc(TotalSize, x);
Inc(Dis.EIP, x);
end;
// Copy original opcodes
Move((TMSect + (Cardinal(EIP) - TMSectR.Address))^, OrigOps^, TotalSize);
SetLength(Rec.Original, TotalSize);
Move(OrigOps^, Rec.Original[0], TotalSize);
// Calculate jump back
Inc(OrigOps, TotalSize);
OrigOps^ := $E9;
PCardinal(OrigOps+1)^ := (Cardinal(EIP) + TotalSize) - (Cardinal(OrigOps) - Cardinal(Buf) + Cardinal(HookDest)) - 5;
//Log(ltInfo, 'OrigOps size: ' + IntToStr(TotalSize));
// Copy to target
WriteProcessMemory(FProcess.hProcess, HookDest, Buf, 128, x);
FlushInstructionCache(FProcess.hProcess, HookDest, 128);
// Install hook
Buf^ := $E9;
PCardinal(Buf+1)^ := Cardinal(HookDest) - Cardinal(EIP) - 5;
WriteProcessMemory(FProcess.hProcess, EIP, Buf, 5, x);
FlushInstructionCache(FProcess.hProcess, EIP, 5);
// Check if there's a jz/jnz that became invalid due to the hook and fix it
RPM(Cardinal(EIP) - 3 - 6, @bs[0], 6);
if (bs[0] = $0F) and ((bs[1] = $84) or (bs[1] = $85)) and (PCardinal(@bs[2])^ in [4..7]) then
begin
PCardinal(@bs[2])^ := (Cardinal(HookDest) + $37 + (PCardinal(@bs[2])^ - 3)) - (Cardinal(EIP) - 3 - 6) - 6;
WriteProcessMemory(FProcess.hProcess, Pointer(Cardinal(EIP) - 3 - 4), @bs[2], 4, x);
end;
// SPECIAL_IAT_PATCH_OK = 1
Log(ltGood, 'EFL Patch at ' + IntToHex(Cardinal(EIP), 8));
Result := True;
end;
function TDebugger.OnLoadDllDebugEvent(var DebugEv: TDebugEvent): DWORD;
var
lpImageName: Pointer;
szBuffer: array[0..MAX_PATH] of Char;
x: NativeUInt;
DLL: string;
begin
if (not ReadProcessMemory(FProcess.hProcess, DebugEv.LoadDll.lpImageName, @lpImageName, Sizeof(Pointer), x) or
not ReadProcessMemory(FProcess.hProcess, lpImageName, @szBuffer, sizeof(szBuffer), x)) then
szBuffer := '?';
DLL := string(szBuffer);
Log(ltInfo, Format('[%.8X] Loaded %s', [Cardinal(DebugEv.LoadDll.lpBaseOfDll), DLL]));
if Pos('aclayers.dll', LowerCase(DLL)) > 0 then
raise Exception.Create('[FATAL] Compatibility mode screws up the unpacking process.');
Result := DBG_CONTINUE;
CloseHandle(DebugEv.LoadDll.hFile);
end;
function TDebugger.OnExitProcessDebugEvent(var DebugEv: TDebugEvent): DWORD;
begin
Log(ltInfo, Format('Process ended (code %d).', [DebugEv.ExitProcess.dwExitCode]));
Result := DBG_CONTINUE;
end;
function TDebugger.OnUnloadDllDebugEvent(var DebugEv: TDebugEvent): DWORD;
begin
Result := DBG_CONTINUE;
end;
function TDebugger.OnOutputDebugStringEvent(var DebugEv: TDebugEvent): DWORD;
begin
Result := DBG_CONTINUE;
end;
function TDebugger.OnRipEvent(var DebugEv: TDebugEvent): DWORD;
begin
Log(ltFatal, 'SYSTEM ERROR');
Result := DBG_CONTINUE;
end;
function TDebugger.PEExecute: Boolean;
var
SI: TStartupInfo;
PI: TProcessInformation;
Flags: DWORD;
CmdLine, CurrentDir: string;
begin
CurrentDir := ExtractFilePath(FExecutable);
if AnsiLastChar(CurrentDir) = '\' then
Delete(CurrentDir, Length(CurrentDir), 1);
FillChar(SI, SizeOf(SI), 0);
with SI do
begin
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := SW_SHOW;
end;
FillChar(PI, SizeOf(PI), 0);
CmdLine := Format('"%s" %s', [FExecutable, TrimRight(FParameters)]);
Flags := CREATE_DEFAULT_ERROR_MODE or CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS or DEBUG_PROCESS or DEBUG_ONLY_THIS_PROCESS;
Result := CreateProcess(nil, PChar(CmdLine), nil, nil, False, Flags, nil, PChar(CurrentDir), SI, PI);
FProcess := PI;
end;
procedure TDebugger.SetBreakpoint(Address: NativeUInt; BType: THWBPType);
var
T: THandle;
begin
if FHW1.Address = 0 then
FHW1.Change(Address, BType)
else if FHW2.Address = 0 then
FHW2.Change(Address, BType)
else if FHW3.Address = 0 then
FHW3.Change(Address, BType)
else if FHW4.Address = 0 then
FHW4.Change(Address, BType)
else
raise Exception.Create('All breakpoints in use');
for T in FThreads.Values do
UpdateDR(T);
end;
function TDebugger.DisableBreakpoint(Address: Pointer): Boolean;
begin
Result := True;
if Pointer(FHW1.Address) = Address then
FHW1.Disabled := True
else if Pointer(FHW2.Address) = Address then
FHW2.Disabled := True
else if Pointer(FHW3.Address) = Address then
FHW3.Disabled := True
else if Pointer(FHW4.Address) = Address then
FHW4.Disabled := True
else
Result := False;
end;
procedure TDebugger.EnableBreakpoints;
var
T: THandle;
begin
if FHW1.Disabled or FHW2.Disabled or FHW3.Disabled or FHW4.Disabled then
begin
FHW1.Disabled := False;
FHW2.Disabled := False;
FHW3.Disabled := False;
FHW4.Disabled := False;
for T in FThreads.Values do
UpdateDR(T);