-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCheatMonitorEnvironmentGuard.cpp
More file actions
493 lines (452 loc) · 19.1 KB
/
Copy pathCheatMonitorEnvironmentGuard.cpp
File metadata and controls
493 lines (452 loc) · 19.1 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
#include "CheatMonitor.h"
#include "CheatMonitorEngine.h"
#include "ISensor.h"
#include "IatHookSensor.h"
#include "VehHookSensor.h"
#include "InlineHookSensor.h"
#include "ProcessHollowingSensor.h"
#include "ProcessAndWindowMonitorSensor.h"
#include "DriverIntegritySensor.h"
#include "ThreadActivitySensor.h"
#include "ModuleActivitySensor.h"
#include "MemorySecuritySensor.h"
#include "AdvancedAntiDebugSensor.h"
#include "SystemCodeIntegritySensor.h"
#include "ModuleIntegritySensor.h"
#include "ProcessHandleSensor.h"
#include "VTableHookSensor.h"
#include "CheatConfigManager.h"
#include "Logger.h"
#include "utils/SystemUtils.h"
#include "utils/Utils.h"
#include <algorithm>
#include <array>
#include <iphlpapi.h>
typedef NTSTATUS(NTAPI *P_LdrRegisterDllNotification)(ULONG Flags, PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction,
PVOID Context, PVOID *Cookie);
typedef NTSTATUS(NTAPI *P_LdrUnregisterDllNotification)(PVOID Cookie);
namespace
{
bool QueryRawOsVersion(OSVERSIONINFOEXW &osInfo)
{
memset(&osInfo, 0, sizeof(osInfo));
osInfo.dwOSVersionInfoSize = sizeof(osInfo);
typedef NTSTATUS (WINAPI *RtlGetVersion_t)(LPOSVERSIONINFOEXW);
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
RtlGetVersion_t pRtlGetVersion = hNtdll ? reinterpret_cast<RtlGetVersion_t>(GetProcAddress(hNtdll, "RtlGetVersion")) : nullptr;
if (pRtlGetVersion)
{
return NT_SUCCESS(pRtlGetVersion(&osInfo));
}
return GetVersionExW(reinterpret_cast<LPOSVERSIONINFOW>(&osInfo));
}
bool IsAtLeastWindowsXp(const OSVERSIONINFOEXW &osInfo)
{
if (osInfo.dwMajorVersion > 5) return true;
return osInfo.dwMajorVersion == 5 && osInfo.dwMinorVersion >= 1;
}
bool IsAtLeastWindows7Sp1(const OSVERSIONINFOEXW &osInfo)
{
if (osInfo.dwMajorVersion > 6) return true;
if (osInfo.dwMajorVersion < 6) return false;
if (osInfo.dwMinorVersion > 1) return true;
return osInfo.dwMinorVersion == 1 && osInfo.wServicePackMajor >= 1;
}
bool IsAtLeastWindows10(const OSVERSIONINFOEXW &osInfo)
{
return osInfo.dwMajorVersion >= 10;
}
}
void CheatMonitorEngine::InitializeSystem()
{
SystemUtils::EnsureNtApisLoaded();
if (m_lightweightSensors.empty())
{
// LIGHT 级传感器:始终在轻量周期执行
m_lightweightSensors.push_back(std::make_unique<AdvancedAntiDebugSensor>());
m_lightweightSensors.push_back(std::make_unique<SystemCodeIntegritySensor>());
m_lightweightSensors.push_back(std::make_unique<IatHookSensor>());
m_lightweightSensors.push_back(std::make_unique<VehHookSensor>());
m_lightweightSensors.push_back(std::make_unique<VTableHookSensor>());
// HEAVY / CRITICAL 级传感器:在重型周期执行,统一走 heavy 扫描预算与分片机制
m_heavyweightSensors.push_back(std::make_unique<ThreadActivitySensor>());
m_heavyweightSensors.push_back(std::make_unique<ModuleActivitySensor>());
m_heavyweightSensors.push_back(std::make_unique<MemorySecuritySensor>());
m_heavyweightSensors.push_back(std::make_unique<DriverIntegritySensor>());
m_heavyweightSensors.push_back(std::make_unique<InlineHookSensor>());
m_heavyweightSensors.push_back(std::make_unique<ProcessHollowingSensor>());
m_heavyweightSensors.push_back(std::make_unique<ProcessHandleSensor>());
m_heavyweightSensors.push_back(std::make_unique<ModuleIntegritySensor>());
m_heavyweightSensors.push_back(std::make_unique<ProcessAndWindowMonitorSensor>());
for (const auto &sensor : m_lightweightSensors) m_sensorRegistry[sensor->GetName()] = sensor.get();
for (const auto &sensor : m_heavyweightSensors) m_sensorRegistry[sensor->GetName()] = sensor.get();
}
if (!IsCurrentOsSupported())
{
LOG_WARNING(AntiCheatLogger::LogCategory::SYSTEM, "当前OS未达到配置要求, 跳过高风险初始化");
return;
}
RegisterDllNotification();
if (!m_wmiMonitor)
{
m_wmiMonitor = std::make_unique<anti_cheat::WMIProcessMonitor>(
[this](DWORD pid, const std::wstring &name) { this->OnProcessCreated(pid, name); });
if (!m_wmiMonitor->Initialize())
{
LOG_WARNING(AntiCheatLogger::LogCategory::SYSTEM, "WMI/Toolhelp process monitor initialization failed.");
}
}
HardenProcessAndThreads();
CheckParentProcessAtStartup();
DetectVirtualMachine();
InitializeProcessBaseline();
m_vehListAddress = FindVehListAddress();
InitializeSelfIntegrityBaseline();
}
void CheatMonitorEngine::OnConfigUpdated()
{
std::string osVersionName = CheatConfigManager::GetInstance().GetMinOsVersionName();
anti_cheat::OsVersion requiredOsVersion = CheatConfigManager::GetInstance().GetMinOsVersion();
(void)osVersionName;
const bool osVersionSupported = IsCurrentOsSupported();
LOG_INFO_F(AntiCheatLogger::LogCategory::SYSTEM, "OS版本门控结果: 当前OS=%d, 配置要求min_os=%d, 版本兼容=%s",
(int)m_windowsVersion, (int)requiredOsVersion, osVersionSupported ? "是" : "否");
std::string hmacKey = CheatConfigManager::GetInstance().GetHmacKey();
LOG_INFO_F(AntiCheatLogger::LogCategory::SECURITY, "协议安全配置更新: HMAC签名=%s",
hmacKey.empty() ? "禁用" : "启用");
// Process pending DLL loads now that whitelist config is available
ProcessPendingDllLoads();
}
bool CheatMonitorEngine::IsCurrentOsSupported() const
{
anti_cheat::OsVersion requiredOsVersion = CheatConfigManager::GetInstance().GetMinOsVersion();
// Use m_windowsVersion member for version check (allows test override)
switch (requiredOsVersion)
{
case anti_cheat::OS_ANY:
return true;
case anti_cheat::OS_WIN_XP:
return m_windowsVersion >= SystemUtils::WindowsVersion::Win_XP;
case anti_cheat::OS_WIN7_SP1:
return m_windowsVersion >= SystemUtils::WindowsVersion::Win_Vista_Win7;
case anti_cheat::OS_WIN10:
return m_windowsVersion >= SystemUtils::WindowsVersion::Win_10;
default:
return false;
}
}
void CheatMonitorEngine::HardenProcessAndThreads()
{
bool isElevated = false;
HANDLE hToken = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
TOKEN_ELEVATION elevation;
DWORD size = sizeof(TOKEN_ELEVATION);
if (GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &size))
{
isElevated = elevation.TokenIsElevated != 0;
}
CloseHandle(hToken);
}
if (!isElevated)
{
LOG_WARNING(AntiCheatLogger::LogCategory::SYSTEM, "进程未以管理员权限运行,某些安全策略可能无法设置");
}
typedef BOOL(WINAPI *PSetProcessMitigationPolicy)(PROCESS_MITIGATION_POLICY Policy, PVOID lpBuffer, SIZE_T dwLength);
static PSetProcessMitigationPolicy pSetProcessMitigationPolicy =
(PSetProcessMitigationPolicy)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "SetProcessMitigationPolicy");
if (!SystemUtils::HasApiCapability(SystemUtils::ApiCapability::ProcessMitigationPolicy))
{
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM,
"当前OS能力矩阵未启用 ProcessMitigationPolicy,跳过进程缓解策略。");
}
else if (pSetProcessMitigationPolicy)
{
PROCESS_MITIGATION_DEP_POLICY depPolicy = {};
depPolicy.Enable = 1;
depPolicy.Permanent = false;
(void)pSetProcessMitigationPolicy(ProcessDEPPolicy, &depPolicy, sizeof(depPolicy));
PROCESS_MITIGATION_CHILD_PROCESS_POLICY childPolicy = {};
childPolicy.NoChildProcessCreation = 1;
(void)pSetProcessMitigationPolicy(ProcessChildProcessPolicy, &childPolicy, sizeof(childPolicy));
}
else
{
LOG_WARNING(AntiCheatLogger::LogCategory::SYSTEM,
"SetProcessMitigationPolicy API 不可用,可能是系统版本过低。");
}
if (SystemUtils::g_pNtSetInformationThread)
{
NTSTATUS status = SystemUtils::g_pNtSetInformationThread(GetCurrentThread(), (THREADINFOCLASS)17, nullptr, 0);
if (!NT_SUCCESS(status))
LOG_INFO_F(AntiCheatLogger::LogCategory::SYSTEM, "线程隐藏设置可能由于权限不足失败,NTSTATUS: 0x%08X", status);
else
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM, "监控线程已设置为对调试器隐藏");
}
else
{
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM, "NtSetInformationThread API 不可用,无法隐藏监控线程");
}
}
void CheatMonitorEngine::CheckParentProcessAtStartup()
{
DWORD parentPid = 0;
std::string parentName;
if (Utils::GetParentProcessInfo(parentPid, parentName))
{
std::transform(parentName.begin(), parentName.end(), parentName.begin(), ::tolower);
if (parentName != "loader.exe")
{
AddEvidence(anti_cheat::ENVIRONMENT_INVALID_PARENT_PROCESS,
"Invalid parent process: " + parentName + " (PID: " + std::to_string(parentPid) + ")");
}
}
else
{
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM, "Parent process not found - could be normal launcher behavior");
}
}
void CheatMonitorEngine::DetectVirtualMachine()
{
DetectVmByCpuid();
DetectVmByRegistry();
DetectVmByMacAddress();
}
void CheatMonitorEngine::DetectVmByCpuid()
{
std::array<int, 4> cpuid_info;
__cpuid(cpuid_info.data(), 1);
if ((cpuid_info[2] >> 31) & 1)
{
AddEvidence(anti_cheat::ENVIRONMENT_VIRTUAL_MACHINE, "检测到虚拟机环境 (CPUID hypervisor bit)");
}
__cpuid(cpuid_info.data(), 0x40000000);
std::string vendor_id;
vendor_id.append(reinterpret_cast<char *>(&cpuid_info[1]), 4);
vendor_id.append(reinterpret_cast<char *>(&cpuid_info[2]), 4);
vendor_id.append(reinterpret_cast<char *>(&cpuid_info[3]), 4);
if (vendor_id.find("VMware") != std::string::npos || vendor_id.find("KVMKVMKVM") != std::string::npos ||
vendor_id.find("VBoxVBoxVBox") != std::string::npos || vendor_id.find("Microsoft Hv") != std::string::npos)
{
AddEvidence(anti_cheat::ENVIRONMENT_VIRTUAL_MACHINE, "检测到虚拟机环境 (CPUID vendor ID: " + vendor_id + ")");
}
}
void CheatMonitorEngine::DetectVmByRegistry()
{
const wchar_t *vmKeys[] = {L"HARDWARE\\DESCRIPTION\\System\\BIOS\\SystemManufacturer",
L"HARDWARE\\DESCRIPTION\\System\\BIOS\\SystemProductName"};
const wchar_t *vmValues[] = {L"vmware", L"virtualbox", L"qemu", L"kvm", L"microsoft"};
for (const auto &key : vmKeys)
{
HKEY hKey;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
wchar_t buffer[256];
DWORD size = sizeof(buffer);
if (RegQueryValueExW(hKey, L"SystemManufacturer", NULL, NULL, (LPBYTE)buffer, &size) == ERROR_SUCCESS)
{
std::wstring manufacturer(buffer);
std::transform(manufacturer.begin(), manufacturer.end(), manufacturer.begin(), ::towlower);
for (const auto &vm : vmValues)
{
if (manufacturer.find(vm) != std::wstring::npos)
{
AddEvidence(anti_cheat::ENVIRONMENT_VIRTUAL_MACHINE,
"检测到虚拟机环境 (Registry: " + Utils::WideToString(manufacturer) + ")");
RegCloseKey(hKey);
return;
}
}
}
RegCloseKey(hKey);
}
}
}
void CheatMonitorEngine::DetectVmByMacAddress()
{
const std::vector<std::string> vmMacPrefixes = {"00:05:69", "00:0C:29", "00:1C:14",
"00:50:56", "08:00:27", "00:15:5D"};
ULONG bufferSize = sizeof(IP_ADAPTER_INFO);
std::vector<BYTE> buffer(bufferSize);
PIP_ADAPTER_INFO pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(buffer.data());
if (GetAdaptersInfo(pAdapterInfo, &bufferSize) == ERROR_BUFFER_OVERFLOW)
{
buffer.resize(bufferSize);
pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(buffer.data());
}
if (GetAdaptersInfo(pAdapterInfo, &bufferSize) == NO_ERROR)
{
while (pAdapterInfo)
{
char macStr[18];
sprintf_s(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X", pAdapterInfo->Address[0],
pAdapterInfo->Address[1], pAdapterInfo->Address[2], pAdapterInfo->Address[3],
pAdapterInfo->Address[4], pAdapterInfo->Address[5]);
for (const auto &prefix : vmMacPrefixes)
{
if (std::string(macStr).rfind(prefix, 0) == 0)
{
AddEvidence(anti_cheat::ENVIRONMENT_VIRTUAL_MACHINE,
"检测到虚拟机环境 (MAC Address: " + std::string(macStr) + ")");
return;
}
}
pAdapterInfo = pAdapterInfo->Next;
}
}
}
uintptr_t CheatMonitorEngine::FindVehListAddress()
{
PVOID pDecoyHandler = nullptr;
int retryCount = 0;
int maxRetries = 3;
while (!pDecoyHandler && retryCount < 3)
{
pDecoyHandler = AddVectoredExceptionHandler(1, SystemUtils::DecoyVehHandler);
if (!pDecoyHandler)
{
retryCount++;
if (retryCount < maxRetries) Sleep(300);
}
}
if (!pDecoyHandler) return 0;
uintptr_t listHeadAddress = 0;
__try
{
const auto *pEntry = reinterpret_cast<const VECTORED_HANDLER_ENTRY *>(pDecoyHandler);
const LIST_ENTRY *pCurrent = &pEntry->List;
for (int i = 0; i < 100; ++i)
{
const LIST_ENTRY *pBlink = pCurrent->Blink;
if (!SystemUtils::IsValidPointer(pBlink, sizeof(LIST_ENTRY)) ||
!SystemUtils::IsValidPointer(pBlink->Flink, sizeof(LIST_ENTRY *)))
break;
if (pBlink->Flink == pCurrent)
{
listHeadAddress = reinterpret_cast<uintptr_t>(pBlink);
break;
}
pCurrent = pBlink;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
listHeadAddress = 0;
}
RemoveVectoredExceptionHandler(pDecoyHandler);
if (listHeadAddress == 0) return 0;
uintptr_t structBaseAddress = 0;
SystemUtils::WindowsVersion ver = SystemUtils::GetWindowsVersion();
switch (ver)
{
case SystemUtils::WindowsVersion::Win_XP:
structBaseAddress = listHeadAddress - offsetof(VECTORED_HANDLER_LIST_XP, List);
break;
case SystemUtils::WindowsVersion::Win_Vista_Win7:
structBaseAddress = listHeadAddress - offsetof(VECTORED_HANDLER_LIST_VISTA, ExceptionList);
break;
default:
structBaseAddress = listHeadAddress - offsetof(VECTORED_HANDLER_LIST_WIN8, ExceptionList);
break;
}
LOG_INFO_F(AntiCheatLogger::LogCategory::SYSTEM, "Dynamically located VEH list structure at: 0x%p",
(void *)structBaseAddress);
return structBaseAddress;
}
VOID CALLBACK CheatMonitorEngine::DllLoadCallback(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA *NotificationData,
PVOID Context)
{
if (NotificationReason == LDR_DLL_NOTIFICATION_REASON_LOADED)
{
auto *impl = static_cast<CheatMonitorEngine *>(Context);
if (impl) impl->OnDllLoaded(NotificationData->Loaded);
}
}
void CheatMonitorEngine::RegisterDllNotification()
{
if (!SystemUtils::HasApiCapability(SystemUtils::ApiCapability::LdrDllNotification))
{
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM, "当前OS能力矩阵未启用 LdrDllNotification,跳过DLL通知注册。");
return;
}
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (!hNtdll) return;
auto pLdrRegisterDllNotification =
(P_LdrRegisterDllNotification)GetProcAddress(hNtdll, "LdrRegisterDllNotification");
if (pLdrRegisterDllNotification && !m_dllNotificationCookie)
{
pLdrRegisterDllNotification(0, DllLoadCallback, this, &m_dllNotificationCookie);
}
}
void CheatMonitorEngine::UnregisterDllNotification()
{
if (m_dllNotificationCookie)
{
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (hNtdll)
{
auto pLdrUnregisterDllNotification =
(P_LdrUnregisterDllNotification)GetProcAddress(hNtdll, "LdrUnregisterDllNotification");
if (pLdrUnregisterDllNotification)
{
pLdrUnregisterDllNotification(m_dllNotificationCookie);
}
}
m_dllNotificationCookie = nullptr;
}
}
void CheatMonitorEngine::OnDllLoaded(const LDR_DLL_LOAD_NOTIFICATION_DATA &data)
{
if (!data.FullDllName || !data.FullDllName->Buffer) return;
std::wstring modulePath(data.FullDllName->Buffer, data.FullDllName->Length / sizeof(WCHAR));
// If server config not yet received, cache the DLL load for later processing
if (!m_hasServerConfig.load())
{
std::lock_guard<std::mutex> lock(m_pendingDllLoadsMutex);
m_pendingDllLoads.emplace_back(modulePath, std::chrono::steady_clock::now());
return;
}
// Config available, check whitelist and report immediately
if (Utils::IsWhitelistedModule(modulePath)) return;
std::string pathStr = Utils::WideToString(modulePath);
LOG_WARNING_F(AntiCheatLogger::LogCategory::SENSOR, "Runtime DLL Loaded: %s", pathStr.c_str());
AddEvidence(anti_cheat::RUNTIME_MODULE_INJECTION, "Runtime DLL load detected: " + pathStr);
}
void CheatMonitorEngine::ProcessPendingDllLoads()
{
std::vector<std::pair<std::wstring, std::chrono::steady_clock::time_point>> pending;
{
std::lock_guard<std::mutex> lock(m_pendingDllLoadsMutex);
pending = std::move(m_pendingDllLoads);
m_pendingDllLoads.clear();
}
for (const auto& entry : pending)
{
const std::wstring& modulePath = entry.first;
if (Utils::IsWhitelistedModule(modulePath)) continue; // Filter by whitelist
std::string pathStr = Utils::WideToString(modulePath);
LOG_WARNING_F(AntiCheatLogger::LogCategory::SENSOR, "Runtime DLL Loaded (delayed): %s", pathStr.c_str());
AddEvidence(anti_cheat::RUNTIME_MODULE_INJECTION, "Runtime DLL load detected: " + pathStr);
}
}
void CheatMonitorEngine::OnProcessCreated(DWORD pid, const std::wstring &name)
{
std::wstring lowerName = name;
std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::towlower);
auto harmfulNames = CheatConfigManager::GetInstance().GetHarmfulProcessNames();
if (harmfulNames)
{
for (const auto &harmful : *harmfulNames)
{
if (lowerName.find(harmful) != std::wstring::npos)
{
std::string u8Name = Utils::WideToString(name);
LOG_WARNING_F(AntiCheatLogger::LogCategory::SENSOR, "WMI Monitor: Harmful process detected: %s (PID: %lu)",
u8Name.c_str(), pid);
AddEvidence(anti_cheat::RUNTIME_PROCESS_BLACKLIST, "Harmful process started: " + u8Name);
return;
}
}
}
}