-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCheatMonitorReporter.cpp
More file actions
496 lines (443 loc) · 20 KB
/
Copy pathCheatMonitorReporter.cpp
File metadata and controls
496 lines (443 loc) · 20 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
#include "CheatMonitor.h"
#include "CheatMonitorEngine.h"
#include "CheatConfigManager.h"
#include "Logger.h"
#include "utils/Utils.h"
#include "utils/CryptoUtils.h"
#include <atomic>
namespace
{
void CaptureSessionIdentity(CheatMonitorEngine &engine, uint32_t &userId, std::string &userName)
{
std::lock_guard<std::mutex> lock(engine.m_sessionMutex);
userId = engine.m_currentUserId;
userName = engine.m_currentUserName;
}
}
void CheatMonitorEngine::AddEvidence(anti_cheat::CheatCategory category, const std::string &description)
{
std::lock_guard<std::mutex> lock(m_sessionMutex);
if (m_evidenceOverflowed) return;
if (m_evidences.size() >= (size_t)CheatConfigManager::GetInstance().GetMaxEvidencesPerSession())
{
m_evidenceOverflowed = true;
anti_cheat::Evidence overflow_evidence;
overflow_evidence.set_client_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
overflow_evidence.set_category(anti_cheat::RUNTIME_ERROR);
overflow_evidence.set_description("Evidence buffer overflow. Further events for this session are suppressed.");
m_evidences.push_back(overflow_evidence);
return;
}
if (m_uniqueEvidence.find({category, description}) != m_uniqueEvidence.end()) return;
const auto now = std::chrono::steady_clock::now();
auto it = m_lastReported.find({m_currentUserId, category});
if (it != m_lastReported.end())
{
auto elapsed = std::chrono::duration_cast<std::chrono::minutes>(now - it->second);
if (elapsed < std::chrono::minutes(CheatConfigManager::GetInstance().GetReportCooldownMinutes())) return;
}
anti_cheat::Evidence evidence;
evidence.set_client_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
evidence.set_category(category);
evidence.set_description(description);
m_evidences.push_back(evidence);
m_uniqueEvidence.insert({category, description});
m_lastReported[{m_currentUserId, category}] = now;
LOG_WARNING_F(AntiCheatLogger::LogCategory::SECURITY, "Evidence added: %s", description.c_str());
}
void CheatMonitorEngine::UploadHardwareReport()
{
auto sendWithFingerprint = [&](std::unique_ptr<anti_cheat::HardwareFingerprint> fp) {
if (!fp)
{
fp = std::make_unique<anti_cheat::HardwareFingerprint>();
fp->set_os_version("ERROR:FingerprintNull");
}
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_HARDWARE);
auto hardware_report = report.mutable_hardware();
hardware_report->set_report_id(Utils::GenerateUuid());
hardware_report->set_report_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
*hardware_report->mutable_fingerprint() = *fp;
SendReport(report);
};
if (!m_hwCollector)
{
auto fp = std::make_unique<anti_cheat::HardwareFingerprint>();
fp->set_disk_serial("ERROR:CollectorNull");
fp->add_mac_addresses("ERROR:CollectorNull");
fp->set_computer_name("ERROR:CollectorNull");
fp->set_os_version("ERROR:CollectorNull");
fp->set_cpu_info("ERROR:CollectorNull");
sendWithFingerprint(std::move(fp));
return;
}
if (!m_hwCollector->GetFingerprint())
{
bool collected = m_hwCollector->EnsureCollected();
if (!collected && !m_hwCollector->GetFingerprint())
{
auto fp = std::make_unique<anti_cheat::HardwareFingerprint>();
fp->set_os_version("ERROR:EnsureCollectedFailed");
fp->add_mac_addresses("ERROR:EnsureCollectedFailed");
sendWithFingerprint(std::move(fp));
return;
}
}
const auto* fp_raw = m_hwCollector->GetFingerprint();
if (!fp_raw)
{
auto fallback = std::make_unique<anti_cheat::HardwareFingerprint>();
fallback->set_os_version("ERROR:GetFingerprintNull");
fallback->add_mac_addresses("ERROR:GetFingerprintNull");
sendWithFingerprint(std::move(fallback));
return;
}
auto fp = std::make_unique<anti_cheat::HardwareFingerprint>(*fp_raw);
if (fp->disk_serial().empty() && fp->mac_addresses().empty() && fp->computer_name().empty() && fp->cpu_info().empty())
{
fp->set_os_version("ERROR:FingerprintEmpty");
fp->add_mac_addresses("ERROR:FingerprintEmpty");
}
sendWithFingerprint(std::move(fp));
}
void CheatMonitorEngine::UploadTargetedSensorReport(const std::string &requestId, const std::string &sensorName,
SensorExecutionResult result,
anti_cheat::SensorFailureReason failureReason, int duration_ms,
const std::string ¬es,
const std::vector<anti_cheat::Evidence> &evidences)
{
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_TARGETED_SENSOR);
auto targeted = report.mutable_targeted_sensor();
targeted->set_request_id(requestId);
targeted->set_sensor_name(sensorName);
targeted->set_success(result == SensorExecutionResult::SUCCESS);
targeted->set_failure_reason(failureReason);
targeted->set_duration_ms(duration_ms >= 0 ? static_cast<uint64_t>(duration_ms) : 0);
targeted->set_notes(notes);
for (const auto &evidence : evidences)
{
*targeted->add_evidences() = evidence;
}
SendReport(report);
}
void CheatMonitorEngine::UploadEvidenceReport()
{
std::vector<anti_cheat::Evidence> evidencesToSend;
{
std::lock_guard<std::mutex> lock(m_sessionMutex);
if (m_evidences.empty()) return;
evidencesToSend.swap(m_evidences);
m_uniqueEvidence.clear();
}
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_EVIDENCE);
auto evidence_report = report.mutable_evidence();
evidence_report->set_report_id(Utils::GenerateUuid());
evidence_report->set_report_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
for (auto &evidence : evidencesToSend)
{
*evidence_report->add_evidences() = std::move(evidence);
}
SendReport(report);
}
void CheatMonitorEngine::UploadTelemetryMetricsReport(const anti_cheat::TelemetryMetrics &metrics)
{
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_TELEMETRY);
auto telemetry_report = report.mutable_telemetry();
telemetry_report->set_report_id(Utils::GenerateUuid());
telemetry_report->set_report_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
*telemetry_report->mutable_metrics() = metrics;
SendReport(report);
}
void CheatMonitorEngine::UploadSnapshotReport()
{
if (!CheatConfigManager::GetInstance().IsSnapshotUploadEnabled()) return;
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM, "开始采集快照数据...");
auto threads = CollectThreadSnapshots();
auto modules = CollectModuleSnapshots();
LOG_INFO_F(AntiCheatLogger::LogCategory::SYSTEM, "采集完成: %zu个线程, %zu个模块", threads.size(), modules.size());
uint32_t currentUserId = 0;
std::string currentUserName;
CaptureSessionIdentity(*this, currentUserId, currentUserName);
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_SNAPSHOT);
auto snapshot_report = report.mutable_snapshot();
snapshot_report->set_report_id(Utils::GenerateUuid());
snapshot_report->set_report_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
snapshot_report->set_user_id(currentUserId);
snapshot_report->set_user_name(currentUserName);
for (const auto &thread : threads) *snapshot_report->add_threads() = thread;
for (const auto &module : modules) *snapshot_report->add_modules() = module;
snapshot_report->set_total_thread_count(static_cast<uint32_t>(threads.size()));
snapshot_report->set_total_module_count(static_cast<uint32_t>(modules.size()));
SendReport(report);
LOG_INFO(AntiCheatLogger::LogCategory::SYSTEM, "快照数据上报完成");
}
void CheatMonitorEngine::UploadSensorExecutionStatsReport()
{
anti_cheat::TelemetryMetrics metrics;
{
std::lock_guard<std::mutex> lock(m_sensorStatsMutex);
for (const auto &kv : m_sensorExecutionStats)
{
const std::string &name = kv.first;
const auto &stats = kv.second;
bool nonEmpty = false;
if (stats.success_count() > 0 || stats.failure_count() > 0 || stats.timeout_count() > 0 ||
stats.total_success_time_ms() > 0 || stats.total_failure_time_ms() > 0 ||
stats.avg_success_time_ms() > 0 || stats.avg_failure_time_ms() > 0 || stats.max_success_time_ms() > 0 ||
stats.min_success_time_ms() > 0 || stats.max_failure_time_ms() > 0 || stats.min_failure_time_ms() > 0 ||
stats.workload_snapshot_size_total() > 0 || stats.workload_attempts_total() > 0 ||
stats.workload_hits_total() > 0 || stats.workload_last_snapshot_size() > 0 ||
stats.workload_last_attempts() > 0 || stats.workload_last_hits() > 0 ||
stats.diagnostic_counters_size() > 0 || stats.last_diagnostic_values_size() > 0)
{
nonEmpty = true;
}
if (!nonEmpty) continue;
(*metrics.mutable_sensor_execution_stats())[name] = stats;
}
m_sensorExecutionStats.clear();
}
UploadTelemetryMetricsReport(metrics);
}
void CheatMonitorEngine::RecordSensorExecutionStats(const char *name, int duration_ms, SensorExecutionResult result,
anti_cheat::SensorFailureReason failureReason)
{
std::lock_guard<std::mutex> lock(m_sensorStatsMutex);
auto &stats = m_sensorExecutionStats[name];
switch (result)
{
case SensorExecutionResult::SUCCESS:
stats.set_success_count(stats.success_count() + 1);
if (duration_ms > 0)
{
stats.set_total_success_time_ms(stats.total_success_time_ms() + duration_ms);
if (stats.total_success_time_ms() > 0 && stats.success_count() > 0)
stats.set_avg_success_time_ms(stats.total_success_time_ms() / stats.success_count());
if (stats.max_success_time_ms() == 0 || duration_ms > stats.max_success_time_ms())
stats.set_max_success_time_ms(duration_ms);
if (stats.min_success_time_ms() == 0 || duration_ms < stats.min_success_time_ms())
stats.set_min_success_time_ms(duration_ms);
}
break;
case SensorExecutionResult::FAILURE:
stats.set_failure_count(stats.failure_count() + 1);
if (duration_ms > 0)
{
stats.set_total_failure_time_ms(stats.total_failure_time_ms() + duration_ms);
if (stats.total_failure_time_ms() > 0 && stats.failure_count() > 0)
stats.set_avg_failure_time_ms(stats.total_failure_time_ms() / stats.failure_count());
if (stats.max_failure_time_ms() == 0 || duration_ms > stats.max_failure_time_ms())
stats.set_max_failure_time_ms(duration_ms);
if (stats.min_failure_time_ms() == 0 || duration_ms < stats.min_failure_time_ms())
stats.set_min_failure_time_ms(duration_ms);
}
break;
case SensorExecutionResult::TIMEOUT:
stats.set_timeout_count(stats.timeout_count() + 1);
break;
}
if (result == SensorExecutionResult::FAILURE && failureReason != anti_cheat::UNKNOWN_FAILURE)
{
(*stats.mutable_failure_reasons())[static_cast<int32_t>(failureReason)]++;
}
}
void CheatMonitorEngine::RecordSensorWorkloadCounters(const std::string &name, uint64_t snapshot_size, uint64_t attempts,
uint64_t hits)
{
std::lock_guard<std::mutex> lock(m_sensorStatsMutex);
auto &stats = m_sensorExecutionStats[name];
if (snapshot_size)
{
stats.set_workload_snapshot_size_total(stats.workload_snapshot_size_total() + snapshot_size);
stats.set_workload_last_snapshot_size(snapshot_size);
}
if (attempts)
{
stats.set_workload_attempts_total(stats.workload_attempts_total() + attempts);
stats.set_workload_last_attempts(attempts);
}
if (hits)
{
stats.set_workload_hits_total(stats.workload_hits_total() + hits);
stats.set_workload_last_hits(hits);
}
}
void CheatMonitorEngine::RecordSensorDiagnosticCounter(const std::string &name, const std::string &key, uint64_t delta)
{
if (delta == 0) return;
std::lock_guard<std::mutex> lock(m_sensorStatsMutex);
auto &stats = m_sensorExecutionStats[name];
(*stats.mutable_diagnostic_counters())[key] += delta;
}
void CheatMonitorEngine::RecordSensorDiagnosticValue(const std::string &name, const std::string &key,
const std::string &value)
{
std::lock_guard<std::mutex> lock(m_sensorStatsMutex);
auto &stats = m_sensorExecutionStats[name];
(*stats.mutable_last_diagnostic_values())[key] = value;
}
void CheatMonitorEngine::SendReport(const anti_cheat::Report &report)
{
std::string serialized_report;
if (!report.SerializeToString(&serialized_report))
{
LOG_WARNING_F(AntiCheatLogger::LogCategory::SYSTEM, "Failed to serialize report");
return;
}
const char *report_type_name = "Unknown";
size_t content_size = 0;
switch (report.type())
{
case anti_cheat::REPORT_HARDWARE:
report_type_name = "Hardware";
content_size = report.has_hardware() ? 1 : 0;
break;
case anti_cheat::REPORT_EVIDENCE:
report_type_name = "Evidence";
content_size = report.has_evidence() ? report.evidence().evidences_size() : 0;
break;
case anti_cheat::REPORT_TELEMETRY:
report_type_name = "Telemetry";
content_size = report.has_telemetry() ? 1 : 0;
break;
case anti_cheat::REPORT_SNAPSHOT:
report_type_name = "Snapshot";
content_size = report.has_snapshot() ? report.snapshot().threads_size() + report.snapshot().modules_size() : 0;
break;
case anti_cheat::REPORT_SERVER_LOG:
report_type_name = "ServerLog";
content_size = report.has_server_log() ? 1 : 0;
break;
case anti_cheat::REPORT_HEARTBEAT:
report_type_name = "Heartbeat";
content_size = report.has_heartbeat() ? 1 : 0;
break;
default:
break;
}
LOG_INFO_F(AntiCheatLogger::LogCategory::SYSTEM, "Uploading %s report... Size: %zu bytes, content items: %zu",
report_type_name, serialized_report.length(), content_size);
// --- 协议加固:增加序号、会话ID、时间戳与签名 ---
anti_cheat::Report signed_report = report;
signed_report.set_sequence_id(++m_sequenceId);
signed_report.set_session_id(m_sessionId);
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
signed_report.set_timestamp_ms(static_cast<uint64_t>(ms));
std::string hmac_key = CheatConfigManager::GetInstance().GetHmacKey();
if (!hmac_key.empty())
{
// 重新序列化以包含 sequence_id
std::string final_serialized;
if (signed_report.SerializeToString(&final_serialized))
{
std::vector<uint8_t> data(final_serialized.begin(), final_serialized.end());
std::string signature = CryptoUtils::CalculateHMAC_SHA256(data, hmac_key);
signed_report.set_signature(signature);
}
}
// 最终上报数据序列化
std::string upload_payload;
if (!signed_report.SerializeToString(&upload_payload))
{
LOG_ERROR(AntiCheatLogger::LogCategory::SYSTEM, "Failed to serialize signed report");
return;
}
// TODO: HttpSend(server_url, upload_payload);
}
void CheatMonitorEngine::FlushPendingReports()
{
std::deque<anti_cheat::Report> reportsToSend;
{
std::lock_guard<std::mutex> lock(m_reportQueueMutex);
if (m_pendingReports.empty())
{
return;
}
reportsToSend.swap(m_pendingReports);
}
while (!reportsToSend.empty())
{
anti_cheat::Report report = reportsToSend.front();
reportsToSend.pop_front();
// --- 协议加固:增加序号、会话ID、时间戳与签名 ---
anti_cheat::Report signed_report = report;
signed_report.set_sequence_id(++m_sequenceId);
signed_report.set_session_id(m_sessionId);
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
signed_report.set_timestamp_ms(static_cast<uint64_t>(ms));
std::string hmac_key = CheatConfigManager::GetInstance().GetHmacKey();
if (!hmac_key.empty())
{
// 重新序列化以包含 sequence_id
std::string final_serialized;
if (signed_report.SerializeToString(&final_serialized))
{
std::vector<uint8_t> data(final_serialized.begin(), final_serialized.end());
std::string signature = CryptoUtils::CalculateHMAC_SHA256(data, hmac_key);
signed_report.set_signature(signature);
}
}
// 最终上报数据序列化
std::string upload_payload;
if (!signed_report.SerializeToString(&upload_payload))
{
LOG_ERROR(AntiCheatLogger::LogCategory::SYSTEM, "Failed to serialize signed report inside FlushPendingReports");
continue;
}
// TODO: HttpSend(server_url, upload_payload);
}
}
void CheatMonitorEngine::UploadHeartbeatReport()
{
uint32_t currentUserId = 0;
std::string currentUserName;
CaptureSessionIdentity(*this, currentUserId, currentUserName);
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_HEARTBEAT);
auto heartbeat_report = report.mutable_heartbeat();
heartbeat_report->set_report_id(Utils::GenerateUuid());
heartbeat_report->set_report_timestamp_ms(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count());
heartbeat_report->set_user_id(currentUserId);
heartbeat_report->set_session_id(m_sessionId);
heartbeat_report->set_light_scan_count(m_lightScanCount.exchange(0));
heartbeat_report->set_heavy_scan_count(m_heavyScanCount.exchange(0));
SendReport(report);
}
void CheatMonitorEngine::SendServerLog(const std::string &log_level, const std::string &log_category,
const std::string &log_message)
{
anti_cheat::Report report;
report.set_type(anti_cheat::REPORT_SERVER_LOG);
static std::atomic<uint64_t> log_counter{0};
std::string report_id = "LOG_" + std::to_string(++log_counter);
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
anti_cheat::ServerLogReport *server_log = report.mutable_server_log();
server_log->set_report_id(report_id);
server_log->set_report_timestamp_ms(ms);
server_log->set_log_level(log_level);
server_log->set_log_category(log_category);
server_log->set_log_message(log_message);
SendReport(report);
}