-
Notifications
You must be signed in to change notification settings - Fork 444
/
Copy pathHookHelper.cpp
954 lines (811 loc) · 33.3 KB
/
HookHelper.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
#include "HookHelper.h"
#include <ntdll/ntdll.h>
#include "HookedFunctions.h"
#include "HookMain.h"
const WCHAR * BadProcessnameList[] =
{
L"ollydbg.exe",
L"ida.exe",
L"ida64.exe",
L"idag.exe",
L"idag64.exe",
L"idaw.exe",
L"idaw64.exe",
L"idaq.exe",
L"idaq64.exe",
L"idau.exe",
L"idau64.exe",
L"scylla.exe",
L"scylla_x64.exe",
L"scylla_x86.exe",
L"protection_id.exe",
L"x64dbg.exe",
L"x32dbg.exe",
L"windbg.exe",
L"reshacker.exe",
L"ImportREC.exe",
L"IMMUNITYDEBUGGER.EXE",
L"devenv.exe",
L"Procmon.exe",
L"Procmon64.exe",
L"APIMonitor.exe",
L"apimonitor-x64.exe",
L"apimonitor-x86.exe",
L"cheatengine-" // cheatengine-i386.exe, cheatengine-x86_64.exe, cheatengine-x86_64-SSE4-AVX2.exe, ...
};
const WCHAR * BadWindowTextList[] =
{
L"OLLYDBG",
L"ida",
L"disassembly",
L"scylla",
L"Debug",
L"[CPU",
L"Immunity",
L"WinDbg",
L"x32dbg",
L"x64dbg",
L"WinDbg",
L"Import reconstructor",
L"Process Monitor - Sysinternals: www.sysinternals.com",
L"API Monitor",
L"Monitored Processes",
L"Cheat Engine"
};
const WCHAR * BadWindowClassList[] =
{
L"OLLYDBG",
L"Zeta Debugger",
L"Rock Debugger",
L"ObsidianGUI",
L"ID", // Immunity Debugger
L"WinDbgFrameClass", // classic WinDBG
L"DbgX.Shell", // new WinDBG
L"idawindow",
L"tnavbox",
L"idaview",
L"tgrzoom",
L"PROCMON_WINDOW_CLASS", // Process Monitor
L"APIMonitor By Rohitab",
L"99929D61-1338-48B1-9433-D42A1D94F0D2" // API Monitor
};
extern "C" void InstrumentationCallbackAsm();
extern HOOK_DLL_DATA HookDllData;
extern SAVE_DEBUG_REGISTERS ArrayDebugRegister[100];
static USHORT DebugObjectTypeIndex = 0;
static USHORT ProcessTypeIndex = 0;
static USHORT ThreadTypeIndex = 0;
bool IsProcessNameBad(PUNICODE_STRING processName)
{
if (processName == nullptr || processName->Length == 0 || processName->Buffer == nullptr)
return false;
UNICODE_STRING badProcessName;
for (int i = 0; i < _countof(BadProcessnameList); i++)
{
RtlInitUnicodeString(&badProcessName, const_cast<PWSTR>(BadProcessnameList[i]));
if (RtlEqualUnicodeString(processName, &badProcessName, TRUE))
return true;
}
return false;
}
bool IsWindowClassNameBad(PUNICODE_STRING className)
{
if (className == nullptr || className->Length == 0 || className->Buffer == nullptr)
return false;
UNICODE_STRING badWindowClassName;
for (int i = 0; i < _countof(BadWindowClassList); i++)
{
RtlInitUnicodeString(&badWindowClassName, const_cast<PWSTR>(BadWindowClassList[i]));
if (RtlUnicodeStringContains(className, &badWindowClassName, TRUE))
return true;
}
return false;
}
bool IsWindowNameBad(PUNICODE_STRING windowName)
{
if (windowName == nullptr || windowName->Length == 0 || windowName->Buffer == nullptr)
return false;
UNICODE_STRING badWindowName;
for (int i = 0; i < _countof(BadWindowTextList); i++)
{
RtlInitUnicodeString(&badWindowName, const_cast<PWSTR>(BadWindowTextList[i]));
if (RtlUnicodeStringContains(windowName, &badWindowName, TRUE))
return true;
}
return false;
}
bool IsWindowBad(HWND hWnd)
{
if (HookDllData.EnableProtectProcessId)
{
const ULONG Pid = HookDllData.dNtUserQueryWindow != nullptr
? HandleToULong(HookDllData.dNtUserQueryWindow(hWnd, WindowProcess))
: HandleToULong(HookDllData.NtUserQueryWindow(hWnd, WindowProcess));
if (Pid == HookDllData.dwProtectedProcessId)
return true;
}
DECLARE_UNICODE_STRING_SIZE(ClassName, 256);
DECLARE_UNICODE_STRING_SIZE(WindowText, 512);
ClassName.Length = (USHORT)HookDllData.NtUserGetClassName(hWnd, FALSE, &ClassName) * sizeof(WCHAR);
ClassName.Buffer[ClassName.Length / sizeof(WCHAR)] = UNICODE_NULL;
if (IsWindowClassNameBad(&ClassName))
return true;
WindowText.Length = (USHORT)HookDllData.NtUserInternalGetWindowText(hWnd, WindowText.Buffer, (INT)(WindowText.MaximumLength / sizeof(WCHAR))) * sizeof(WCHAR);
WindowText.Buffer[WindowText.Length / sizeof(WCHAR)] = UNICODE_NULL;
return IsWindowNameBad(&WindowText);
}
static void GetBadObjectTypes()
{
// If NtQSI is not hooked, this function is N/A
if (HookDllData.dNtQuerySystemInformation == nullptr)
return;
// Only get the object type indices once
if (DebugObjectTypeIndex != 0 || ProcessTypeIndex != 0 || ThreadTypeIndex != 0)
return;
// Create handles to three bad object types: an empty debug object and our own process and thread
HANDLE DebugObjectHandle = nullptr, ProcessHandle = nullptr, ThreadHandle = nullptr;
OBJECT_ATTRIBUTES ObjectAttributes = { sizeof(OBJECT_ATTRIBUTES) };
CLIENT_ID ClientId = NtCurrentTeb()->ClientId;
NtCreateDebugObject(&DebugObjectHandle, DEBUG_ALL_ACCESS, &ObjectAttributes, 0);
NtOpenProcess(&ProcessHandle, PROCESS_ALL_ACCESS, &ObjectAttributes, &ClientId);
NtOpenThread(&ThreadHandle, THREAD_ALL_ACCESS, &ObjectAttributes, &ClientId);
SYSTEM_HANDLE_INFORMATION_EX Dummy; // Prevent getting STATUS_INFO_LENGTH_MISMATCH twice
PSYSTEM_HANDLE_INFORMATION_EX HandleInfo = &Dummy;
ULONG Size;
NTSTATUS Status;
if ((Status = HookDllData.dNtQuerySystemInformation(SystemExtendedHandleInformation,
HandleInfo,
sizeof(Dummy),
&Size)) != STATUS_INFO_LENGTH_MISMATCH)
goto exit;
HandleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)RtlAllocateHeap(RtlProcessHeap(), 0, 2 * Size);
Status = HookDllData.dNtQuerySystemInformation(SystemExtendedHandleInformation,
HandleInfo,
2 * Size,
nullptr);
if (!NT_SUCCESS(Status))
goto exit;
// Enumerate all handles
for (ULONG i = 0; i < HandleInfo->NumberOfHandles; ++i)
{
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Entry = HandleInfo->Handles[i];
if (Entry.UniqueProcessId != (ULONG_PTR)NtCurrentTeb()->ClientId.UniqueProcess)
continue; // Not our process
if (Entry.HandleValue == (ULONG_PTR)DebugObjectHandle)
DebugObjectTypeIndex = Entry.ObjectTypeIndex;
else if (Entry.HandleValue == (ULONG_PTR)ProcessHandle)
ProcessTypeIndex = Entry.ObjectTypeIndex;
else if (Entry.HandleValue == (ULONG_PTR)ThreadHandle)
ThreadTypeIndex = Entry.ObjectTypeIndex;
}
exit:
if (DebugObjectHandle != nullptr)
NtClose(DebugObjectHandle);
if (ProcessHandle != nullptr)
NtClose(ProcessHandle);
if (ThreadHandle != nullptr)
NtClose(ThreadHandle);
if (HandleInfo != &Dummy)
RtlFreeHeap(RtlProcessHeap(), 0, HandleInfo);
}
bool IsObjectTypeBad(USHORT objectTypeIndex)
{
GetBadObjectTypes();
return objectTypeIndex == DebugObjectTypeIndex ||
objectTypeIndex == ProcessTypeIndex ||
objectTypeIndex == ThreadTypeIndex;
}
static LUID ConvertLongToLuid(LONG value)
{
LUID luid;
LARGE_INTEGER largeInt;
largeInt.QuadPart = value;
luid.LowPart = largeInt.LowPart;
luid.HighPart = largeInt.HighPart;
return luid;
}
bool HasDebugPrivileges(HANDLE hProcess)
{
HANDLE hToken;
NTSTATUS status = NtOpenProcessToken(hProcess, TOKEN_QUERY, &hToken);
if (!NT_SUCCESS(status))
return false;
const LUID SeDebugPrivilege = ConvertLongToLuid(SE_DEBUG_PRIVILEGE);
PRIVILEGE_SET privilegeSet;
privilegeSet.PrivilegeCount = 1;
privilegeSet.Control = PRIVILEGE_SET_ALL_NECESSARY;
privilegeSet.Privilege[0].Luid = SeDebugPrivilege;
privilegeSet.Privilege[0].Attributes = 0;
BOOLEAN hasDebugPrivileges = FALSE;
NtPrivilegeCheck(hToken, &privilegeSet, &hasDebugPrivileges);
NtClose(hToken);
return hasDebugPrivileges == TRUE;
}
bool IsWow64Process(HANDLE ProcessHandle)
{
PPEB WoW64Peb = nullptr;
const NTSTATUS Status = NtQueryInformationProcess(ProcessHandle,
ProcessWow64Information,
&WoW64Peb,
sizeof(PPEB),
nullptr);
return NT_SUCCESS(Status) && WoW64Peb != nullptr;
}
NTSTATUS
InstallInstrumentationCallbackHook(
_In_ HANDLE ProcessHandle,
_In_ BOOLEAN Remove
)
{
const PVOID Callback = Remove ? nullptr : (PVOID)InstrumentationCallbackAsm;
NTSTATUS Status = STATUS_NOT_SUPPORTED;
if (RtlNtMajorVersion() > 6)
{
// Windows 10
PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION InstrumentationCallbackInfo;
#ifdef _WIN64
InstrumentationCallbackInfo.Version = 0;
#else
// Native x86 instrumentation callbacks don't work correctly
if (!IsWow64Process(ProcessHandle))
{
//InstrumentationCallbackInfo.Version = 1; // Value to use if they did
return Status;
}
// WOW64: set the callback pointer in the version field
InstrumentationCallbackInfo.Version = (ULONG_PTR)Callback;
#endif
InstrumentationCallbackInfo.Reserved = 0;
InstrumentationCallbackInfo.Callback = Callback;
Status = HookDllData.dNtSetInformationProcess != nullptr
? HookDllData.dNtSetInformationProcess(ProcessHandle,
ProcessInstrumentationCallback,
&InstrumentationCallbackInfo,
sizeof(InstrumentationCallbackInfo))
: NtSetInformationProcess(ProcessHandle,
ProcessInstrumentationCallback,
&InstrumentationCallbackInfo,
sizeof(InstrumentationCallbackInfo));
}
#ifdef _WIN64 // Windows 7-8.1 do not support x86/WOW64 instrumentation callbacks
else if (RtlNtMajorVersion() == 6 && RtlNtMinorVersion() >= 1)
{
// Windows 7-8.1 require SE_DEBUG for this to work, even on the current process
BOOLEAN SeDebugWasEnabled;
Status = RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &SeDebugWasEnabled);
if (!NT_SUCCESS(Status))
return Status;
Status = HookDllData.dNtSetInformationProcess != nullptr
? HookDllData.dNtSetInformationProcess(ProcessHandle,
ProcessInstrumentationCallback,
(PVOID)&Callback,
sizeof(Callback))
: NtSetInformationProcess(ProcessHandle,
ProcessInstrumentationCallback,
(PVOID)&Callback,
sizeof(Callback));
RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, SeDebugWasEnabled, FALSE, &SeDebugWasEnabled);
}
#endif
return Status;
}
void * GetPEBRemote(HANDLE hProcess)
{
PROCESS_BASIC_INFORMATION pbi;
if (HookDllData.dNtQueryInformationProcess)
{
if (HookDllData.dNtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), 0) >= 0)
{
return pbi.PebBaseAddress;
}
}
else
{
//maybe not hooked
if (NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), 0) >= 0)
{
return pbi.PebBaseAddress;
}
}
return 0;
}
DWORD GetProcessIdByProcessHandle(HANDLE hProcess)
{
PROCESS_BASIC_INFORMATION pbi;
if (HookDllData.dNtQueryInformationProcess)
{
if (HookDllData.dNtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), 0) >= 0)
{
return HandleToULong(pbi.UniqueProcessId);
}
}
else
{
//maybe not hooked
if (NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), 0) >= 0)
{
return HandleToULong(pbi.UniqueProcessId);
}
}
return 0;
}
DWORD GetProcessIdByThreadHandle(HANDLE hThread)
{
THREAD_BASIC_INFORMATION tbi;
if (NT_SUCCESS(NtQueryInformationThread(hThread, ThreadBasicInformation, &tbi, sizeof(THREAD_BASIC_INFORMATION), 0)))
{
return HandleToULong(tbi.ClientId.UniqueProcess);
}
return 0;
}
void TerminateProcessByProcessId(DWORD dwProcess)
{
if (dwProcess == 0)
return;
OBJECT_ATTRIBUTES attributes = { sizeof(OBJECT_ATTRIBUTES) };
CLIENT_ID clientId = { ULongToHandle(dwProcess) };
HANDLE hProcess;
NTSTATUS status = NtOpenProcess(&hProcess, PROCESS_TERMINATE, &attributes, &clientId);
if (NT_SUCCESS(status))
{
NtTerminateProcess(hProcess, STATUS_SUCCESS);
NtClose(hProcess);
}
}
static DWORD dwExplorerPid = 0;
DWORD GetExplorerProcessId()
{
if (dwExplorerPid == 0)
{
UNICODE_STRING explorerName = RTL_CONSTANT_STRING(L"explorer.exe");
dwExplorerPid = GetProcessIdByName(&explorerName);
}
return dwExplorerPid;
}
DWORD GetProcessIdByName(PUNICODE_STRING processName)
{
ULONG size;
if (NtQuerySystemInformation(SystemProcessInformation, nullptr, 0, &size) != STATUS_INFO_LENGTH_MISMATCH)
return 0;
const PSYSTEM_PROCESS_INFORMATION systemProcessInfo =
static_cast<PSYSTEM_PROCESS_INFORMATION>(RtlAllocateHeap(RtlProcessHeap(), 0, 2 * size));
NTSTATUS status;
if (HookDllData.dNtQuerySystemInformation != nullptr)
{
status = HookDllData.dNtQuerySystemInformation(SystemProcessInformation,
systemProcessInfo,
2 * size,
nullptr);
}
else
{
status = NtQuerySystemInformation(SystemProcessInformation,
systemProcessInfo,
2 * size,
nullptr);
}
if (!NT_SUCCESS(status))
return 0;
DWORD pid = 0;
PSYSTEM_PROCESS_INFORMATION process = systemProcessInfo;
while (true)
{
if (RtlEqualUnicodeString(&process->ImageName, processName, TRUE))
{
pid = HandleToULong(process->UniqueProcessId);
break;
}
if (process->NextEntryOffset == 0)
break;
process = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)process + process->NextEntryOffset);
}
RtlFreeHeap(RtlProcessHeap(), 0, systemProcessInfo);
return pid;
}
bool RtlUnicodeStringContains(PUNICODE_STRING Str, PUNICODE_STRING SubStr, BOOLEAN CaseInsensitive)
{
if (Str == nullptr || SubStr == nullptr || Str->Length < SubStr->Length)
return false;
const USHORT numCharsDiff = (Str->Length - SubStr->Length) / sizeof(WCHAR);
UNICODE_STRING slice = *Str;
slice.Length = SubStr->Length;
for (USHORT i = 0; i <= numCharsDiff; ++i, ++slice.Buffer, slice.MaximumLength -= sizeof(WCHAR))
{
if (RtlEqualUnicodeString(&slice, SubStr, CaseInsensitive))
return true;
}
return false;
}
void ThreadDebugContextRemoveEntry(const int index)
{
ArrayDebugRegister[index].dwThreadId = 0;
}
void ThreadDebugContextSaveContext(const int index, const PCONTEXT ThreadContext)
{
ArrayDebugRegister[index].dwThreadId = HandleToULong(NtCurrentTeb()->ClientId.UniqueThread);
ArrayDebugRegister[index].Dr0 = ThreadContext->Dr0;
ArrayDebugRegister[index].Dr1 = ThreadContext->Dr1;
ArrayDebugRegister[index].Dr2 = ThreadContext->Dr2;
ArrayDebugRegister[index].Dr3 = ThreadContext->Dr3;
ArrayDebugRegister[index].Dr6 = ThreadContext->Dr6;
ArrayDebugRegister[index].Dr7 = ThreadContext->Dr7;
}
int ThreadDebugContextFindExistingSlotIndex()
{
for (int i = 0; i < _countof(ArrayDebugRegister); i++)
{
if (ArrayDebugRegister[i].dwThreadId != 0)
{
if (ArrayDebugRegister[i].dwThreadId == HandleToULong(NtCurrentTeb()->ClientId.UniqueThread))
{
return i;
}
}
}
return -1;
}
int ThreadDebugContextFindFreeSlotIndex()
{
for (int i = 0; i < _countof(ArrayDebugRegister); i++)
{
if (ArrayDebugRegister[i].dwThreadId == 0)
{
return i;
}
}
return -1;
}
// GetSystemTime and GetLocalTime are reimplemented here because the KernelBase functions use
// RIP-relative addressing which breaks hooking. https://github.com/x64dbg/ScyllaHide/issues/31
void NTAPI RealGetSystemTime(PSYSTEMTIME lpSystemTime)
{
TIME_FIELDS TimeFields;
RtlTimeToTimeFields((PLARGE_INTEGER)& SharedUserData->SystemTime, &TimeFields);
lpSystemTime->wYear = TimeFields.Year;
lpSystemTime->wMonth = TimeFields.Month;
lpSystemTime->wDay = TimeFields.Day;
lpSystemTime->wHour = TimeFields.Hour;
lpSystemTime->wMinute = TimeFields.Minute;
lpSystemTime->wSecond = TimeFields.Second;
lpSystemTime->wMilliseconds = TimeFields.Milliseconds;
lpSystemTime->wDayOfWeek = TimeFields.Weekday;
}
void NTAPI RealGetLocalTime(LPSYSTEMTIME lpSystemTime)
{
TIME_FIELDS TimeFields;
LARGE_INTEGER SystemTime = *(PLARGE_INTEGER)& SharedUserData->SystemTime;
LARGE_INTEGER TimeZoneBias = *(PLARGE_INTEGER)& SharedUserData->TimeZoneBias;
SystemTime.QuadPart -= TimeZoneBias.QuadPart;
RtlTimeToTimeFields(&SystemTime, &TimeFields);
lpSystemTime->wYear = TimeFields.Year;
lpSystemTime->wMonth = TimeFields.Month;
lpSystemTime->wDay = TimeFields.Day;
lpSystemTime->wHour = TimeFields.Hour;
lpSystemTime->wMinute = TimeFields.Minute;
lpSystemTime->wSecond = TimeFields.Second;
lpSystemTime->wMilliseconds = TimeFields.Milliseconds;
lpSystemTime->wDayOfWeek = TimeFields.Weekday;
}
void IncreaseSystemTime(LPSYSTEMTIME lpTime)
{
lpTime->wMilliseconds++;
//The hour. The valid values for this member are 0 through 23.
//The minute. The valid values for this member are 0 through 59.
//The second. The valid values for this member are 0 through 59.
//The millisecond. The valid values for this member are 0 through 999.
if (lpTime->wMilliseconds > 999)
{
lpTime->wSecond++;
lpTime->wMilliseconds = 0;
if (lpTime->wSecond > 59)
{
lpTime->wMinute++;
lpTime->wSecond = 0;
if (lpTime->wMinute > 59)
{
lpTime->wHour++;
lpTime->wMinute = 0;
if (lpTime->wHour > 23)
{
lpTime->wDay++;
lpTime->wDayOfWeek++;
lpTime->wHour = 0;
}
}
}
}
}
BYTE memory[sizeof(IMAGE_NT_HEADERS) + 0x100] = {0};
void DumpMalware(DWORD dwProcessId)
{
OBJECT_ATTRIBUTES attributes = { sizeof(OBJECT_ATTRIBUTES) };
CLIENT_ID clientId = { ULongToHandle(dwProcessId) };
HANDLE hProcess;
NTSTATUS status = NtOpenProcess(&hProcess, PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, &attributes, &clientId);
if (!NT_SUCCESS(status))
return;
PPEB peb = (PPEB)GetPEBRemote(hProcess);
if (peb)
{
DWORD_PTR imagebase = 0;
NtReadVirtualMemory(hProcess, &peb->ImageBaseAddress, &imagebase, sizeof(DWORD_PTR), nullptr);
NtReadVirtualMemory(hProcess, (PVOID)imagebase, memory, sizeof(memory), nullptr);
PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)memory;
if (pDos->e_magic == IMAGE_DOS_SIGNATURE)
{
PIMAGE_NT_HEADERS pNt = (PIMAGE_NT_HEADERS)((DWORD_PTR)pDos + pDos->e_lfanew);
if (pNt->Signature == IMAGE_NT_SIGNATURE)
{
PVOID tempMem = nullptr;
SIZE_T size = pNt->OptionalHeader.SizeOfImage;
status = NtAllocateVirtualMemory(NtCurrentProcess, &tempMem, 0, &size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (NT_SUCCESS(status))
{
NtReadVirtualMemory(hProcess, (PVOID)imagebase, tempMem, pNt->OptionalHeader.SizeOfImage, nullptr);
WriteMalwareToDisk(tempMem, pNt->OptionalHeader.SizeOfImage, imagebase);
size = 0;
NtFreeVirtualMemory(NtCurrentProcess, &tempMem, &size, MEM_RELEASE);
}
}
}
}
NtClose(hProcess);
}
WCHAR MalwareFile[MAX_PATH] = {0};
const WCHAR MalwareFilename[] = L"Unpacked.exe";
bool WriteMalwareToDisk(LPCVOID buffer, DWORD bufferSize, DWORD_PTR imagebase)
{
if (MalwareFile[0] == 0)
{
PUNICODE_STRING imagePath = &NtCurrentPeb()->ProcessParameters->ImagePathName;
ULONG size = MIN(sizeof(MalwareFile) - 1, imagePath->Length);
RtlCopyMemory(MalwareFile, imagePath->Buffer, size);
MalwareFile[size / sizeof(WCHAR)] = L'\0';
for (int i = (int)(size / sizeof(WCHAR)) - 1; i >= 0; i--)
{
if (MalwareFile[i] == L'\\')
{
MalwareFile[i+1] = L'\0';
break;
}
}
wcscat(MalwareFile, MalwareFilename);
}
return WriteMemoryToFile(MalwareFile, buffer,bufferSize, imagebase);
}
bool WriteMemoryToFile(const WCHAR * filename, LPCVOID buffer, DWORD bufferSize, DWORD_PTR imagebase)
{
PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)buffer;
PIMAGE_NT_HEADERS pNt = (PIMAGE_NT_HEADERS)((DWORD_PTR)pDos + pDos->e_lfanew);
PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(pNt);
UNICODE_STRING NtPath;
if (!RtlDosPathNameToNtPathName_U(filename, &NtPath, nullptr, nullptr))
return false;
OBJECT_ATTRIBUTES objectAttributes;
IO_STATUS_BLOCK ioStatusBlock;
InitializeObjectAttributes(&objectAttributes, &NtPath, OBJ_CASE_INSENSITIVE, nullptr, nullptr);
HANDLE hFile;
NTSTATUS status = NtCreateFile(&hFile,
FILE_GENERIC_WRITE,
&objectAttributes,
&ioStatusBlock,
nullptr,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ,
FILE_OVERWRITE_IF,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
nullptr,
0);
if (!NT_SUCCESS(status))
return false;
status = NtWriteFile(hFile, nullptr, nullptr, nullptr, &ioStatusBlock, (PVOID)buffer,
pNt->OptionalHeader.SizeOfHeaders, nullptr, nullptr);
for (WORD i = 0; i < pNt->FileHeader.NumberOfSections; i++)
{
status = NtWriteFile(hFile, nullptr, nullptr, nullptr, &ioStatusBlock, (BYTE *)buffer + pSection->VirtualAddress,
pSection->SizeOfRawData, nullptr, nullptr);
pSection++;
}
NtClose(hFile);
return NT_SUCCESS(status);
}
#ifndef _WIN64 // Windows 7-8.1 do not support x86/WOW64 instrumentation callbacks
LONG CALLBACK VMPSysenterHandler(EXCEPTION_POINTERS* info)
{
int ExceptionCode = info->ExceptionRecord->ExceptionCode;
ULONG_PTR ExceptionInfo0 = info->ExceptionRecord->ExceptionInformation[0];
ULONG_PTR ExceptionInfo1 = info->ExceptionRecord->ExceptionInformation[1];
ULONG_PTR ExceptionAddr = (ULONG_PTR)info->ExceptionRecord->ExceptionAddress;
if (ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
{
if (ExceptionInfo0 == 0) // Read
if (ExceptionInfo1 == -1) // InAccessible Address
if (!IsBadReadPtr((void*)ExceptionAddr, 2))
if (*reinterpret_cast<USHORT*>(ExceptionAddr) == 0x340F) // sysenter
{
//x32bit syscall_number windows 10 22H2 19045.3324 ~
enum SYSCALLNAME : ULONG {
NTSETINFORMATIONPROCESS = 0x4F,
NTQUERYINFORMATIONPROCESS = 0xB9,
NTSETINFORMATIONTHREAD = 0x4D,
NTOPENFILE = 0xF4,
NTCREATESECTION = 0x163,
NTMAPVIEWOFSECTION = 0x101,
NTUNMAPVIEWOFSECTION = 0x14,
NTCLOSE = 0x18E,
NTPROTECTVIRTUALMEMORY = 0xCE,
NTQUERYVIRTUALMEMORY = 0x97,
NTQUERYSYSTEMINFORMATION = 0x9D
};
ULONG Syscallnum = info->ContextRecord->Eax;
PVOID FuncArgs = reinterpret_cast<PVOID>(info->ContextRecord->Esp + 8);
switch (Syscallnum)
{
case SYSCALLNAME::NTSETINFORMATIONPROCESS:
{
//ProcessWow64Information
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
PROCESSINFOCLASS pclass = *reinterpret_cast<PROCESSINFOCLASS*>((ULONG_PTR*)FuncArgs + 1);
PVOID informationbuffer = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 2);
ULONG buffersize = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 3);
if (pclass != ProcessInstrumentationCallback)
info->ContextRecord->Eax = NtSetInformationProcess(ProcessHandle, pclass, informationbuffer, buffersize);
else
{
info->ContextRecord->Eax = 0;
}
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTQUERYINFORMATIONPROCESS:
{
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
PROCESSINFOCLASS pclass = *reinterpret_cast<PROCESSINFOCLASS*>((ULONG_PTR*)FuncArgs + 1);
PVOID informationbuffer = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 2);
ULONG buffersize = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 3);
PULONG returnbuffersize = *reinterpret_cast<PULONG*>((ULONG_PTR*)FuncArgs + 4);
info->ContextRecord->Eax = NtQueryInformationProcess(ProcessHandle, pclass, informationbuffer, buffersize, returnbuffersize);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTSETINFORMATIONTHREAD:
{
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
THREADINFOCLASS tclass = *reinterpret_cast<THREADINFOCLASS*>((ULONG_PTR*)FuncArgs + 1);
PVOID threadinformation = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 2);
ULONG buffersize = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 3);
info->ContextRecord->Eax = NtSetInformationThread(ProcessHandle, tclass, threadinformation, buffersize);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTOPENFILE:
{
PHANDLE PProcessHandle = *reinterpret_cast<PHANDLE*>(FuncArgs);
ACCESS_MASK accessmask = *reinterpret_cast<ACCESS_MASK*>((ULONG_PTR*)FuncArgs + 1);
POBJECT_ATTRIBUTES attribute = *reinterpret_cast<POBJECT_ATTRIBUTES*>((ULONG_PTR*)FuncArgs + 2);
PIO_STATUS_BLOCK io_block = *reinterpret_cast<PIO_STATUS_BLOCK*>((ULONG_PTR*)FuncArgs + 3);
ULONG shareaccess = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 4);
ULONG openoption = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 5);
info->ContextRecord->Eax = NtOpenFile(PProcessHandle, accessmask, attribute, io_block, shareaccess, openoption);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTCREATESECTION:
{
PHANDLE SectionHandle = *reinterpret_cast<PHANDLE*>(FuncArgs);
ACCESS_MASK accessmask = *reinterpret_cast<ACCESS_MASK*>((ULONG_PTR*)FuncArgs + 1);
POBJECT_ATTRIBUTES attribute = *reinterpret_cast<POBJECT_ATTRIBUTES*>((ULONG_PTR*)FuncArgs + 2);
PLARGE_INTEGER largeinteger = *reinterpret_cast<PLARGE_INTEGER*>((ULONG_PTR*)FuncArgs + 3);
ULONG shareaccess = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 4);
ULONG openoption = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 5);
HANDLE filehandle = *reinterpret_cast<HANDLE*>((ULONG_PTR*)FuncArgs + 6);
info->ContextRecord->Eax = NtCreateSection(
SectionHandle,
accessmask,
attribute,
largeinteger,
shareaccess,
openoption,
filehandle
);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTMAPVIEWOFSECTION:
{
HANDLE SectionHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>((ULONG_PTR*)FuncArgs + 1);
PVOID* Baseaddress = *reinterpret_cast<PVOID**>((ULONG_PTR*)FuncArgs + 2);
ULONG_PTR Zerobits = *reinterpret_cast<ULONG_PTR*>((ULONG_PTR*)FuncArgs + 3);
SIZE_T commitsize = *reinterpret_cast<SIZE_T*>((ULONG_PTR*)FuncArgs + 4);
PLARGE_INTEGER largeinteger = *reinterpret_cast<PLARGE_INTEGER*>((ULONG_PTR*)FuncArgs + 5);
PSIZE_T viewsize = *reinterpret_cast<PSIZE_T*>((ULONG_PTR*)FuncArgs + 6);
SECTION_INHERIT inhertdispos = *reinterpret_cast<SECTION_INHERIT*>((ULONG_PTR*)FuncArgs + 7);
ULONG AllocationType = *reinterpret_cast<ULONG_PTR*>((ULONG_PTR*)FuncArgs + 8);
ULONG Win32Protect = *reinterpret_cast<ULONG_PTR*>((ULONG_PTR*)FuncArgs + 9);
info->ContextRecord->Eax = NtMapViewOfSection(
SectionHandle,
ProcessHandle,
Baseaddress,
Zerobits,
commitsize,
largeinteger,
viewsize,
inhertdispos,
AllocationType,
Win32Protect
);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTUNMAPVIEWOFSECTION:
{
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
PVOID Baseaddress = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 1);
info->ContextRecord->Eax = NtUnmapViewOfSection(ProcessHandle, Baseaddress);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTCLOSE:
{
HANDLE Handle = *reinterpret_cast<HANDLE*>(FuncArgs);
info->ContextRecord->Eax = NtClose(Handle);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTPROTECTVIRTUALMEMORY:
{
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
PVOID* Baseaddress = *reinterpret_cast<PVOID**>((ULONG_PTR*)FuncArgs + 1);
PSIZE_T RegionSize = *reinterpret_cast<PSIZE_T*>((ULONG_PTR*)FuncArgs + 2);
ULONG NewProt = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 3);
PULONG OldProt = *reinterpret_cast<PULONG*>((ULONG_PTR*)FuncArgs + 4);
info->ContextRecord->Eax = NtProtectVirtualMemory(ProcessHandle, Baseaddress, RegionSize, NewProt, OldProt);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTQUERYVIRTUALMEMORY:
{
HANDLE ProcessHandle = *reinterpret_cast<HANDLE*>(FuncArgs);
PVOID Baseaddress = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 1);
MEMORY_INFORMATION_CLASS meminfoclass = *reinterpret_cast<MEMORY_INFORMATION_CLASS*>((ULONG_PTR*)FuncArgs + 2);
PVOID MemoryInformation = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 3);
SIZE_T MemoryInformationLength = *reinterpret_cast<SIZE_T*>((ULONG_PTR*)FuncArgs + 4);
PSIZE_T ReturnLength = *reinterpret_cast<PSIZE_T*>((ULONG_PTR*)FuncArgs + 5);
info->ContextRecord->Eax = NtQueryVirtualMemory(
ProcessHandle,
Baseaddress,
meminfoclass,
MemoryInformation,
MemoryInformationLength,
ReturnLength
);
info->ContextRecord->Eip += 2;
break;
}
case SYSCALLNAME::NTQUERYSYSTEMINFORMATION:
{
SYSTEM_INFORMATION_CLASS SysteminformationClass = *reinterpret_cast<SYSTEM_INFORMATION_CLASS*>(FuncArgs);
PVOID SystemInformation = *reinterpret_cast<PVOID*>((ULONG_PTR*)FuncArgs + 1);
ULONG SystemInformationLength = *reinterpret_cast<ULONG*>((ULONG_PTR*)FuncArgs + 2);
PULONG ReturnLength = *reinterpret_cast<PULONG*>((ULONG_PTR*)FuncArgs + 3);
info->ContextRecord->Eax = NtQuerySystemInformation(
SysteminformationClass,
SystemInformation,
SystemInformationLength,
ReturnLength
);
info->ContextRecord->Eip += 2;
break;
}
default:
{
return EXCEPTION_CONTINUE_SEARCH;
}
}
return EXCEPTION_CONTINUE_EXECUTION;
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
#endif