forked from ekknod/acdrv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1109 lines (941 loc) · 29.3 KB
/
main.cpp
File metadata and controls
1109 lines (941 loc) · 29.3 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 <ntifs.h>
#include <ntddmou.h>
#include <kbdmou.h>
#include <intrin.h>
#include "img.h"
//
// features:
// - exception hook
// - mouse hook
// - syscall hook (https://github.com/everdox/InfinityHook)
// - SwapContext hook
// tested Win11 22H3 + Win10 22H2 HVCI/Core Isolation enabled
//
#define POOLTAG (DWORD)'ACEC'
typedef ULONG_PTR QWORD;
typedef unsigned __int32 DWORD;
typedef unsigned __int16 WORD;
typedef unsigned __int8 BYTE;
#define LOG(...) DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[driver.sys] " __VA_ARGS__)
typedef struct
{
QWORD base, size;
} MODULE_INFO;
MODULE_INFO get_module_info(PWCH module_name);
void NtSleep(DWORD milliseconds)
{
QWORD ms = milliseconds;
ms = (ms * 1000) * 10;
ms = ms * -1;
#ifdef _KERNEL_MODE
KeDelayExecutionThread(KernelMode, 0, (PLARGE_INTEGER)&ms);
#else
NtDelayExecution(0, (PLARGE_INTEGER)&ms);
#endif
}
namespace globals
{
MODULE_INFO ntoskrnl;
MODULE_INFO vmusbmouse;
DWORD exit = 0;
}
namespace hooks
{
BOOLEAN install(void);
void uninstall(void);
namespace efi
{
QWORD(*oGetVariable)(PCWCH VariableName, GUID* VendorGuid, DWORD* Attributes, QWORD* DataSize, VOID* Data);
QWORD(*oSetVariable)(PCWCH VariableName, GUID* VendorGuid, DWORD Attributes, QWORD DataSize, VOID* Data);
QWORD NtSetSystemEnvironmentValueEx;
QWORD NtQuerySystemEnvironmentValueEx;
NTSTATUS NTAPI NtQuerySystemEnvironmentValueExHook(
PUNICODE_STRING VariableName,
LPGUID VendorGuid,
PVOID Value,
PULONG ValueLength,
PULONG Attributes
);
NTSTATUS NTAPI NtSetSystemEnvironmentValueExHook(
PUNICODE_STRING VariableName,
LPGUID VendorGuid,
PVOID Value,
ULONG ValueLength,
ULONG Attributes
);
}
namespace syscall
{
QWORD SystemCallEntryPage;
void __fastcall SyscallStub(unsigned int SyscallIndex, void** SyscallFunction);
QWORD(*oKeQueryPerformanceCounter)(QWORD rcx);
QWORD KeQueryPerformanceCounterHook(QWORD rcx);
}
namespace input
{
PDRIVER_OBJECT mouclass;
PDRIVER_OBJECT mouhid;
QWORD mouclass_routine;
MOUSE_INPUT_DATA mouse_data;
PMOUSE_INPUT_DATA mouse_irp;
NTSTATUS (*rimInputApc)(void* a1, void* a2, void* a3, void* a4, void* a5);
NTSTATUS (*oMouseClassRead)(PDEVICE_OBJECT device, PIRP irp);
NTSTATUS (*oMouseAddDevice)(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT PhysicalDeviceObject);
QWORD MouseClassServiceCallbackHook(PDEVICE_OBJECT DeviceObject, PMOUSE_INPUT_DATA InputDataStart, PMOUSE_INPUT_DATA InputDataEnd, PULONG InputDataConsumed);
NTSTATUS MouseApc(void* a1, void* a2, void* a3, void* a4, void* a5);
NTSTATUS MouseClassReadHook(PDEVICE_OBJECT device, PIRP irp);
NTSTATUS MouseAddDeviceHook(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject);
}
namespace exception
{
QWORD KdpDebugRoutineSelect;
QWORD PoHiderInProgress;
void (*oKdTrap)(void);
void KdTrapHook();
}
namespace swap_ctx
{
UCHAR(*oHalClearLastBranchRecordStack)(void);
UCHAR HalClearLastBranchRecordStackHook();
}
}
enum class TRACE_OPERATION
{
TRACE_START,
TRACE_SYSCALL,
TRACE_END
};
NTSTATUS ApplyTraceSettings(_In_ TRACE_OPERATION Operation);
QWORD FindPattern(QWORD base, unsigned char* pattern, unsigned char* mask);
extern "C" VOID DriverUnload(
_In_ struct _DRIVER_OBJECT* DriverObject
)
{
UNREFERENCED_PARAMETER(DriverObject);
globals::exit = 1;
while (globals::exit != 2)
{
NtSleep(100);
LOG("Please move mouse in order to unload the driver\n");
}
hooks::uninstall();
NtSleep(200);
LOG("Shutdown\n");
}
extern "C" NTSTATUS DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
UNREFERENCED_PARAMETER(RegistryPath);
UNREFERENCED_PARAMETER(DriverObject);
globals::ntoskrnl = get_module_info(0);
globals::vmusbmouse = get_module_info(L"vmusbmouse.sys");
if (!hooks::install())
{
LOG("failed to install hooks\n");
return STATUS_ENTRYPOINT_NOT_FOUND;
}
LOG("Running\n");
DriverObject->DriverUnload = DriverUnload;
return STATUS_SUCCESS;
}
NTSTATUS NTAPI hooks::efi::NtQuerySystemEnvironmentValueExHook(
PUNICODE_STRING VariableName,
LPGUID VendorGuid,
PVOID Value,
PULONG ValueLength,
PULONG Attributes
)
{
if (VariableName == 0 || VendorGuid == 0)
{
return STATUS_INVALID_PARAMETER_1;
}
//
// if someone has x86-x64 emulator with basic x86/x64 instruction set, feel free to commit
//
// cpu::emulator(efi::oGetVariable, VariableName, VendorGuid, Attributes, DataSize, Data);
//
QWORD status = oGetVariable(VariableName->Buffer, VendorGuid, (DWORD*)Attributes, (QWORD*)ValueLength, Value);
if (status != 0)
{
return STATUS_INVALID_PARAMETER;
}
return STATUS_SUCCESS;
}
NTSTATUS NTAPI hooks::efi::NtSetSystemEnvironmentValueExHook(
PUNICODE_STRING VariableName,
LPGUID VendorGuid,
PVOID Value,
ULONG ValueLength,
ULONG Attributes
)
{
if (VariableName == 0 || VendorGuid == 0)
{
return STATUS_INVALID_PARAMETER_1;
}
//
// if someone has x86-x64 emulator with basic x86/x64 instruction set, feel free to commit
//
// cpu::emulator(efi::oSetVariable, VariableName, VendorGuid, Attributes, DataSize, Data);
//
QWORD status = oSetVariable(VariableName->Buffer, VendorGuid, Attributes, ValueLength, Value);
if (status != 0)
{
return STATUS_INVALID_PARAMETER;
}
return STATUS_SUCCESS;
}
void __fastcall hooks::syscall::SyscallStub(unsigned int SyscallIndex, void** SyscallFunction)
{
UNREFERENCED_PARAMETER(SyscallIndex);
UNREFERENCED_PARAMETER(SyscallFunction);
if (*SyscallFunction == (void*)efi::NtQuerySystemEnvironmentValueEx)
{
*SyscallFunction = efi::NtQuerySystemEnvironmentValueExHook;
}
else if (*SyscallFunction == (void*)efi::NtSetSystemEnvironmentValueEx)
{
*SyscallFunction = efi::NtSetSystemEnvironmentValueExHook;
}
}
QWORD hooks::syscall::KeQueryPerformanceCounterHook(QWORD rcx)
{
if (ExGetPreviousMode() == KernelMode)
{
return oKeQueryPerformanceCounter(rcx);
}
QWORD current_thread = (QWORD)PsGetCurrentThread();
DWORD syscall_index = *(DWORD*)(current_thread + 0x80);
if (KeGetCurrentIrql() != PASSIVE_LEVEL)
{
return oKeQueryPerformanceCounter(rcx);
}
PVOID* StackMax = (PVOID*)__readgsqword(0x1A8);
PVOID* StackFrame = (PVOID*)_AddressOfReturnAddress();
for (PVOID* StackCurrent = StackMax;
StackCurrent > StackFrame;
--StackCurrent)
{
PULONG AsUlong = (PULONG)StackCurrent;
if (*AsUlong != ((ULONG)0x501802))
{
continue;
}
//
// If the first magic is set, check for the second magic.
//
--StackCurrent;
PUSHORT AsShort = (PUSHORT)StackCurrent;
if (*AsShort != ((USHORT)0xF33))
{
continue;
}
//
// Now we reverse the direction of the stack walk.
//
int index = 0;
for (;
StackCurrent < StackMax;
++StackCurrent)
{
PULONGLONG AsUlonglong = (PULONGLONG)StackCurrent;
index++;
if (index > 8)
{
break;
}
if (!(PAGE_ALIGN(*AsUlonglong) >= (PVOID)syscall::SystemCallEntryPage &&
PAGE_ALIGN(*AsUlonglong) < (PVOID)((uintptr_t)syscall::SystemCallEntryPage + (PAGE_SIZE * 2))))
{
continue;
}
void** syscall = &StackCurrent[9];
SyscallStub(syscall_index, syscall);
break;
}
break;
}
return oKeQueryPerformanceCounter(rcx);
}
QWORD hooks::input::MouseClassServiceCallbackHook(
PDEVICE_OBJECT DeviceObject,
PMOUSE_INPUT_DATA InputDataStart,
PMOUSE_INPUT_DATA InputDataEnd,
PULONG InputDataConsumed
)
{
QWORD rsp = (QWORD)_AddressOfReturnAddress();
rsp = rsp + 0x08; // call MouseClassServiceCallback
rsp = rsp + 0x08; // push rbp
rsp = rsp + 0x08; // push rbx
rsp = rsp + 0x08; // push rsi
rsp = rsp + 0x08; // push rdi
rsp = rsp + 0x08; // push r12
rsp = rsp + 0x08; // push r13
rsp = rsp + 0x08; // push r14
rsp = rsp + 0x08; // push r15
rsp = rsp + 0x58; // sub rsp, 58h
QWORD return_address = *(QWORD*)(rsp);
//
// extra data
// *(UCHAR*)(__readgsqword(0x20) + 0x33BA) == 1 (DpcRoutineActive)
// *(QWORD*)(__readgsqword(0x20) + 0x3320) == Wdf01000.sys:0x6ca0 (void __fastcall imp_VfWdfRequestGetParameters) (CurrentDpcRoutine)
//
//
// call should be coming from ntoskrnl.exe IopfCompleteRequest
//
if (return_address >= globals::ntoskrnl.base && return_address <= (globals::ntoskrnl.base + globals::ntoskrnl.size))
{
mouse_data = *InputDataStart;
}
else
{
memset(&mouse_data, 0, sizeof(mouse_data));
}
//
// HidpDistributeInterruptReport->IofCompleteRequest->IopfCompleteRequest->MouHid_ReadComplete->MouseClassServiceCallback->MouseClassRead->win32k.sys:rimInputApc
//
return ((QWORD(*)(PDEVICE_OBJECT, PMOUSE_INPUT_DATA, PMOUSE_INPUT_DATA, PULONG))(mouclass_routine))(
DeviceObject,
InputDataStart,
InputDataEnd,
InputDataConsumed
);
}
//
// https:://github.com/everdox/hidinput
//
NTSTATUS hooks::input::MouseApc(void* a1, void* a2, void* a3, void* a4, void* a5)
{
for (int i = sizeof(MOUSE_INPUT_DATA); i--;)
{
if (((unsigned char*)mouse_irp)[i] != ((unsigned char*)&mouse_data)[i])
{
DbgPrintEx(77, 0, "invalid mouse packet detected\n");
break;
}
}
return rimInputApc(a1, a2, a3, a4, a5);
}
//
// https:://github.com/everdox/hidinput
//
NTSTATUS hooks::input::MouseClassReadHook(PDEVICE_OBJECT device, PIRP irp)
{
//
// do not allow mouse hook with vmware
//
if (globals::vmusbmouse.base == 0)
{
QWORD* routine;
routine = (QWORD*)irp;
routine += 0xb;
if (rimInputApc == 0)
{
*(QWORD*)&rimInputApc = *routine;
}
if (globals::exit == 0)
{
*routine = (ULONGLONG)MouseApc;
}
else
{
if (rimInputApc)
{
*routine = (ULONGLONG)rimInputApc;
}
globals::exit = 2;
}
mouse_irp = (struct _MOUSE_INPUT_DATA*)irp->UserBuffer;
}
return hooks::input::oMouseClassRead(device, irp);
}
void update_mouse_devices(QWORD callback, QWORD original_callback, PDRIVER_OBJECT mouclass, PDRIVER_OBJECT mouhid);
NTSTATUS hooks::input::MouseAddDeviceHook(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject)
{
NTSTATUS status = oMouseAddDevice(DriverObject, PhysicalDeviceObject);
if (status == 0)
{
update_mouse_devices((QWORD)mouclass_routine, (QWORD)MouseClassServiceCallbackHook, mouclass, mouhid);
}
return status;
}
extern "C" __declspec(dllimport) PCSTR PsGetProcessImageFileName(QWORD process);
void __fastcall hooks::exception::KdTrapHook(void)
{
//
// disable upcoming DPC call
//
*(BYTE*)(exception::PoHiderInProgress) = 1;
QWORD KeBugCheckExPtr = (QWORD)KeBugCheckEx;
KeBugCheckExPtr = KeBugCheckExPtr + 0x23;
KeBugCheckExPtr = KeBugCheckExPtr + 0x03;
DWORD ctx_offset = *(DWORD*)KeBugCheckExPtr;
struct _CONTEXT* current_context = *(struct _CONTEXT**)(__readgsqword(0x20) + ctx_offset);
//
// check if exception was caught
//
if (current_context == 0 || current_context->Rip == 0)
{
return oKdTrap();
}
//
// skipping usermode exceptions
//
/*
if (current_context->Rip <= 0x7FFFFFFFFFFF)
{
return oKdTrap();
}
*/
/*
QWORD thread = __readgsqword(0x188);
QWORD process = *(QWORD*)(thread + 0xB8);
QWORD thread_process = *(QWORD*)(thread + 0x98 + 0x20);
//
// exception was caught
//
LOG("[%s:%s][%llX][%llX] exception was caught\n",
PsGetProcessImageFileName(process),
PsGetProcessImageFileName(thread_process),
__readcr3(),
current_context->Rip
);*/
return oKdTrap();
}
BOOLEAN is_unlinked_thread(QWORD process, QWORD thread)
{
PLIST_ENTRY list_head = (PLIST_ENTRY)((QWORD)process + 0x30);
PLIST_ENTRY list_entry = list_head;
QWORD entry = (QWORD)((char*)list_entry - 0x2f8);
if (entry == thread)
{
return 0;
}
while ((list_entry = list_entry->Flink) != 0 && list_entry != list_head)
{
entry = (QWORD)((char*)list_entry - 0x2f8);
if (entry == thread)
{
return 0;
}
}
return 1;
}
BOOLEAN unlink_thread_detection(QWORD thread)
{
if (thread == 0)
return 0;
QWORD host_process = *(QWORD*)(thread + 0x220);
QWORD lookup_thread;
if (NT_SUCCESS(PsLookupThreadByThreadId(
(HANDLE)PsGetThreadId((PETHREAD)thread),
(PETHREAD*)&lookup_thread
)))
{
if (lookup_thread == thread)
{
return 0;
}
}
return is_unlinked_thread(host_process, thread);
}
UCHAR __fastcall hooks::swap_ctx::HalClearLastBranchRecordStackHook(void)
{
QWORD current_thread = __readgsqword(0x188);
QWORD cr3 = __readcr3();
if (unlink_thread_detection(current_thread))
{
LOG("Unlinked thread found [%lld] [%llX] [%llX]\n", (QWORD)PsGetCurrentThreadId(), current_thread, cr3);
}
return swap_ctx::oHalClearLastBranchRecordStack();
}
typedef struct _KLDR_DATA_TABLE_ENTRY {
LIST_ENTRY InLoadOrderLinks;
VOID* ExceptionTable;
UINT32 ExceptionTableSize;
VOID* GpValue;
VOID* NonPagedDebugInfo;
VOID* ImageBase;
VOID* EntryPoint;
UINT32 SizeOfImage;
UNICODE_STRING FullImageName;
UNICODE_STRING BaseImageName;
} LDR_DATA_TABLE_ENTRY, * PLDR_DATA_TABLE_ENTRY;
extern "C" __declspec(dllimport) LIST_ENTRY * PsLoadedModuleList;
MODULE_INFO get_module_info(PWCH module_name)
{
PLDR_DATA_TABLE_ENTRY module_entry = CONTAINING_RECORD(PsLoadedModuleList, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
if (module_name == 0)
{
return { (QWORD)module_entry->ImageBase, module_entry->SizeOfImage };
}
for (PLIST_ENTRY list_entry = PsLoadedModuleList->Flink; list_entry != PsLoadedModuleList; list_entry = list_entry->Flink)
{
module_entry = CONTAINING_RECORD(list_entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
if (module_entry->ImageBase == 0)
continue;
if (module_entry->BaseImageName.Length == 0)
continue;
if (module_entry->BaseImageName.Buffer && !wcscmp(module_entry->BaseImageName.Buffer, module_name))
{
return { (QWORD)module_entry->ImageBase, module_entry->SizeOfImage };
}
}
return {};
}
extern "C" __declspec(dllimport) LIST_ENTRY * PsLoadedModuleList;
PCWSTR GetCallerModuleName(QWORD address, QWORD* offset)
{
PLDR_DATA_TABLE_ENTRY module_entry = CONTAINING_RECORD(PsLoadedModuleList, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
if (address >= (QWORD)module_entry->ImageBase && address <= (QWORD)((QWORD)module_entry->ImageBase + module_entry->SizeOfImage + 0x1000))
{
if (offset)
*offset = address - (QWORD)module_entry->ImageBase;
if (module_entry->BaseImageName.Length == 0)
return L"unknown";
return (PWCH)module_entry->BaseImageName.Buffer;
}
for (PLIST_ENTRY pListEntry = PsLoadedModuleList->Flink; pListEntry != PsLoadedModuleList; pListEntry = pListEntry->Flink)
{
module_entry = CONTAINING_RECORD(pListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
if (module_entry->ImageBase == 0)
continue;
if (address >= (QWORD)module_entry->ImageBase && address <= (QWORD)((QWORD)module_entry->ImageBase + module_entry->SizeOfImage + 0x1000))
{
if (offset)
*offset = address - (QWORD)module_entry->ImageBase;
if (module_entry->BaseImageName.Length == 0)
return L"unknown";
return (PWCH)module_entry->BaseImageName.Buffer;
}
}
return L"unknown";
}
extern "C" NTSYSCALLAPI
NTSTATUS
ObReferenceObjectByName(
__in PUNICODE_STRING ObjectName,
__in ULONG Attributes,
__in_opt PACCESS_STATE AccessState,
__in_opt ACCESS_MASK DesiredAccess,
__in POBJECT_TYPE ObjectType,
__in KPROCESSOR_MODE AccessMode,
__inout_opt PVOID ParseContext,
__out PVOID * Object
);
extern "C" NTSYSCALLAPI POBJECT_TYPE * IoDriverObjectType;
QWORD get_mouse_callback_address(PDRIVER_OBJECT* mouclass, PDRIVER_OBJECT* mouhid)
{
//
// https://github.com/nbqofficial/norsefire
//
UNICODE_STRING class_string;
RtlInitUnicodeString(&class_string, L"\\Driver\\MouClass");
PDRIVER_OBJECT class_driver_object = 0;
NTSTATUS status = ObReferenceObjectByName(&class_string, OBJ_CASE_INSENSITIVE, 0, 0, *IoDriverObjectType, KernelMode, 0, (PVOID*)&class_driver_object);
if (!NT_SUCCESS(status)) {
return 0;
}
if (mouclass)
*mouclass = class_driver_object;
UNICODE_STRING hid_string;
RtlInitUnicodeString(&hid_string, L"\\Driver\\MouHID");
PDRIVER_OBJECT hid_driver_object = 0;
status = ObReferenceObjectByName(&hid_string, OBJ_CASE_INSENSITIVE, 0, 0, *IoDriverObjectType, KernelMode, 0, (PVOID*)&hid_driver_object);
if (!NT_SUCCESS(status))
{
ObfDereferenceObject(class_driver_object);
return 0;
}
if (mouhid)
*mouhid = hid_driver_object;
QWORD result = 0;
PDEVICE_OBJECT hid_device_object = hid_driver_object->DeviceObject;
while (hid_device_object)
{
PDEVICE_OBJECT class_device_object = class_driver_object->DeviceObject;
while (class_device_object)
{
PULONG_PTR device_extension = (PULONG_PTR)hid_device_object->DeviceExtension;
ULONG_PTR device_ext_size = ((ULONG_PTR)hid_device_object->DeviceObjectExtension - (ULONG_PTR)hid_device_object->DeviceExtension) / 4;
for (ULONG_PTR i = 0; i < device_ext_size; i++)
{
if (device_extension[i] == (ULONG_PTR)class_device_object && device_extension[i + 1] > (ULONG_PTR)class_driver_object)
{
result = (QWORD)(device_extension[i + 1]);
goto E0;
}
}
class_device_object = class_device_object->NextDevice;
}
hid_device_object = hid_device_object->AttachedDevice;
}
E0:
ObfDereferenceObject(class_driver_object);
ObfDereferenceObject(hid_driver_object);
return result;
}
void update_mouse_devices(QWORD current_callback, QWORD callback, PDRIVER_OBJECT mouclass, PDRIVER_OBJECT mouhid)
{
PDEVICE_OBJECT hid_device_object = mouhid->DeviceObject;
while (hid_device_object)
{
PDEVICE_OBJECT class_device_object = mouclass->DeviceObject;
while (class_device_object)
{
PULONG_PTR device_extension = (PULONG_PTR)hid_device_object->DeviceExtension;
ULONG_PTR device_ext_size =
((ULONG_PTR)hid_device_object->DeviceObjectExtension - (ULONG_PTR)hid_device_object->DeviceExtension) / 4;
for (ULONG_PTR i = 0; i < device_ext_size; i++)
{
if (device_extension[i] == current_callback)
{
device_extension[i] = callback;
}
}
class_device_object = class_device_object->NextDevice;
}
hid_device_object = hid_device_object->AttachedDevice;
}
}
extern "C" NTSYSCALLAPI NTSTATUS HalPrivateDispatchTable(void);
extern "C" NTSYSCALLAPI NTSTATUS HalEnumerateEnvironmentVariablesEx(void);
QWORD GetExportByName(QWORD base, const char* export_name)
{
QWORD a0;
DWORD a1[4];
a0 = base + *(unsigned short*)(base + 0x3C);
if (a0 == base)
{
return 0;
}
WORD machine = *(WORD*)(a0 + 0x4);
a0 = machine == 0x8664 ? base + *(DWORD*)(a0 + 0x88) : base + *(DWORD*)(a0 + 0x78);
if (a0 == base)
{
return 0;
}
a1[0] = *(DWORD*)(a0 + 0x18);
a1[1] = *(DWORD*)(a0 + 0x1C);
a1[2] = *(DWORD*)(a0 + 0x20);
a1[3] = *(DWORD*)(a0 + 0x24);
while (a1[0]--) {
a0 = base + *(DWORD*)(base + a1[2] + (a1[0] * 4));
if (strcmp((const char*)a0, export_name) == 0)
{
return (base + *(DWORD*)(base + a1[1] + (*(unsigned short*)(base + a1[3] + (a1[0] * 2)) * 4)));
}
}
return 0;
}
QWORD GetAddressByRef(QWORD ref, BOOLEAN inc)
{
QWORD val = ref;
while (1)
{
if (*(unsigned char*)val == 0xE8)
{
if ((val + 5) + *(int*)(val + 1) == ref)
break;
}
if (inc) val++; else val--;
}
while (*(unsigned char*)val != 0xCC)
val--;
return val + 1;
}
BOOLEAN hooks::install(void)
{
//
// syscall hook
//
if (!NT_SUCCESS(ApplyTraceSettings(TRACE_OPERATION::TRACE_SYSCALL)))
{
if (!NT_SUCCESS(ApplyTraceSettings(TRACE_OPERATION::TRACE_START)))
{
return 0;
}
ApplyTraceSettings(TRACE_OPERATION::TRACE_SYSCALL);
}
QWORD temp = (QWORD)KeQueryPerformanceCounter + 0x05;
while (*(WORD*)temp != 0x8948) temp++;
temp = temp + 0x08;
temp = (temp + 7) + *(int*)(temp + 3);
temp = *(QWORD*)temp;
*(QWORD*)&syscall::oKeQueryPerformanceCounter = *(QWORD*)(temp + 0x70);
*(QWORD*)(temp + 0x70) = (QWORD)syscall::KeQueryPerformanceCounterHook;
syscall::SystemCallEntryPage = (QWORD)ImgGetSyscallEntry((PVOID)globals::ntoskrnl.base);
//
// mouse hook
//
input::mouclass_routine = get_mouse_callback_address(&input::mouclass, &input::mouhid);
if (input::mouclass_routine == 0)
return 0;
update_mouse_devices(input::mouclass_routine, (QWORD)input::MouseClassServiceCallbackHook, input::mouclass, input::mouhid);
input::oMouseClassRead = input::mouclass->MajorFunction[IRP_MJ_READ];
input::mouclass->MajorFunction[IRP_MJ_READ] = input::MouseClassReadHook;
input::oMouseAddDevice = input::mouclass->DriverExtension->AddDevice;
input::mouclass->DriverExtension->AddDevice = input::MouseAddDeviceHook;
//
// global exception hook
//
exception::KdpDebugRoutineSelect = FindPattern(globals::ntoskrnl.base, (BYTE*)"\x83\x3D\x00\x00\x00\x00\x00\x8A\x44", (BYTE*)"xx????xxx");
if (exception::KdpDebugRoutineSelect == 0)
{
E0:
update_mouse_devices((QWORD)input::MouseClassServiceCallbackHook, input::mouclass_routine, input::mouclass, input::mouhid);
input::mouclass->MajorFunction[IRP_MJ_READ] = input::oMouseClassRead;
input::mouclass->DriverExtension->AddDevice = input::oMouseAddDevice;
return 0;
}
exception::PoHiderInProgress = FindPattern(globals::ntoskrnl.base, (BYTE*)"\xC6\x05\x00\x00\x00\x00\x01\x33\xC9\xE8", (BYTE*)"xx????xxxx");
if (exception::PoHiderInProgress == 0)
{
goto E0;
}
exception::KdpDebugRoutineSelect = (exception::KdpDebugRoutineSelect + 7) + *(INT32*)(exception::KdpDebugRoutineSelect + 2);
exception::PoHiderInProgress = (exception::PoHiderInProgress + 7) + *(INT32*)(exception::PoHiderInProgress + 2);
*(DWORD*)(exception::KdpDebugRoutineSelect) = 1;
//
// HalPrivateDispatchTable + 0x328 = xHalTimerWatchdogStop/xHalTimerWatchdogStart
//
*(QWORD*)&exception::oKdTrap = *(QWORD*)((QWORD)HalPrivateDispatchTable + 0x328);
*(QWORD*)((QWORD)HalPrivateDispatchTable + 0x328) = (QWORD)exception::KdTrapHook;
//
// HalPrivateDispatchTable + 0x400 = HalClearLastBranchRecordStack
//
*(QWORD*)&swap_ctx::oHalClearLastBranchRecordStack = *(QWORD*)((QWORD)HalPrivateDispatchTable + 0x400);
*(QWORD*)((QWORD)HalPrivateDispatchTable + 0x400) = (QWORD)swap_ctx::HalClearLastBranchRecordStackHook;
//
// set KiCpuTracingFlags 2
//
QWORD KiCpuTracingFlags = (QWORD)KeBugCheckEx;
while (*(unsigned short*)KiCpuTracingFlags != 0xE800) KiCpuTracingFlags++; KiCpuTracingFlags += 2;
while (*(unsigned short*)KiCpuTracingFlags != 0xE800) KiCpuTracingFlags++; KiCpuTracingFlags++;
KiCpuTracingFlags = (KiCpuTracingFlags + 5) + *(int*)(KiCpuTracingFlags + 1);
while (*(unsigned short*)KiCpuTracingFlags != 0x05F7) KiCpuTracingFlags++;
KiCpuTracingFlags = (KiCpuTracingFlags + 10) + *(int*)(KiCpuTracingFlags + 2);
*(BYTE*)(KiCpuTracingFlags) = 2;
QWORD HalEfiRuntimeServicesBlock = (QWORD)HalEnumerateEnvironmentVariablesEx + 0xC;
HalEfiRuntimeServicesBlock =
*(INT*)(HalEfiRuntimeServicesBlock + 1) + HalEfiRuntimeServicesBlock + 5;
HalEfiRuntimeServicesBlock = HalEfiRuntimeServicesBlock + 0x69;
HalEfiRuntimeServicesBlock =
*(INT*)(HalEfiRuntimeServicesBlock + 3) + HalEfiRuntimeServicesBlock + 7;
HalEfiRuntimeServicesBlock = *(QWORD*)(HalEfiRuntimeServicesBlock);
*(QWORD*)&efi::oGetVariable = *(QWORD*)(HalEfiRuntimeServicesBlock + 0x18);
*(QWORD*)&efi::oSetVariable = *(QWORD*)(HalEfiRuntimeServicesBlock + 0x28);
efi::NtSetSystemEnvironmentValueEx =
GetAddressByRef((QWORD)GetExportByName(globals::ntoskrnl.base, "ExSetFirmwareEnvironmentVariable"), 1);
efi::NtQuerySystemEnvironmentValueEx =
GetAddressByRef((QWORD)GetExportByName(globals::ntoskrnl.base, "ExGetFirmwareEnvironmentVariable"), 0);
return 1;
}
void hooks::uninstall(void)
{
//
// unhook syscalls
//
ApplyTraceSettings(TRACE_OPERATION::TRACE_END);
QWORD temp = (QWORD)KeQueryPerformanceCounter + 0x05;
while (*(WORD*)temp != 0x8948) temp++;
temp = temp + 0x08;
temp = (temp + 7) + *(int*)(temp + 3);
temp = *(QWORD*)temp;
*(QWORD*)(temp + 0x70) = (QWORD)syscall::oKeQueryPerformanceCounter;
//
// unhook mouse
//
update_mouse_devices((QWORD)input::MouseClassServiceCallbackHook, input::mouclass_routine, input::mouclass, input::mouhid);
input::mouclass->MajorFunction[IRP_MJ_READ] = input::oMouseClassRead;
input::mouclass->DriverExtension->AddDevice = input::oMouseAddDevice;
//
// unhook exceptions
//
*(QWORD*)((QWORD)HalPrivateDispatchTable + 0x328) = (QWORD)exception::oKdTrap;
*(DWORD*)(exception::KdpDebugRoutineSelect) = 0;
*(BYTE*)(exception::PoHiderInProgress) = 0;
//
// unhook SwapContext
//
*(QWORD*)((QWORD)HalPrivateDispatchTable + 0x400) = *(QWORD*)&swap_ctx::oHalClearLastBranchRecordStack;
//
// set KiCpuTracingFlags 0
//
QWORD KiCpuTracingFlags = (QWORD)KeBugCheckEx;
while (*(unsigned short*)KiCpuTracingFlags != 0xE800) KiCpuTracingFlags++; KiCpuTracingFlags += 2;
while (*(unsigned short*)KiCpuTracingFlags != 0xE800) KiCpuTracingFlags++; KiCpuTracingFlags++;
KiCpuTracingFlags = (KiCpuTracingFlags + 5) + *(int*)(KiCpuTracingFlags + 1);
while (*(unsigned short*)KiCpuTracingFlags != 0x05F7) KiCpuTracingFlags++;
KiCpuTracingFlags = (KiCpuTracingFlags + 10) + *(int*)(KiCpuTracingFlags + 2);
*(BYTE*)(KiCpuTracingFlags) = 0;
}
static int CheckMask(unsigned char* base, unsigned char* pattern, unsigned char* mask)
{
for (; *mask; ++base, ++pattern, ++mask)
if (*mask == 'x' && *base != *pattern)
return 0;
return 1;
}
void* FindPatternEx(unsigned char* base, QWORD size, unsigned char* pattern, unsigned char* mask)
{
size -= strlen((const char*)mask);
for (QWORD i = 0; i <= size; ++i) {
void* addr = &base[i];
if (CheckMask((unsigned char*)addr, pattern, mask))
return addr;
}
return 0;
}
QWORD FindPattern(QWORD base, unsigned char* pattern, unsigned char* mask)
{
if (base == 0)
{
return 0;
}
QWORD nt_header = (QWORD) * (DWORD*)(base + 0x03C) + base;
if (nt_header == base)
{
return 0;
}
WORD machine = *(WORD*)(nt_header + 0x4);
QWORD section_header = machine == 0x8664 ?
nt_header + 0x0108 :
nt_header + 0x00F8;
for (WORD i = 0; i < *(WORD*)(nt_header + 0x06); i++) {
QWORD section = section_header + ((QWORD)i * 40);
DWORD section_characteristics = *(DWORD*)(section + 0x24);
if (section_characteristics & 0x00000020 && !(section_characteristics & 0x02000000))
{
QWORD virtual_address = base + (QWORD) * (DWORD*)(section + 0x0C);
DWORD virtual_size = *(DWORD*)(section + 0x08);
QWORD addr = (QWORD)FindPatternEx((unsigned char*)virtual_address, virtual_size, pattern, mask);
if (addr)
{
return addr;
}
}
}
return 0;
}
EXTERN_C
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTraceControl(
_In_ ULONG FunctionCode,
_In_reads_bytes_opt_(InBufferLen) PVOID InBuffer,
_In_ ULONG InBufferLen,
_Out_writes_bytes_opt_(OutBufferLen) PVOID OutBuffer,
_In_ ULONG OutBufferLen,
_Out_ PULONG ReturnLength
);
#define EVENT_TRACE_BUFFERING_MODE 0x00000400 // Buffering mode only
#define EtwpStartTrace 1
#define EtwpStopTrace 2
#define EtwpQueryTrace 3
#define EtwpUpdateTrace 4
#define EtwpFlushTrace 5
#define EVENT_TRACE_FLAG_SYSTEMCALL 0x00000080 // system calls
#define WNODE_FLAG_TRACED_GUID 0x00020000 // denotes a trace
#pragma warning (disable: 4201)