This repository was archived by the owner on Sep 7, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathDetections.cpp
More file actions
2091 lines (1827 loc) · 74.6 KB
/
Copy pathDetections.cpp
File metadata and controls
2091 lines (1827 loc) · 74.6 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
//By AlSch092 @github
#include "Detections.hpp"
#include "Obscure/XorStr.hpp"
#include "Common/SHA256.hpp"
#include "Common/SHA256Utils.hpp"
#include <tlhelp32.h>
#include <algorithm>
#include <functional>
#include <map>
#define OBFUSCATE(str) make_encrypted(L##str)
// Utility: check if a process is in allowedParents (game, launcher, etc)
static bool IsAllowedProcess(DWORD pid, const std::list<std::wstring>& allowedParents);
// Hash a region of memory (utility for self-integrity check)
static std::string HashMemoryRegion(const void* addr, size_t size) {
SHA256 sha;
sha.update(reinterpret_cast<const uint8_t*>(addr), size);
uint8_t* digest = sha.digest();
char buf[65] = {0};
for (int i = 0; i < 32; ++i) sprintf(buf + i * 2, "%02x", digest[i]);
return std::string(buf);
}
// Dynamic API resolver using FNV-1a hash
static FARPROC ResolveApiByHash(HMODULE hMod, uint32_t fnvHash) {
if (!hMod) return nullptr;
auto* dos = (PIMAGE_DOS_HEADER)hMod;
auto* nt = (PIMAGE_NT_HEADERS)((BYTE*)hMod + dos->e_lfanew);
auto* exp = (PIMAGE_EXPORT_DIRECTORY)((BYTE*)hMod + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
auto names = (DWORD*)((BYTE*)hMod + exp->AddressOfNames);
auto funcs = (DWORD*)((BYTE*)hMod + exp->AddressOfFunctions);
auto ords = (WORD*)((BYTE*)hMod + exp->AddressOfNameOrdinals);
for (DWORD i = 0; i < exp->NumberOfNames; ++i) {
const char* name = (const char*)hMod + names[i];
uint32_t hash = 2166136261u;
for (const char* p = name; *p; ++p) hash = (hash ^ (unsigned char)*p) * 16777619u;
if (hash == fnvHash) {
return (FARPROC)((BYTE*)hMod + funcs[ords[i]]);
}
}
return nullptr;
}
// FNV-1a hash macro for API names
#define FNV1A_HASH(str) ([]() { \
const char* s = str; \
uint32_t hash = 2166136261u; \
while (*s) hash = (hash ^ (unsigned char)*s++) * 16777619u; \
return hash; \
}())
// --- Offuscated API wrappers ---
static HANDLE My_CreateToolhelp32Snapshot(DWORD flags, DWORD pid) {
HMODULE h = GetModuleHandleA("kernel32.dll");
using fn = HANDLE(WINAPI*)(DWORD, DWORD);
static fn p = (fn)ResolveApiByHash(h, FNV1A_HASH("CreateToolhelp32Snapshot"));
return p ? p(flags, pid) : NULL;
}
static BOOL My_Process32First(HANDLE hSnap, LPPROCESSENTRY32 lppe) {
HMODULE h = GetModuleHandleA("kernel32.dll");
using fn = BOOL(WINAPI*)(HANDLE, LPPROCESSENTRY32);
static fn p = (fn)ResolveApiByHash(h, FNV1A_HASH("Process32First"));
return p ? p(hSnap, lppe) : FALSE;
}
static BOOL My_Process32Next(HANDLE hSnap, LPPROCESSENTRY32 lppe) {
HMODULE h = GetModuleHandleA("kernel32.dll");
using fn = BOOL(WINAPI*)(HANDLE, LPPROCESSENTRY32);
static fn p = (fn)ResolveApiByHash(h, FNV1A_HASH("Process32Next"));
return p ? p(hSnap, lppe) : FALSE;
}
static BOOL My_CloseHandle(HANDLE h) {
HMODULE hK = GetModuleHandleA("kernel32.dll");
using fn = BOOL(WINAPI*)(HANDLE);
static fn p = (fn)ResolveApiByHash(hK, FNV1A_HASH("CloseHandle"));
return p ? p(h) : FALSE;
}
static HMODULE My_GetModuleHandleA(const char* name) {
HMODULE hK = GetModuleHandleA("kernel32.dll");
using fn = HMODULE(WINAPI*)(const char*);
static fn p = (fn)ResolveApiByHash(hK, FNV1A_HASH("GetModuleHandleA"));
return p ? p(name) : NULL;
}
static FARPROC My_GetProcAddress(HMODULE h, const char* name) {
HMODULE hK = GetModuleHandleA("kernel32.dll");
using fn = FARPROC(WINAPI*)(HMODULE, const char*);
static fn p = (fn)ResolveApiByHash(hK, FNV1A_HASH("GetProcAddress"));
return p ? p(h, name) : NULL;
}
static SIZE_T My_VirtualQuery(LPCVOID addr, PMEMORY_BASIC_INFORMATION mbi, SIZE_T sz) {
HMODULE hK = GetModuleHandleA("kernel32.dll");
using fn = SIZE_T(WINAPI*)(LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T);
static fn p = (fn)ResolveApiByHash(hK, FNV1A_HASH("VirtualQuery"));
return p ? p(addr, mbi, sz) : 0;
}
static BOOL My_ReadProcessMemory(HANDLE h, LPCVOID addr, LPVOID buf, SIZE_T sz, SIZE_T* read) {
HMODULE hK = GetModuleHandleA("kernel32.dll");
using fn = BOOL(WINAPI*)(HANDLE, LPCVOID, LPVOID, SIZE_T, SIZE_T*);
static fn p = (fn)ResolveApiByHash(hK, FNV1A_HASH("ReadProcessMemory"));
return p ? p(h, addr, buf, sz, read) : FALSE;
}
// --- Challenge/response stub ---
static std::string GetRandomTextSectionHash() {
// For demo: hash first 256 bytes of .text
HMODULE hMod = GetModuleHandleA(NULL);
if (!hMod) return "";
auto* dos = (PIMAGE_DOS_HEADER)hMod;
auto* nt = (PIMAGE_NT_HEADERS)((BYTE*)hMod + dos->e_lfanew);
auto* sec = IMAGE_FIRST_SECTION(nt);
for (int i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
if (strncmp((const char*)sec->Name, ".text", 5) == 0) {
return HashMemoryRegion((BYTE*)hMod + sec->VirtualAddress, 256);
}
++sec;
}
return "";
}
Detections::Detections(Settings* s, EvidenceLocker* evidence, BOOL StartMonitor, shared_ptr<NetClient> client) : Config(s), EvidenceManager(evidence), netClient(client)
{
this->InitializeBlacklistedProcessesList();
MonitoringProcessCreation = false; //gets set to true inside `MonitorProcessCreation`
auto ModuleList = Process::GetLoadedModules();
try
{
auto sections = Process::GetSections(_MAIN_MODULE_NAME);
if (sections.size() > 0)
_Proc = make_unique<Process>(sections.size());
else
_Proc = make_unique<Process>(6); //.text , .rdata, .data, .pdata, .rsrc, .reloc, .tls,
Process::SetNumSections(sections.size());
for (ProcessData::Section* section : sections)
{
if (section != nullptr)
delete section;
}
_Services = make_unique<Services>();
integrityChecker = make_shared<Integrity>(ModuleList);
VM = std::make_unique<VirtualMachine>(256);
}
catch (const std::bad_alloc& e)
{
Logger::logf(Err, "One or more pointers could not be allocated @ Detections::Detections: %s", e.what());
std::terminate();
}
if (!FetchBlacklistedBytePatterns(BlacklisteBytePatternRepository))
{
Logger::logf(Warning, "Failed to fetch blacklisted byte patterns from web location!");
}
HMODULE hNtdll = GetModuleHandleA("ntdll.dll");
if (hNtdll != 0) //register DLL notifications callback
{
_LdrRegisterDllNotification pLdrRegisterDllNotification = (_LdrRegisterDllNotification)GetProcAddress(hNtdll, "LdrRegisterDllNotification");
NTSTATUS status = pLdrRegisterDllNotification(0, (PLDR_DLL_NOTIFICATION_FUNCTION)OnDllNotification, this, &DllCallbackRegistrationCookie);
}
if (StartMonitor)
this->StartMonitor();
}
Detections::~Detections()
{
if (DllCallbackRegistrationCookie) //unregister DLL notifications
{
typedef NTSTATUS(NTAPI* pfnLdrUnregisterDllNotification)(PVOID Cookie);
HMODULE hNtdll = GetModuleHandleA("ntdll.dll");
if (hNtdll == 0)
hNtdll = LoadLibraryA("ntdll.dll");
pfnLdrUnregisterDllNotification pLdrRegisterDllNotification = (pfnLdrUnregisterDllNotification)GetProcAddress(hNtdll, "LdrUnregisterDllNotification");
NTSTATUS status = pLdrRegisterDllNotification(DllCallbackRegistrationCookie);
if (!NT_SUCCESS(status))
{
Logger::logf(Err, "Failed to unregister DLL notifications: %d", GetLastError());
}
DllCallbackRegistrationCookie = nullptr;
}
if (MonitorThread != nullptr)
delete MonitorThread;
if (RegistryMonitorThread != nullptr)
delete RegistryMonitorThread;
if (ProcessCreationMonitorThread != nullptr)
delete ProcessCreationMonitorThread;
}
/*
Detections::StartMonitor - use class member MonitorThread to start our main detections loop
*/
bool Detections::StartMonitor()
{
if (this->MonitorThread != nullptr) //prevent accidental double calls to this function/double thread creation
return false;
this->MonitorThread = new Thread((LPTHREAD_START_ROUTINE)&Monitor, (LPVOID)this, true, false);
Logger::logf(Info, "Created monitoring thread with ID %d", this->MonitorThread->GetId());
if (this->MonitorThread->GetId() == 0)
{
Logger::logf(Err, " Failed to create monitor thread @ Detections::StartMonitor");
return false;
}
this->ProcessCreationMonitorThread = new Thread((LPTHREAD_START_ROUTINE)&Detections::MonitorProcessCreation, this, true, false);
this->RegistryMonitorThread = new Thread((LPTHREAD_START_ROUTINE)&MonitorImportantRegistryKeys, (LPVOID)this, true, false);
return true;
}
/*
LdrpDllNotification - This function is called whenever a new module is loaded into the process space, called before TLS callbacks
*/
VOID CALLBACK Detections::OnDllNotification(ULONG NotificationReason, const PLDR_DLL_NOTIFICATION_DATA NotificationData, PVOID Context)
{
Detections* Monitor = reinterpret_cast<Detections*>(Context);
if (NotificationReason == LDR_DLL_NOTIFICATION_REASON_LOADED)
{
LPCWSTR FullDllName = NotificationData->Loaded.FullDllName->pBuffer;
if (Monitor != nullptr && FullDllName != nullptr)
{
Logger::logfw(Info, L"[LdrpDllNotification Callback] dll loaded: %s", FullDllName);
std::lock_guard<std::mutex> lock(Monitor->DLLVerificationQueueMutex);
Monitor->DLLVerificationQueue.push(wstring(FullDllName));
}
}
}
/*
CheckDLLSignature - checks the signatures of any newly loaded modules
*/
void Detections::CheckDLLSignature()
{
while (true)
{
wstring FullDllName;
{
std::lock_guard<std::mutex> lock(this->DLLVerificationQueueMutex); //lock only for queue access
if (this->DLLVerificationQueue.empty())
{
break;
}
FullDllName = this->DLLVerificationQueue.front();
this->DLLVerificationQueue.pop();
} //mutex is unlocked here automatically since lock_guard works as a RAII and we create scope with { and }
if (FullDllName.size() > 0) //now do the expensive work without holding the lock
{
if (!Authenticode::HasSignature(FullDllName.c_str(), TRUE))
{
Logger::logfw(Detection, L"Failed to verify signature of %s", FullDllName.c_str());
this->EvidenceManager->AddFlagged(DetectionFlags::INJECTED_ILLEGAL_PROGRAM, Utility::ConvertWStringToString(FullDllName), GetCurrentProcessId());
this->UnsignedModulesLoaded.push_back(FullDllName);
}
else
{
if (find(this->PassedCertCheckModules.begin(), this->PassedCertCheckModules.end(), FullDllName) == this->PassedCertCheckModules.end())
this->PassedCertCheckModules.push_back(FullDllName); //add proper signed module to cache
}
}
}
}
/*
Detections::Monitor(LPVOID thisPtr)
Routine which monitors aspects of the process for fragments of cheating, loops continuously until the thread is signalled to shut down
*/
void Detections::Monitor(__in LPVOID thisPtr)
{
if (thisPtr == NULL)
{
Logger::logf(Err, "thisPtr was NULL @ Detections::Monitor. Aborting execution!");
return;
}
Logger::logf(Info, "Starting Detections::Monitor");
Detections* Monitor = reinterpret_cast<Detections*>(thisPtr);
if (Monitor == nullptr)
{
Logger::logf(Err, "Monitor Ptr was NULL @ Detections::Monitor. Aborting execution!");
return;
}
UINT64 CachedTextSectionAddress = 0;
DWORD CachedTextSectionSize = 0;
UINT64 CachedRDataSectionAddress = 0;
DWORD CachedRDataSectionSize = 0;
if (Monitor->Config->bCheckIntegrity) //integrity check setup if option is enabled
{
list<ProcessData::Section*> sections = Process::GetSections(_MAIN_MODULE_NAME);
Monitor->SetSectionHash(_MAIN_MODULE_NAME, ".text"); //set our memory hashes of .text
Monitor->SetSectionHash(_MAIN_MODULE_NAME, ".rdata");
if (sections.size() == 0)
{
Logger::logf(Err, "Sections size was 0 @ Detections::Monitor. Aborting execution!");
return;
}
UINT64 ModuleAddr = (UINT64)GetModuleHandleA(NULL);
if (ModuleAddr == 0)
{
Logger::logf(Err, "Module couldn't be retrieved @ Detections::Monitor. Aborting execution! (%d)\n", GetLastError());
return;
}
for (auto section : sections)
{
if (section == nullptr)
continue;
if (section->name == ".text")
{
CachedTextSectionAddress = section->address + ModuleAddr; //cache our .text sections address and memory size, since an attacker could possibly spoof the section name or # of sections in ntheaders to prevent section traversing
CachedTextSectionSize = section->size;
}
else if (section->name == ".rdata")
{
CachedRDataSectionAddress = section->address + ModuleAddr;
CachedRDataSectionSize = section->size;
}
}
}
//Main Monitor Loop, continuous detections go in here. we need access to CachedSectionAddress variables so this loop doesnt get its own function.
bool Monitoring = true;
const int MonitorLoopMilliseconds = 5000;
static std::string initialMonitorHash;
if (initialMonitorHash.empty()) {
// Calcola hash della funzione Monitor (self-integrity baseline)
initialMonitorHash = HashMemoryRegion((void*)&Detections::Monitor, 1024); // 1024 byte dalla funzione
}
static std::string initialRandomTextHash;
static size_t randomTextOffset = 0;
if (initialRandomTextHash.empty()) {
// Scegli offset random nella .text section (tra 0 e 4096)
srand((unsigned int)time(NULL));
randomTextOffset = (rand() % 16) * 256; // 0, 256, 512, ... 3840
HMODULE hMod = GetModuleHandleA(NULL);
if (hMod) {
auto* dos = (PIMAGE_DOS_HEADER)hMod;
auto* nt = (PIMAGE_NT_HEADERS)((BYTE*)hMod + dos->e_lfanew);
auto* sec = IMAGE_FIRST_SECTION(nt);
for (int i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
if (strncmp((const char*)sec->Name, ".text", 5) == 0) {
initialRandomTextHash = HashMemoryRegion((BYTE*)hMod + sec->VirtualAddress + randomTextOffset, 256);
break;
}
++sec;
}
}
}
int challengeCounter = 0;
while (Monitoring)
{
if (Monitor == nullptr) //critical error
{
Logger::logf(Err, "Monitor ptr was NULL @ Detections::Monitor, shutting down");
std::terminate();
}
if (Monitor->GetMonitorThread()->IsShutdownSignalled()) //end thread if thread shutdown is signalled
{
Logger::logf(Info, "STOPPING Detections::Monitor , ending detections thread");
return;
}
Monitor->CheckDLLSignature(); //check signatures of any newly loaded modules
// --- INIZIO BLOCCO: detection generiche limitate ai processi critici ---
const std::list<std::wstring>& allowedParents = Monitor->Config->allowedParents;
DWORD myPid = GetCurrentProcessId();
bool shouldFlag = false;
if (IsAllowedProcess(myPid, allowedParents)) {
shouldFlag = true;
} else {
// Check parent
HANDLE hSnapshot = My_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE) {
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (My_Process32First(hSnapshot, &pe)) {
do {
if (pe.th32ProcessID == myPid) {
if (IsAllowedProcess(pe.th32ParentProcessID, allowedParents)) {
shouldFlag = true;
break;
}
}
} while (My_Process32Next(hSnapshot, &pe));
}
My_CloseHandle(hSnapshot);
}
}
// --- FINE BLOCCO ---
if (Monitor->Config->bCheckHypervisor)
{
if (Services::IsHypervisorPresent())
{
string vendor = Services::GetHypervisorVendor();
if (vendor.size() == 0)
{
Logger::logf(Detection, "Hypervisor vendor was empty, some custom hypervisor might be hooking cpuid instruction");
}
else if (vendor == "Microsoft Hv" || vendor == "VMwareVMware" || vendor == "XenVMMXenVMM" || vendor == "VBoxVBoxVBox")
{
Logger::logf(Detection, "Hypervisor was present with vendor: %s", vendor.c_str());
}
else
{
Logger::logf(Detection, "Hypervisor was present with unknown/non-standard vendor: %s.", vendor.c_str());
}
Monitor->EvidenceManager->AddFlagged(DetectionFlags::HYPERVISOR);
}
}
if (Monitor->Config->bCheckIntegrity)
{
if (Monitor->GetIntegrityChecker()->IsTLSCallbackStructureModified())
{
if (shouldFlag)
{
Logger::logf(Detection, "Found modified TLS callback structure section (atleast one aspect of the TLS data directory structure was modified)");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
}
}
if (Monitor->IsSectionHashUnmatching(CachedTextSectionAddress, CachedTextSectionSize, ".text"))
{
if (shouldFlag)
{
Logger::logf(Detection, "Found modified .text section (or you're debugging with software breakpoints)!\n");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
}
}
if (Monitor->IsSectionHashUnmatching(CachedRDataSectionAddress, CachedRDataSectionSize, ".rdata"))
{
if (shouldFlag)
{
Logger::logf(Detection, "Found modified .rdata section!\n");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
}
}
if (!Monitor->GetIntegrityChecker()->CheckFileIntegrityFromDisc())
{
if (shouldFlag)
{
Logger::logf(Detection, ".text section of file on disc differs from runtime process!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
}
}
}
if (Monitor->GetIntegrityChecker()->IsModuleModified(L"WINTRUST.dll"))
{
if (shouldFlag)
{
Logger::logf(Detection, "Found modified .text section in WINTRUST.dll!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
}
}
vector<uint64_t> mappedRegions = Monitor->DetectManualMapping();
if (mappedRegions.size() > 0)
{
for (uint64_t mappedRegionAddress : mappedRegions)
{
Logger::logf(Detection, "Found potentially manually mapped region at: %llX", mappedRegionAddress);
Monitor->EvidenceManager->AddFlagged(DetectionFlags::MANUAL_MAPPING, std::to_string(mappedRegionAddress), GetCurrentProcessId());
}
}
if (Monitor->GetConfig() != nullptr && Monitor->GetConfig()->bEnforceDSE)
{
Monitor->SetUnsignedLoadedDriversList(Monitor->GetServiceManager()->GetUnsignedDrivers(Monitor->PassedCertCheckDrivers));
if (Monitor->GetUnsignedLoadedDriversList().size() > 0)
{
for (wstring driver : Monitor->GetUnsignedLoadedDriversList())
{
Logger::logfw(Warning, L"Unsigned driver was loaded: %s", driver.c_str());
}
}
}
if (Monitor->IsBlacklistedProcessRunning())
{
Logger::logf(Detection, "Found blacklisted process!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::EXTERNAL_ILLEGAL_PROGRAM);
auto netClientWeak = Monitor->GetNetClient();
if (auto netClient = netClientWeak.lock()) {
netClient->FlagCheater(DetectionFlags::EXTERNAL_ILLEGAL_PROGRAM);
}
}
if (Monitor->DoesFunctionAppearHooked("ws2_32.dll", "send") || Monitor->DoesFunctionAppearHooked("ws2_32.dll", "recv"))
{
if (shouldFlag)
{
Logger::logf(Detection, "Networking WINAPI (send | recv) was hooked!\n");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::DLL_TAMPERING);
}
}
if (Monitor->GetIntegrityChecker()->IsUnknownModulePresent())
{
if (shouldFlag)
{
Logger::logf(Detection, "Found at least one unsigned dll loaded : We ideally only want verified, signed dlls in our application!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::INJECTED_ILLEGAL_PROGRAM);
}
}
if (Services::IsTestsigningEnabled() || Services::IsDebugModeEnabled())
{
if (shouldFlag)
{
Logger::logf(Detection, "Testsigning or debugging mode is enabled! In most cases we don't allow the game/process to continue if testsigning is enabled.");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::UNSIGNED_DRIVERS);
}
}
if (Monitor->Detections::DoesIATContainHooked())
{
if (shouldFlag)
{
Logger::logf(Detection, "IAT was hooked! One or more functions lead to addresses outside their respective modules!\n");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::BAD_IAT);
}
}
if (Detections::IsTextSectionWritable())
{
#ifndef _DEBUG
if (shouldFlag)
{
Logger::logf(Detection, ".text section was writable, which means someone re-re-mapped our memory regions! (or you ran this in DEBUG build)");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::PAGE_PROTECTIONS);
}
#endif
}
if (Detections::CheckOpenHandles())
{
if (shouldFlag)
{
Logger::logf(Detection, "Found open process handles to our process from other processes");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::OPEN_PROCESS_HANDLES);
}
}
if (Monitor->IsBlacklistedWindowPresent())
{
Logger::logf(Detection, "Found blacklisted window text!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::EXTERNAL_ILLEGAL_PROGRAM);
}
auto _future = std::async(std::launch::async, &EvidenceLocker::PushAllEvidence, Monitor->EvidenceManager); //push any newly found flags to server
// --- Self-integrity check runtime ---
std::string currentMonitorHash = HashMemoryRegion((void*)&Detections::Monitor, 1024);
if (currentMonitorHash != initialMonitorHash) {
Logger::logf(Detection, "Monitor function code in memory was modified at runtime!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
// Invio immediato della detection al server
auto netClientWeak = Monitor->GetNetClient();
if (auto netClient = netClientWeak.lock()) {
netClient->FlagCheater(DetectionFlags::CODE_INTEGRITY);
}
}
// --- Self-integrity check random .text section ---
if (!initialRandomTextHash.empty()) {
HMODULE hMod = GetModuleHandleA(NULL);
if (hMod) {
auto* dos = (PIMAGE_DOS_HEADER)hMod;
auto* nt = (PIMAGE_NT_HEADERS)((BYTE*)hMod + dos->e_lfanew);
auto* sec = IMAGE_FIRST_SECTION(nt);
for (int i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
if (strncmp((const char*)sec->Name, ".text", 5) == 0) {
std::string currentRandomTextHash = HashMemoryRegion((BYTE*)hMod + sec->VirtualAddress + randomTextOffset, 256);
if (currentRandomTextHash != initialRandomTextHash) {
Logger::logf(Detection, "Random .text section region was modified at runtime!");
Monitor->EvidenceManager->AddFlagged(DetectionFlags::CODE_INTEGRITY);
auto netClientWeak = Monitor->GetNetClient();
if (auto netClient = netClientWeak.lock()) {
netClient->FlagCheater(DetectionFlags::CODE_INTEGRITY);
}
}
break;
}
++sec;
}
}
}
// --- API call obfuscation example ---
HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
// FNV-1a("Sleep") = 0xa7a6cfa7
using SleepFunc = VOID(WINAPI*)(DWORD);
SleepFunc pSleep = (SleepFunc)ResolveApiByHash(hKernel32, 0xa7a6cfa7);
if (pSleep) pSleep(MonitorLoopMilliseconds); else Sleep(MonitorLoopMilliseconds);
// --- Dynamic blacklist update periodic ---
if (challengeCounter % 60 == 0) { // ogni ~5min
Monitor->UpdateBlacklistsFromServer();
}
}
}
/*
FetchBlacklistedBytePatterns - read file from `url`, add each line of file to our blacklisted byte pattern list
Each line of the file located at `url` should be a space-seperated hex byte string, eg) 48 8D 05 12 33 CD
returns `false` on failure
*/
bool Detections::FetchBlacklistedBytePatterns(__in const char* url)
{
if (url == nullptr)
return false;
vector<string> responseHeaders;
string response = HttpClient::ReadWebPage(url, {}, "", responseHeaders);
if (response.size() == 0)
return false;
stringstream ss(response);
string bytePattern;
while (getline(ss, bytePattern))
{
vector<uint8_t> bytes;
if (!bytePattern.empty() && bytePattern.back() == '\r')
{
bytePattern.pop_back(); //remove \r
if (!bytePattern.empty() && bytePattern.back() == ' ')
bytePattern.pop_back(); //remove space
}
stringstream ss2(bytePattern);
string _byte;
while (getline(ss2, _byte, ' '))
{
if (_byte.size() >= 2 && _byte[0] == '/' && _byte[1] == '/') //found comment at end of pattern, don't parse this part
break;
uint8_t byte = stoul(_byte, nullptr, 16);
bytes.push_back(byte);
}
this->BlacklistedBytePatterns.emplace_back(BytePattern(bytes, bytes.size()));
}
return true;
}
/*
SetSectionHash sets the member variable `_TextSectionHashes` or `_RDataSectionHashes` via SetSectionHashList() call after finding the `sectionName` named section (.text in our case)
Returns a list<Section*> which we can use in later hashing calls to compare sets of these hashes and detect memory tampering within the section
*/
bool Detections::SetSectionHash(__in const char* moduleName, __in const char* sectionName)
{
if (moduleName == nullptr || sectionName == nullptr)
{
Logger::logf(Err, "one or more parameters were nullptr @ SetSectionHash");
return false;
}
if (GetIntegrityChecker() == nullptr)
{
Logger::logf(Err, "IntegrityChecker was nullptr @ SetSectionHash");
return false;
}
bool funcFailed = false;
UINT64 ModuleAddr = (UINT64)GetModuleHandleA(moduleName);
if (ModuleAddr == 0)
{
Logger::logf(Err, "ModuleAddr was 0 @ SetSectionHash");
return false;
}
list<ProcessData::Section*> sections = Process::GetSections(moduleName);
if (sections.size() == 0)
{
Logger::logf(Err, "sections.size() of section %s was 0 @ SetSectionHash", sectionName);
funcFailed = true;
goto cleanup;
}
for (auto section : sections)
{
if (section == nullptr)
continue;
if (section->name == sectionName)
{
vector<uint64_t> hashes = GetIntegrityChecker()->GetMemoryHash((uint64_t)section->address + ModuleAddr, section->size);
if (hashes.size() > 0)
{
GetIntegrityChecker()->SetSectionHashList(hashes, sectionName);
break;
}
else
{
Logger::logf(Err, "hashes.size() was 0 @ SetSectionHash", sectionName);
funcFailed = true;
goto cleanup;
}
}
}
cleanup:
for (auto section : sections)
{
if (section != nullptr)
delete section;
}
return !funcFailed;
}
/*
IsSectionHashUnmatching compares our collected hash list from ::SetSectionHash() , we use cached address + size to prevent spoofing (sections can be renamed at runtime by an attacker)
Returns true if the two sets of hashes do not match, implying memory was modified
*/
bool Detections::IsSectionHashUnmatching(__in const UINT64 cachedAddress, __in const DWORD cachedSize, __in const string section)
{
if (cachedAddress == 0 || cachedSize == 0)
{
Logger::logf(Err, "Parameters were 0 @ Detections::IsSectionHashUnmatching");
return false;
}
Logger::logf(Info, "Checking hashes of address: %llx (%d bytes) for memory integrity\n", cachedAddress, cachedSize);
if (section == ".text")
{
if (GetIntegrityChecker()->Check((uint64_t)cachedAddress, cachedSize, GetIntegrityChecker()->GetSectionHashList(".text"))) //compares hash to one gathered previously
{
Logger::logf(Info, "Hashes match: Program's .text section appears genuine.\n");
return false;
}
else
{
Logger::logf(Detection, " .text section of program is modified!\n");
return true;
}
}
else if (section == ".rdata")
{
if (GetIntegrityChecker()->Check((uint64_t)cachedAddress, cachedSize, GetIntegrityChecker()->GetSectionHashList(".rdata"))) //compares hash to one gathered previously
{
Logger::logf(Info, "Hashes match: Program's .rdata section appears genuine.\n");
return false;
}
else
{
Logger::logf(Detection, " .rdata section of program is modified!\n");
return true;
}
}
return false;
}
/*
IsBlacklistedProcessRunning
returns TRUE if a blacklisted program is running in the background, blacklisted processes can be found in the class constructor
*/
bool Detections::IsBlacklistedProcessRunning() const
{
bool foundBlacklistedProcess = false;
HANDLE hSnapshot = My_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
{
Logger::logf(Err, "Failed to create snapshot of processes. Error code: %d @ Detections::IsBlacklistedProcessRunning\n", GetLastError());
return false;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (!My_Process32First(hSnapshot, &pe32))
{
Logger::logf(Err, "Failed to get first process. Error code: %d @ Detections::IsBlacklistedProcessRunning\n", GetLastError());
My_CloseHandle(hSnapshot);
return false;
}
do
{
std::wstring processName = pe32.szExeFile;
// Controllo nome esatto
for (const auto& blacklisted : BlacklistedProcesses)
{
if (Utility::wcscmp_insensitive(blacklisted.c_str(), processName.c_str()))
{
Logger::logfw(Detection, L"[BLACKLIST] Processo blacklisted rilevato: %s", processName.c_str());
foundBlacklistedProcess = true;
break;
}
}
// Controllo parole chiave
for (const auto& keyword : BlacklistedKeywords)
{
if (Utility::wcsistr(processName.c_str(), keyword.c_str()) != nullptr)
{
Logger::logfw(Detection, L"[BLACKLIST] Processo con parola chiave sospetta '%s': %s", keyword.c_str(), processName.c_str());
foundBlacklistedProcess = true;
break;
}
}
} while (My_Process32Next(hSnapshot, &pe32));
My_CloseHandle(hSnapshot);
return foundBlacklistedProcess;
}
/*
* DoesFunctionAppearHooked - Checks if first bytes of a routine are a jump or call. Please make sure the function you use with this doesnt normally start with a jump or call.
Returns TRUE if the looked up function contains a jump or call as its first instruction
*/
bool Detections::DoesFunctionAppearHooked(__in const char* moduleName, __in const char* functionName)
{
if (moduleName == nullptr || functionName == nullptr)
{
Logger::logf(Err, "moduleName or functionName was NULL @ Detections::DoesFunctionAppearHooked");
return false;
}
bool FunctionPreambleHooked = false;
HMODULE hMod = My_GetModuleHandleA(moduleName);
if (hMod == NULL)
{
Logger::logf(Err, " Couldn't fetch module @ Detections::DoesFunctionAppearHooked: %s", moduleName);
return false;
}
UINT64 AddressFunction = (UINT64)My_GetProcAddress(hMod, functionName);
if (AddressFunction == NULL)
{
Logger::logf(Err, " Couldn't fetch address of function @ Detections::DoesFunctionAppearHooked: %s", functionName);
return false;
}
__try
{
if (*(BYTE*)AddressFunction == 0xE8 || *(BYTE*)AddressFunction == 0xE9 || *(BYTE*)AddressFunction == 0xEA || *(BYTE*)AddressFunction == 0xEB) //0xEB = short jump, 0xE8 = call X, 0xE9 = long jump, 0xEA = "jmp oper2:oper1"
FunctionPreambleHooked = true;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
Logger::logf(Warning, " Couldn't read bytes @ Detections::DoesFunctionAppearHooked: %s", functionName);
return false; //couldn't read memory at function
}
return FunctionPreambleHooked;
}
/*
DoesIATContainHooked - Returns TRUE if any routines in the IAT lead to addresses outside their respective modules
if the attacker writes their hooks in the dll's address space then they can get around this detection
*/
bool Detections::DoesIATContainHooked()
{
list<ProcessData::ImportFunction*> IATFunctions = Process::GetIATEntries();
bool isIATHooked = false;
auto modules = Process::GetLoadedModules();
for (ProcessData::ImportFunction* IATEntry : IATFunctions)
{
DWORD moduleSize = Process::GetModuleSize(IATEntry->Module);
bool FoundIATEntryInModule = false;
if (moduleSize != 0)
{ //some IAT functions in k32 can point to ntdll (forwarding), thus we have to compare IAT to each other whitelisted DLL range
for (auto mod : modules)
{
UINT64 LowAddr = (UINT64)mod.dllInfo.lpBaseOfDll;
UINT64 HighAddr = (UINT64)mod.dllInfo.lpBaseOfDll + mod.dllInfo.SizeOfImage;
if (IATEntry->AddressOfData > LowAddr && IATEntry->AddressOfData < HighAddr) //each IAT entry needs to be checked thru all loaded ranges
{
FoundIATEntryInModule = true;
}
}
if (!FoundIATEntryInModule)
{
isIATHooked = true;
break;
}
}
else //error, we shouldnt get here!
{
Logger::logf(Err, " Couldn't fetch module size @ Detections::DoesIATContainHooked");
return false;
}
}
return isIATHooked;
}
/*
Detections::IsTextSectionWritable() - Simple memory protections check on page in the .text section
returns address where the page was writable, which imples someone re-re-mapped our process memory and wants to write patches.
*/
UINT64 Detections::IsTextSectionWritable()
{
UINT64 textAddr = Process::GetSectionAddress(NULL, ".text");
MEMORY_BASIC_INFORMATION mbi = { 0 };
SIZE_T result;
UINT64 address = textAddr;
const int pageSize = 0x1000;
if (textAddr == NULL)
{
Logger::logf(Err, "textAddr was NULL @ Detections::IsTextSectionWritable");
return 0;
}
UINT64 max_addr = textAddr + Process::GetTextSectionSize(GetModuleHandle(NULL));
while ((result = My_VirtualQuery((LPCVOID)address, &mbi, sizeof(mbi))) != 0) //Loop through all pages in .text
{
if (address >= max_addr)
break;
if (mbi.Protect != PAGE_EXECUTE_READ) //check if its not RX protections
{
Logger::logfw(Detection, L"Memory region at address %p is not PAGE_EXECUTE_READ - attacker likely re-re-mapped\n", address);
return address;
}
address += pageSize;
}
return 0;
}
/*
CheckOpenHandles - Checks if any processes have open handles to our process, excluding whitelisted processes such as conhost.exe
returns true if some other process has an open process handle to the current process
*/
// DISABILITATO per test ed errori parental per l'updater.. SOLO TEST (ANCHE IN API.cpp)
/*
bool Detections::CheckOpenHandles()
{