forked from x64dbg/ScyllaHide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHookedFunctions.cpp
1145 lines (981 loc) · 39.6 KB
/
HookedFunctions.cpp
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 "HookMain.h"
#pragma intrinsic(_ReturnAddress)
HOOK_DLL_DATA HookDllData = { 0 };
#include "HookedFunctions.h"
#include "HookHelper.h"
#include "Tls.h"
void FakeCurrentParentProcessId(PSYSTEM_PROCESS_INFORMATION pInfo);
void FakeCurrentOtherOperationCount(PSYSTEM_PROCESS_INFORMATION pInfo);
void FilterHandleInfo(PSYSTEM_HANDLE_INFORMATION pHandleInfo, PULONG pReturnLengthAdjust);
void FilterHandleInfoEx(PSYSTEM_HANDLE_INFORMATION_EX pHandleInfoEx, PULONG pReturnLengthAdjust);
void FilterProcess(PSYSTEM_PROCESS_INFORMATION pInfo);
void FilterObjects(POBJECT_TYPES_INFORMATION pObjectTypes);
void FilterObject(POBJECT_TYPE_INFORMATION pObject, bool zeroTotal);
void FilterHwndList(HWND * phwndFirst, PUINT pcHwndNeeded);
SAVE_DEBUG_REGISTERS ArrayDebugRegister[100] = { 0 }; //Max 100 threads
// https://forum.tuts4you.com/topic/40011-debugme-vmprotect-312-build-886-anti-debug-method-improved/#comment-192824
// https://github.com/x64dbg/ScyllaHide/issues/47
// https://github.com/mrexodia/TitanHide/issues/27
#define BACKUP_RETURNLENGTH() \
ULONG TempReturnLength = 0; \
if(ReturnLength != nullptr) \
TempReturnLength = *ReturnLength
#define RESTORE_RETURNLENGTH() \
if(ReturnLength != nullptr) \
(*ReturnLength) = TempReturnLength
NTSTATUS NTAPI HookedNtSetInformationThread(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength)
{
if (ThreadInformationClass == ThreadHideFromDebugger && ThreadInformationLength == 0) // NB: ThreadInformation is not checked, this is deliberate
{
if (ThreadHandle == NtCurrentThread ||
HandleToULong(NtCurrentTeb()->ClientId.UniqueProcess) == GetProcessIdByThreadHandle(ThreadHandle)) //thread inside this process?
{
return STATUS_SUCCESS;
}
}
return HookDllData.dNtSetInformationThread(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength);
}
NTSTATUS NTAPI HookedNtQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength)
{
if (SystemInformationClass == SystemKernelDebuggerInformation ||
SystemInformationClass == SystemProcessInformation ||
SystemInformationClass == SystemSessionProcessInformation ||
SystemInformationClass == SystemHandleInformation ||
SystemInformationClass == SystemExtendedHandleInformation ||
SystemInformationClass == SystemExtendedProcessInformation || // Vista+
SystemInformationClass == SystemCodeIntegrityInformation || // Vista+
SystemInformationClass == SystemKernelDebuggerInformationEx || // 8.1+
SystemInformationClass == SystemKernelDebuggerFlags || // 10+
SystemInformationClass == SystemCodeIntegrityUnlockInformation) // 10+
{
NTSTATUS ntStat = HookDllData.dNtQuerySystemInformation(SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength);
if (NT_SUCCESS(ntStat) && SystemInformation != nullptr && SystemInformationLength != 0)
{
if (SystemInformationClass == SystemKernelDebuggerInformation)
{
BACKUP_RETURNLENGTH();
((PSYSTEM_KERNEL_DEBUGGER_INFORMATION)SystemInformation)->KernelDebuggerEnabled = FALSE;
((PSYSTEM_KERNEL_DEBUGGER_INFORMATION)SystemInformation)->KernelDebuggerNotPresent = TRUE;
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemHandleInformation)
{
BACKUP_RETURNLENGTH();
ULONG ReturnLengthAdjust = 0;
FilterHandleInfo((PSYSTEM_HANDLE_INFORMATION)SystemInformation, &ReturnLengthAdjust);
if (ReturnLengthAdjust <= TempReturnLength)
TempReturnLength -= ReturnLengthAdjust;
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemExtendedHandleInformation)
{
BACKUP_RETURNLENGTH();
ULONG ReturnLengthAdjust = 0;
FilterHandleInfoEx((PSYSTEM_HANDLE_INFORMATION_EX)SystemInformation, &ReturnLengthAdjust);
if (ReturnLengthAdjust <= TempReturnLength)
TempReturnLength -= ReturnLengthAdjust;
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemProcessInformation ||
SystemInformationClass == SystemSessionProcessInformation ||
SystemInformationClass == SystemExtendedProcessInformation)
{
BACKUP_RETURNLENGTH();
PSYSTEM_PROCESS_INFORMATION ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)SystemInformation;
if (SystemInformationClass == SystemSessionProcessInformation)
ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((PSYSTEM_SESSION_PROCESS_INFORMATION)SystemInformation)->Buffer;
FilterProcess(ProcessInfo);
FakeCurrentParentProcessId(ProcessInfo);
FakeCurrentOtherOperationCount(ProcessInfo);
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemCodeIntegrityInformation)
{
BACKUP_RETURNLENGTH();
((PSYSTEM_CODEINTEGRITY_INFORMATION)SystemInformation)->CodeIntegrityOptions = CODEINTEGRITY_OPTION_ENABLED;
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemKernelDebuggerInformationEx)
{
BACKUP_RETURNLENGTH();
((PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX)SystemInformation)->DebuggerAllowed = FALSE;
((PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX)SystemInformation)->DebuggerEnabled = FALSE;
((PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX)SystemInformation)->DebuggerPresent = FALSE;
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemKernelDebuggerFlags)
{
BACKUP_RETURNLENGTH();
*(PUCHAR)SystemInformation = 0;
RESTORE_RETURNLENGTH();
}
else if (SystemInformationClass == SystemCodeIntegrityUnlockInformation)
{
BACKUP_RETURNLENGTH();
// The size of the buffer for this class changed from 4 to 36, but the output should still be all zeroes
RtlZeroMemory(SystemInformation, SystemInformationLength);
RESTORE_RETURNLENGTH();
}
}
return ntStat;
}
return HookDllData.dNtQuerySystemInformation(SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength);
}
static ULONG ValueProcessBreakOnTermination = FALSE;
static ULONG ValueProcessDebugFlags = PROCESS_DEBUG_INHERIT; // actual value is no inherit
static bool IsProcessHandleTracingEnabled = false;
#ifndef STATUS_INVALID_PARAMETER
#define STATUS_INVALID_PARAMETER ((DWORD )0xC000000DL)
#endif
// Instrumentation callback
static LONG volatile InstrumentationCallbackHookInstalled = 0;
static ULONG NumManualSyscalls = 0;
extern "C"
ULONG_PTR
NTAPI
InstrumentationCallback(
_In_ ULONG_PTR ReturnAddress, // ECX/R10
_Inout_ ULONG_PTR ReturnVal // EAX/RAX
)
{
if (InterlockedOr(TlsGetInstrumentationCallbackDisabled(), 0x1) == 0x1)
return ReturnVal; // Do not recurse
const PVOID ImageBase = NtCurrentPeb()->ImageBaseAddress;
const PIMAGE_NT_HEADERS NtHeaders = RtlImageNtHeader(ImageBase);
if (NtHeaders != nullptr && ReturnAddress >= (ULONG_PTR)ImageBase &&
ReturnAddress < (ULONG_PTR)ImageBase + NtHeaders->OptionalHeader.SizeOfImage)
{
// Syscall return address within the exe file
ReturnVal = (ULONG_PTR)(ULONG)STATUS_PORT_NOT_SET;
// Uninstall ourselves after we have completed the sequence { NtQIP, NtQIP }. More NtSITs will follow but we can't do anything about them
NumManualSyscalls++;
if (NumManualSyscalls >= 2)
{
InstallInstrumentationCallbackHook(NtCurrentProcess, TRUE);
}
}
InterlockedAnd(TlsGetInstrumentationCallbackDisabled(), 0);
return ReturnVal;
}
NTSTATUS NTAPI HookedNtQueryInformationProcess(HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength)
{
if (NumManualSyscalls == 0 &&
InterlockedOr(&InstrumentationCallbackHookInstalled, 0x1) == 0)
{
InstallInstrumentationCallbackHook(NtCurrentProcess, FALSE);
}
NTSTATUS Status;
if (ProcessInformationClass == ProcessDebugObjectHandle && // Handle ProcessDebugObjectHandle early
ProcessInformation != nullptr &&
ProcessInformationLength == sizeof(HANDLE) &&
(ProcessHandle == NtCurrentProcess || HandleToULong(NtCurrentTeb()->ClientId.UniqueProcess) == GetProcessIdByProcessHandle(ProcessHandle)))
{
// Verify (1) that the handle has PROCESS_QUERY_INFORMATION access, and (2) that writing
// to ProcessInformation and/or ReturnLength does not cause any access or alignment violations
Status = HookDllData.dNtQueryInformationProcess(ProcessHandle,
ProcessDebugPort, // Note: not ProcessDebugObjectHandle
ProcessInformation,
sizeof(HANDLE),
ReturnLength);
if (!NT_SUCCESS(Status))
return Status;
// The kernel calls DbgkOpenProcessDebugPort here
// This should be done in a try/except block, but since we are a mapped DLL we cannot use SEH.
// Rely on the fact that the NtQIP call we just did wrote to the same buffers successfully
*(PHANDLE)ProcessInformation = nullptr;
if (ReturnLength != nullptr)
*ReturnLength = sizeof(HANDLE);
return STATUS_PORT_NOT_SET;
}
if ((ProcessInformationClass == ProcessDebugFlags ||
ProcessInformationClass == ProcessDebugPort ||
ProcessInformationClass == ProcessBasicInformation ||
ProcessInformationClass == ProcessBreakOnTermination ||
ProcessInformationClass == ProcessHandleTracing ||
ProcessInformationClass == ProcessIoCounters) &&
(ProcessHandle == NtCurrentProcess || HandleToULong(NtCurrentTeb()->ClientId.UniqueProcess) == GetProcessIdByProcessHandle(ProcessHandle)))
{
Status = HookDllData.dNtQueryInformationProcess(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength);
if (NT_SUCCESS(Status) && ProcessInformation != nullptr && ProcessInformationLength != 0)
{
if (ProcessInformationClass == ProcessDebugFlags)
{
BACKUP_RETURNLENGTH();
*((ULONG *)ProcessInformation) = ((ValueProcessDebugFlags & PROCESS_NO_DEBUG_INHERIT) != 0) ? 0 : PROCESS_DEBUG_INHERIT;
RESTORE_RETURNLENGTH();
}
else if (ProcessInformationClass == ProcessDebugPort)
{
BACKUP_RETURNLENGTH();
*((HANDLE *)ProcessInformation) = nullptr;
RESTORE_RETURNLENGTH();
}
else if (ProcessInformationClass == ProcessBasicInformation) //Fake parent
{
BACKUP_RETURNLENGTH();
((PPROCESS_BASIC_INFORMATION)ProcessInformation)->InheritedFromUniqueProcessId = ULongToHandle(GetExplorerProcessId());
RESTORE_RETURNLENGTH();
}
else if (ProcessInformationClass == ProcessBreakOnTermination)
{
BACKUP_RETURNLENGTH();
*((ULONG *)ProcessInformation) = ValueProcessBreakOnTermination;
RESTORE_RETURNLENGTH();
}
else if (ProcessInformationClass == ProcessHandleTracing)
{
BACKUP_RETURNLENGTH();
RESTORE_RETURNLENGTH(); // Trigger any possible exceptions caused by messing with the output buffer before changing the final return status
Status = IsProcessHandleTracingEnabled ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER;
}
else if (ProcessInformationClass == ProcessIoCounters)
{
BACKUP_RETURNLENGTH();
((PIO_COUNTERS)ProcessInformation)->OtherOperationCount = 1;
RESTORE_RETURNLENGTH();
}
}
return Status;
}
return HookDllData.dNtQueryInformationProcess(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength);
}
NTSTATUS NTAPI HookedNtSetInformationProcess(HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength)
{
if (ProcessHandle == NtCurrentProcess || HandleToULong(NtCurrentTeb()->ClientId.UniqueProcess) == GetProcessIdByProcessHandle(ProcessHandle))
{
if (ProcessInformationClass == ProcessBreakOnTermination)
{
if (ProcessInformationLength != sizeof(ULONG))
{
return STATUS_INFO_LENGTH_MISMATCH;
}
// NtSetInformationProcess will happily dereference this pointer
if (ProcessInformation == NULL)
{
return STATUS_ACCESS_VIOLATION;
}
// A process must have debug privileges enabled to set the ProcessBreakOnTermination flag
if (!HasDebugPrivileges(NtCurrentProcess))
{
return STATUS_PRIVILEGE_NOT_HELD;
}
ValueProcessBreakOnTermination = *((ULONG *)ProcessInformation);
return STATUS_SUCCESS;
}
// Don't allow changing the debug inherit flag, and keep track of the new value to report in NtQIP
if (ProcessInformationClass == ProcessDebugFlags)
{
if (ProcessInformationLength != sizeof(ULONG))
{
return STATUS_INFO_LENGTH_MISMATCH;
}
if (ProcessInformation == NULL)
{
return STATUS_ACCESS_VIOLATION;
}
ULONG Flags = *(ULONG*)ProcessInformation;
if ((Flags & ~PROCESS_DEBUG_INHERIT) != 0)
{
return STATUS_INVALID_PARAMETER;
}
if ((Flags & PROCESS_DEBUG_INHERIT) != 0)
{
ValueProcessDebugFlags &= ~PROCESS_NO_DEBUG_INHERIT;
}
else
{
ValueProcessDebugFlags |= PROCESS_NO_DEBUG_INHERIT;
}
return STATUS_SUCCESS;
}
//PROCESS_HANDLE_TRACING_ENABLE -> ULONG, PROCESS_HANDLE_TRACING_ENABLE_EX -> ULONG,ULONG
if (ProcessInformationClass == ProcessHandleTracing)
{
bool enable = ProcessInformationLength != 0; // A length of 0 is valid and indicates we should disable tracing
if (enable)
{
if (ProcessInformationLength != sizeof(ULONG) && ProcessInformationLength != (sizeof(ULONG) * 2))
{
return STATUS_INFO_LENGTH_MISMATCH;
}
// NtSetInformationProcess will happily dereference this pointer
if (ProcessInformation == NULL)
{
return STATUS_ACCESS_VIOLATION;
}
PPROCESS_HANDLE_TRACING_ENABLE_EX phtEx = (PPROCESS_HANDLE_TRACING_ENABLE_EX)ProcessInformation;
if (phtEx->Flags != 0)
{
return STATUS_INVALID_PARAMETER;
}
}
IsProcessHandleTracingEnabled = enable;
return STATUS_SUCCESS;
}
}
return HookDllData.dNtSetInformationProcess(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength);
}
NTSTATUS NTAPI HookedNtQueryObject(HANDLE Handle, OBJECT_INFORMATION_CLASS ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength)
{
NTSTATUS ntStat = HookDllData.dNtQueryObject(Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, ReturnLength);
if ((ObjectInformationClass == ObjectTypesInformation ||
ObjectInformationClass == ObjectTypeInformation) &&
(NT_SUCCESS(ntStat) && ObjectInformation))
{
if (ObjectInformationClass == ObjectTypesInformation)
{
BACKUP_RETURNLENGTH();
FilterObjects((POBJECT_TYPES_INFORMATION)ObjectInformation);
RESTORE_RETURNLENGTH();
}
else if (ObjectInformationClass == ObjectTypeInformation)
{
BACKUP_RETURNLENGTH();
FilterObject((POBJECT_TYPE_INFORMATION)ObjectInformation, false);
RESTORE_RETURNLENGTH();
}
}
return ntStat;
}
NTSTATUS NTAPI HookedNtYieldExecution()
{
HookDllData.dNtYieldExecution();
return STATUS_ACCESS_DENIED; //better than STATUS_SUCCESS or STATUS_NO_YIELD_PERFORMED
}
NTSTATUS NTAPI HookedNtGetContextThread(HANDLE ThreadHandle, PCONTEXT ThreadContext)
{
DWORD ContextBackup = 0;
BOOLEAN DebugRegistersRequested = FALSE;
if (ThreadHandle == NtCurrentThread ||
HandleToULong(NtCurrentTeb()->ClientId.UniqueProcess) == GetProcessIdByThreadHandle(ThreadHandle)) //thread inside this process?
{
if (ThreadContext)
{
ContextBackup = ThreadContext->ContextFlags;
ThreadContext->ContextFlags &= ~CONTEXT_DEBUG_REGISTERS;
DebugRegistersRequested = ThreadContext->ContextFlags != ContextBackup;
}
}
NTSTATUS ntStat = HookDllData.dNtGetContextThread(ThreadHandle, ThreadContext);
if (ContextBackup)
{
ThreadContext->ContextFlags = ContextBackup;
if (DebugRegistersRequested)
{
ThreadContext->Dr0 = 0;
ThreadContext->Dr1 = 0;
ThreadContext->Dr2 = 0;
ThreadContext->Dr3 = 0;
ThreadContext->Dr6 = 0;
ThreadContext->Dr7 = 0;
#ifdef _WIN64
ThreadContext->LastBranchToRip = 0;
ThreadContext->LastBranchFromRip = 0;
ThreadContext->LastExceptionToRip = 0;
ThreadContext->LastExceptionFromRip = 0;
#endif
}
}
return ntStat;
}
NTSTATUS NTAPI HookedNtSetContextThread(HANDLE ThreadHandle, PCONTEXT ThreadContext)
{
DWORD ContextBackup = 0;
if (ThreadHandle == NtCurrentThread ||
HandleToULong(NtCurrentTeb()->ClientId.UniqueProcess) == GetProcessIdByThreadHandle(ThreadHandle)) //thread inside this process?
{
if (ThreadContext)
{
ContextBackup = ThreadContext->ContextFlags;
ThreadContext->ContextFlags &= ~CONTEXT_DEBUG_REGISTERS;
}
}
NTSTATUS ntStat = HookDllData.dNtSetContextThread(ThreadHandle, ThreadContext);
if (ContextBackup)
{
ThreadContext->ContextFlags = ContextBackup;
}
return ntStat;
}
void NTAPI HandleKiUserExceptionDispatcher(PEXCEPTION_RECORD pExcptRec, PCONTEXT ContextFrame)
{
if (ContextFrame && (ContextFrame->ContextFlags & CONTEXT_DEBUG_REGISTERS))
{
int slotIndex = ThreadDebugContextFindFreeSlotIndex();
if (slotIndex != -1)
{
ThreadDebugContextSaveContext(slotIndex, ContextFrame);
}
ContextFrame->Dr0 = 0;
ContextFrame->Dr1 = 0;
ContextFrame->Dr2 = 0;
ContextFrame->Dr3 = 0;
ContextFrame->Dr6 = 0;
ContextFrame->Dr7 = 0;
}
}
#ifdef _WIN64
void NTAPI HookedKiUserExceptionDispatcher()
{
// inline assembly is not supported in x86_64 with CL. a more elegant
// way to do this would be to modify the project to include an .asm
// source file that defines 'HookedKiUserExceptionDispatcher' for both
// 32 and 64 bit.
// the + 8 in the line below is because we arrive at this function via
// a CALL instruction which causes the stack to shift. This CALL in
// the trampoline is necessary because HandleKiUserExceptionDispatcher
// will end in a RET instruction, and the CALL preserves the stack.
PCONTEXT ContextFrame = (PCONTEXT)(((UINT_PTR)_AddressOfReturnAddress()) + 8);
HandleKiUserExceptionDispatcher(nullptr, ContextFrame);
}
#else
VOID NAKED NTAPI HookedKiUserExceptionDispatcher()// (PEXCEPTION_RECORD pExcptRec, PCONTEXT ContextFrame) //remove DRx Registers
{
//MOV ECX,DWORD PTR SS:[ESP+4] <- ContextFrame
//MOV EBX,DWORD PTR SS:[ESP] <- pExcptRec
__asm
{
MOV EAX, [ESP + 4]
MOV ECX, [ESP]
PUSH EAX
PUSH ECX
CALL HandleKiUserExceptionDispatcher
jmp HookDllData.dKiUserExceptionDispatcher
}
//return HookDllData.dKiUserExceptionDispatcher(pExcptRec, ContextFrame);
}
#endif
static DWORD_PTR KiUserExceptionDispatcherAddress = 0;
NTSTATUS NTAPI HookedNtContinue(PCONTEXT ThreadContext, BOOLEAN RaiseAlert) //restore DRx Registers
{
DWORD_PTR retAddress = (DWORD_PTR)_ReturnAddress();
if (!KiUserExceptionDispatcherAddress)
{
UNICODE_STRING NtdllName = RTL_CONSTANT_STRING(L"ntdll.dll");
PVOID Ntdll;
if (NT_SUCCESS(LdrGetDllHandle(nullptr, nullptr, &NtdllName, &Ntdll)))
{
ANSI_STRING KiUserExceptionDispatcherName = RTL_CONSTANT_ANSI_STRING("KiUserExceptionDispatcher");
LdrGetProcedureAddress(Ntdll, &KiUserExceptionDispatcherName, 0, (PVOID*)&KiUserExceptionDispatcherAddress);
}
}
if (ThreadContext != nullptr &&
retAddress >= KiUserExceptionDispatcherAddress && retAddress < (KiUserExceptionDispatcherAddress + 0x100))
{
int index = ThreadDebugContextFindExistingSlotIndex();
if (index != -1)
{
ThreadContext->Dr0 = ArrayDebugRegister[index].Dr0;
ThreadContext->Dr1 = ArrayDebugRegister[index].Dr1;
ThreadContext->Dr2 = ArrayDebugRegister[index].Dr2;
ThreadContext->Dr3 = ArrayDebugRegister[index].Dr3;
ThreadContext->Dr6 = ArrayDebugRegister[index].Dr6;
ThreadContext->Dr7 = ArrayDebugRegister[index].Dr7;
ThreadDebugContextRemoveEntry(index);
}
}
return HookDllData.dNtContinue(ThreadContext, RaiseAlert);
}
#ifndef _WIN64
PVOID NTAPI HandleNativeCallInternal(DWORD eaxValue, DWORD ecxValue)
{
for (ULONG i = 0; i < _countof(HookDllData.HookNative); i++)
{
if (HookDllData.HookNative[i].eaxValue == eaxValue)
{
if (HookDllData.HookNative[i].ecxValue)
{
if (HookDllData.HookNative[i].ecxValue == ecxValue)
{
return HookDllData.HookNative[i].hookedFunction;
}
}
else
{
return HookDllData.HookNative[i].hookedFunction;
}
}
}
return 0;
}
#endif
void NAKED NTAPI HookedNativeCallInternal()
{
#ifndef _WIN64
__asm
{
PUSHAD
PUSH ECX
PUSH EAX
CALL HandleNativeCallInternal
cmp eax, 0
je NoHook
POPAD
ADD ESP,4
PUSH ECX
PUSH EAX
CALL HandleNativeCallInternal
jmp eax
NoHook:
POPAD
jmp HookDllData.NativeCallContinue
}
#endif
}
NTSTATUS NTAPI HookedNtClose(HANDLE Handle)
{
OBJECT_HANDLE_FLAG_INFORMATION flags;
NTSTATUS Status;
if (HookDllData.dNtQueryObject != nullptr)
Status = HookDllData.dNtQueryObject(Handle, ObjectHandleFlagInformation, &flags, sizeof(OBJECT_HANDLE_FLAG_INFORMATION), nullptr);
else
Status = NtQueryObject(Handle, ObjectHandleFlagInformation, &flags, sizeof(OBJECT_HANDLE_FLAG_INFORMATION), nullptr);
if (NT_SUCCESS(Status))
{
if (flags.ProtectFromClose)
{
return STATUS_HANDLE_NOT_CLOSABLE;
}
return HookDllData.dNtClose(Handle);
}
return STATUS_INVALID_HANDLE;
}
NTSTATUS NTAPI HookedNtDuplicateObject(HANDLE SourceProcessHandle, HANDLE SourceHandle, HANDLE TargetProcessHandle, PHANDLE TargetHandle, ACCESS_MASK DesiredAccess, ULONG HandleAttributes, ULONG Options)
{
if (Options & DUPLICATE_CLOSE_SOURCE)
{
// If a process is being debugged and duplicates a handle with DUPLICATE_CLOSE_SOURCE, *and* the handle has the ProtectFromClose bit set, a STATUS_HANDLE_NOT_CLOSABLE exception will occur.
// This is actually the exact same exception we already check for in NtClose, but the difference is that this NtClose call happens inside the kernel which we obviously can't hook.
// When a process is not being debugged, NtDuplicateObject will simply return success without closing the source. This is because ObDuplicateObject ignores NtClose return values
OBJECT_HANDLE_FLAG_INFORMATION HandleFlags;
NTSTATUS Status;
if (HookDllData.dNtQueryObject != nullptr)
Status = HookDllData.dNtQueryObject(SourceHandle, ObjectHandleFlagInformation, &HandleFlags, sizeof(HandleFlags), nullptr);
else
Status = NtQueryObject(SourceHandle, ObjectHandleFlagInformation, &HandleFlags, sizeof(HandleFlags), nullptr);
if (NT_SUCCESS(Status) && HandleFlags.ProtectFromClose)
{
// Prevent the exception
Options &= ~DUPLICATE_CLOSE_SOURCE;
}
}
return HookDllData.dNtDuplicateObject(SourceProcessHandle, SourceHandle, TargetProcessHandle, TargetHandle, DesiredAccess, HandleAttributes, Options);
}
//////////////////////////////////////////////////////////////
////////////////////// TIME FUNCTIONS ////////////////////////
//////////////////////////////////////////////////////////////
static DWORD OneTickCount = 0;
DWORD WINAPI HookedGetTickCount(void)
{
if (!OneTickCount)
{
OneTickCount = HookDllData.dGetTickCount();
}
else
{
OneTickCount++;
}
return OneTickCount;
}
ULONGLONG WINAPI HookedGetTickCount64(void) //yes we can use DWORD
{
if (!OneTickCount)
{
if (HookDllData.dGetTickCount)
{
OneTickCount = HookDllData.dGetTickCount();
}
else
{
OneTickCount = RtlGetTickCount();
}
}
else
{
OneTickCount++;
}
return OneTickCount;
}
static SYSTEMTIME OneLocalTime = {0};
static SYSTEMTIME OneSystemTime = {0};
void WINAPI HookedGetLocalTime(LPSYSTEMTIME lpSystemTime)
{
if (!OneLocalTime.wYear)
{
RealGetLocalTime(&OneLocalTime);
if (HookDllData.dGetSystemTime)
{
RealGetSystemTime(&OneSystemTime);
}
}
else
{
IncreaseSystemTime(&OneLocalTime);
if (HookDllData.dGetSystemTime)
{
IncreaseSystemTime(&OneSystemTime);
}
}
if (lpSystemTime)
{
memcpy(lpSystemTime, &OneLocalTime, sizeof(SYSTEMTIME));
}
}
void WINAPI HookedGetSystemTime(LPSYSTEMTIME lpSystemTime)
{
if (!OneSystemTime.wYear)
{
RealGetSystemTime(&OneSystemTime);
if (HookDllData.dGetLocalTime)
{
RealGetLocalTime(&OneLocalTime);
}
}
else
{
IncreaseSystemTime(&OneSystemTime);
if (HookDllData.dGetLocalTime)
{
IncreaseSystemTime(&OneLocalTime);
}
}
if (lpSystemTime)
{
memcpy(lpSystemTime, &OneSystemTime, sizeof(SYSTEMTIME));
}
}
static LARGE_INTEGER OneNativeSysTime = {0};
NTSTATUS WINAPI HookedNtQuerySystemTime(PLARGE_INTEGER SystemTime)
{
if (!OneNativeSysTime.QuadPart)
{
HookDllData.dNtQuerySystemTime(&OneNativeSysTime);
}
else
{
OneNativeSysTime.QuadPart++;
}
NTSTATUS ntStat = HookDllData.dNtQuerySystemTime(SystemTime);
if (ntStat == STATUS_SUCCESS)
{
if (SystemTime)
{
SystemTime->QuadPart = OneNativeSysTime.QuadPart;
}
}
return ntStat;
}
static LARGE_INTEGER OnePerformanceCounter = {0};
static LARGE_INTEGER OnePerformanceFrequency = {0};
NTSTATUS NTAPI HookedNtQueryPerformanceCounter(PLARGE_INTEGER PerformanceCounter, PLARGE_INTEGER PerformanceFrequency)
{
if (!OnePerformanceCounter.QuadPart)
{
HookDllData.dNtQueryPerformanceCounter(&OnePerformanceCounter, &OnePerformanceFrequency);
}
else
{
OnePerformanceCounter.QuadPart++;
}
NTSTATUS ntStat = HookDllData.dNtQueryPerformanceCounter(PerformanceCounter, PerformanceFrequency);
if (ntStat == STATUS_SUCCESS)
{
if (PerformanceFrequency) //OPTIONAL
{
PerformanceFrequency->QuadPart = OnePerformanceFrequency.QuadPart;
}
if (PerformanceCounter)
{
PerformanceCounter->QuadPart = OnePerformanceCounter.QuadPart;
}
}
return ntStat;
}
//////////////////////////////////////////////////////////////
////////////////////// TIME FUNCTIONS ////////////////////////
//////////////////////////////////////////////////////////////
static BOOL isBlocked = FALSE;
BOOL NTAPI HookedNtUserBlockInput(BOOL fBlockIt)
{
if (isBlocked == FALSE && fBlockIt != FALSE)
{
isBlocked = TRUE;
return TRUE;
}
else if (isBlocked != FALSE && fBlockIt == FALSE)
{
isBlocked = FALSE;
return TRUE;
}
return FALSE;
}
//GetLastError() function might not change if a debugger is present (it has never been the case that it is always set to zero).
DWORD WINAPI HookedOutputDebugStringA(LPCSTR lpOutputString) //Worst anti-debug ever
{
if (RtlNtMajorVersion() >= 6) // Vista or later
return 0;
NtCurrentTeb()->LastErrorValue = NtCurrentTeb()->LastErrorValue + 1; //change last error
return 1; //WinXP EAX -> 1
}
HWND NTAPI HookedNtUserFindWindowEx(HWND hWndParent, HWND hWndChildAfter, PUNICODE_STRING lpszClass, PUNICODE_STRING lpszWindow, DWORD dwType)
{
HWND resultHwnd = HookDllData.dNtUserFindWindowEx(hWndParent, hWndChildAfter, lpszClass, lpszWindow, dwType);
if (resultHwnd)
{
if (IsWindowClassNameBad(lpszClass) || IsWindowNameBad(lpszWindow))
{
return 0;
}
if (HookDllData.EnableProtectProcessId == TRUE)
{
DWORD dwProcessId;
if (HookDllData.dNtUserQueryWindow)
{
dwProcessId = HandleToULong(HookDllData.dNtUserQueryWindow(resultHwnd, WindowProcess));
}
else
{
dwProcessId = HandleToULong(HookDllData.NtUserQueryWindow(resultHwnd, WindowProcess));
}
if (dwProcessId == HookDllData.dwProtectedProcessId)
{
return 0;
}
}
}
return resultHwnd;
}
NTSTATUS NTAPI HookedNtSetDebugFilterState(ULONG ComponentId, ULONG Level, BOOLEAN State)
{
return HasDebugPrivileges(NtCurrentProcess) ? STATUS_SUCCESS : STATUS_ACCESS_DENIED;
}
void FilterHwndList(HWND * phwndFirst, PULONG pcHwndNeeded)
{
for (UINT i = 0; i < *pcHwndNeeded; i++)
{
if (phwndFirst[i] != nullptr && IsWindowBad(phwndFirst[i]))
{
if (i == 0)
{
// Find the first HWND that belongs to a different process (i + 1, i + 2... may still be ours)
for (UINT j = i + 1; j < *pcHwndNeeded; j++)
{
if (phwndFirst[j] != nullptr && !IsWindowBad(phwndFirst[j]))
{
phwndFirst[i] = phwndFirst[j];
break;
}
}
}
else
{
phwndFirst[i] = phwndFirst[i - 1]; //just override with previous
}
}
}
}
NTSTATUS NTAPI HookedNtUserBuildHwndList(HDESK hDesktop, HWND hwndParent, BOOLEAN bChildren, ULONG dwThreadId, ULONG lParam, HWND* pWnd, PULONG pBufSize)
{
NTSTATUS ntStat = HookDllData.dNtUserBuildHwndList(hDesktop, hwndParent, bChildren, dwThreadId, lParam, pWnd, pBufSize);
if (NT_SUCCESS(ntStat) && pWnd != nullptr && pBufSize != nullptr)
{
FilterHwndList(pWnd, pBufSize);
}
return ntStat;
}
NTSTATUS NTAPI HookedNtUserBuildHwndList_Eight(HDESK hDesktop, HWND hwndParent, BOOLEAN bChildren, BOOLEAN bUnknownFlag, ULONG dwThreadId, ULONG lParam, HWND* pWnd, PULONG pBufSize)
{
NTSTATUS ntStat = ((t_NtUserBuildHwndList_Eight)HookDllData.dNtUserBuildHwndList)(hDesktop, hwndParent, bChildren, bUnknownFlag, dwThreadId, lParam, pWnd, pBufSize);
if (NT_SUCCESS(ntStat) && pWnd != nullptr && pBufSize != nullptr)
{
FilterHwndList(pWnd, pBufSize);
}
return ntStat;
}
HANDLE NTAPI HookedNtUserQueryWindow(HWND hwnd, WINDOWINFOCLASS WindowInfo)
{
if ((WindowInfo == WindowProcess || WindowInfo == WindowThread) && IsWindowBad(hwnd))
{
if (WindowInfo == WindowProcess)
return NtCurrentTeb()->ClientId.UniqueProcess;
if (WindowInfo == WindowThread)
return NtCurrentTeb()->ClientId.UniqueThread;
}
return HookDllData.dNtUserQueryWindow(hwnd, WindowInfo);
}
HWND NTAPI HookedNtUserGetForegroundWindow()
{
HWND Hwnd = HookDllData.dNtUserGetForegroundWindow();
if (Hwnd != nullptr && IsWindowBad(Hwnd))
{
Hwnd = (HWND)HookDllData.NtUserGetThreadState(THREADSTATE_ACTIVEWINDOW);
}
return Hwnd;
}
//WIN XP: CreateThread -> CreateRemoteThread -> NtCreateThread
NTSTATUS NTAPI HookedNtCreateThread(PHANDLE ThreadHandle,ACCESS_MASK DesiredAccess,POBJECT_ATTRIBUTES ObjectAttributes,HANDLE ProcessHandle,PCLIENT_ID ClientId,PCONTEXT ThreadContext,PINITIAL_TEB InitialTeb,BOOLEAN CreateSuspended)
{
if (ProcessHandle == NtCurrentProcess)
{
return STATUS_INSUFFICIENT_RESOURCES;//STATUS_INVALID_PARAMETER STATUS_INVALID_HANDLE STATUS_INSUFFICIENT_RESOURCES
}
return HookDllData.dNtCreateThread(ThreadHandle, DesiredAccess, ObjectAttributes, ProcessHandle, ClientId,ThreadContext, InitialTeb,CreateSuspended);
}
//WIN 7: CreateThread -> CreateRemoteThreadEx -> NtCreateThreadEx
NTSTATUS NTAPI HookedNtCreateThreadEx(PHANDLE ThreadHandle,ACCESS_MASK DesiredAccess,POBJECT_ATTRIBUTES ObjectAttributes,HANDLE ProcessHandle,PUSER_THREAD_START_ROUTINE StartRoutine,PVOID Argument,ULONG CreateFlags,ULONG_PTR ZeroBits,SIZE_T StackSize,SIZE_T MaximumStackSize,PPS_ATTRIBUTE_LIST AttributeList)
{
if (HookDllData.EnableNtCreateThreadExHook == TRUE) //prevent hide from debugger
{
if (CreateFlags & THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER)
{
CreateFlags ^= THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER;
}
}
if (HookDllData.EnablePreventThreadCreation == TRUE)
{
if (ProcessHandle == NtCurrentProcess)
{
return STATUS_INSUFFICIENT_RESOURCES;//STATUS_INVALID_PARAMETER STATUS_INVALID_HANDLE STATUS_INSUFFICIENT_RESOURCES
}
}
return HookDllData.dNtCreateThreadEx(ThreadHandle, DesiredAccess, ObjectAttributes, ProcessHandle, StartRoutine, Argument, CreateFlags, ZeroBits, StackSize, MaximumStackSize,AttributeList);
}
void FilterHandleInfo(PSYSTEM_HANDLE_INFORMATION pHandleInfo, PULONG pReturnLengthAdjust)
{
*pReturnLengthAdjust = 0;
const ULONG TrueCount = pHandleInfo->NumberOfHandles;
for (ULONG i = 0; i < TrueCount; ++i)
{
// TODO: protect processes by name too
if ((HookDllData.EnableProtectProcessId == TRUE && (ULONG)(pHandleInfo->Handles[i].UniqueProcessId == HookDllData.dwProtectedProcessId)) &&
IsObjectTypeBad(pHandleInfo->Handles[i].ObjectTypeIndex))