### Initialize and Configure Anti-Debugging in C++ Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Demonstrates how to instantiate the DebuggerDetections class, start the monitoring thread, and perform manual debugger checks. It covers both automated background monitoring and manual execution of specific detection routines. ```cpp #include "AntiDebug/DebuggerDetections.hpp" void SetupAntiDebugging(Settings* config, EvidenceLocker* evidence) { DebuggerDetections* antiDebug = new DebuggerDetections(config, evidence); antiDebug->StartAntiDebugThread(); } void PerformDebuggerChecks(DebuggerDetections* antiDebug) { antiDebug->RunDetectionFunctions(); Thread* hwDebugThread = new Thread( (LPTHREAD_START_ROUTINE)&Debugger::AntiDebug::_IsHardwareDebuggerPresent, antiDebug, false, true ); if (antiDebug->IsDBK64DriverLoaded()) { Logger::logf(Detection, "DBVM debugger driver detected!"); } } ``` -------------------------------- ### Start Automated Cheat Detection Monitoring Thread in C++ Source: https://context7.com/alsch092/ultimateanticheat/llms.txt This C++ code snippet shows how to initiate the automated cheat detection monitoring thread using the Detections class. The `StartMonitor` method starts a background thread that continuously checks for various cheating indicators, including module integrity, process events, registry changes, DLL signatures, and open handles. It logs a success message upon starting. ```cpp #include "Core/Detections.hpp" // Start the automated monitor thread void StartMonitoring(Detections* monitor) { if (monitor->StartMonitor()) { Logger::logf(Info, "Detection monitor started successfully"); // Monitor thread is now running and checking: // - Module integrity checksums // - Process creation events // - Registry key modifications // - DLL signature verification // - Open handle detection } } ``` -------------------------------- ### Get Machine Identification Information (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Retrieves and logs the hostname, MAC address, and hardware ID of the machine using the NetClient. This function is static for hostname retrieval and instance-based for MAC and HWID. Requires a NetClient instance. ```cpp // Get machine identification info void GetMachineInfo(NetClient* client) { std::string hostname = NetClient::GetHostname(); std::string macAddr = client->GetMACAddress(); std::string hwid = client->GetHardwareID(); Logger::logf(Info, "Hostname: %s", hostname.c_str()); Logger::logf(Info, "MAC: %s", macAddr.c_str()); Logger::logf(Info, "HWID: %s", hwid.c_str()); } ``` -------------------------------- ### Implement TLS Callback for Thread Validation Source: https://context7.com/alsch092/ultimateanticheat/llms.txt This snippet demonstrates a Windows TLS callback that executes during process and thread initialization. It performs anti-debugging tasks, prevents duplicate process instances, and validates thread start addresses to block unauthorized execution. ```cpp #include #include "Process/Process.hpp" #include "Core/Preventions.hpp" #pragma comment (linker, "/INCLUDE:_tls_used") #pragma comment (linker, "/INCLUDE:_tls_callback") void NTAPI __stdcall TLSCallback(PVOID pHandle, DWORD dwReason, PVOID Reserved); EXTERN_C #ifdef _M_X64 #pragma const_seg (".CRT$XLB") const #endif PIMAGE_TLS_CALLBACK _tls_callback = TLSCallback; #pragma data_seg () #pragma const_seg () void ExitThreadGracefully() { } void NTAPI __stdcall TLSCallback(PVOID pHandle, DWORD dwReason, PVOID Reserved) { const uintptr_t ThreadStackOffset = 0x378; static bool FirstAttach = true; switch (dwReason) { case DLL_PROCESS_ATTACH: { if (!Preventions::StopMultipleProcessInstances()) { terminate(); } if (FirstAttach) { SetUnhandledExceptionFilter(ExceptionHandler); AddVectoredExceptionHandler(1, ExceptionHandler); FirstAttach = false; } break; } case DLL_THREAD_ATTACH: { Debugger::AntiDebug::HideThreadFromDebugger(GetCurrentThread()); uintptr_t* stackSlot = (uintptr_t*)(_AddressOfReturnAddress()) + ThreadStackOffset; uintptr_t threadStartAddr = *stackSlot; if (threadStartAddr == 0) return; auto modules = Process::GetLoadedModules(); bool validThread = false; for (const auto& mod : modules) { uintptr_t base = (uintptr_t)mod.dllInfo.lpBaseOfDll; uintptr_t end = base + mod.dllInfo.SizeOfImage; if (threadStartAddr >= base && threadStartAddr < end) { validThread = true; break; } } if (!validThread) { Logger::logf(Detection, "Blocking unknown thread: %d", GetCurrentThreadId()); *stackSlot = (uintptr_t)&ExitThreadGracefully; } break; } case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } } ``` -------------------------------- ### Initialize AntiCheat System in C++ Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Demonstrates the main entry point for the UltimateAntiCheat system. It configures settings, creates a protected memory region for settings, initializes the AntiCheat class, and includes a basic application loop with checks for thread suspension and cheater detection. It also includes error handling for initialization failures. ```cpp #include "Core/AntiCheat.hpp" #include "Common/Settings.hpp" #include "AntiTamper/MapProtectedClass.hpp" int main() { // Configure anti-cheat settings const std::string serverIP = "127.0.0.1"; const uint16_t serverPort = 5445; const bool bEnableNetworking = false; const bool bEnforceSecureBoot = true; const bool bEnforceDSE = true; const bool bEnforceNoKDBG = true; const bool bUseAntiDebugging = true; const bool bUseIntegrityChecking = true; const bool bCheckThreadIntegrity = true; const bool bCheckHypervisor = false; const bool bRequireRunAsAdministrator = true; const bool bUsingDriver = false; const bool bEnableLogging = true; const std::wstring DriverCertSubject = L"YourGameCompany"; const std::list allowedParents = {L"explorer.exe", L"powershell.exe"}; const std::string logFileName = "UltimateAnticheat.log"; // Create protected settings memory region ProtectedMemory ProtectedSettingsMemory(sizeof(Settings)); Settings* Config = ProtectedSettingsMemory.Construct( serverIP, serverPort, bEnableNetworking, bEnforceSecureBoot, bEnforceDSE, bEnforceNoKDBG, bUseAntiDebugging, bUseIntegrityChecking, bCheckThreadIntegrity, bCheckHypervisor, bRequireRunAsAdministrator, bUsingDriver, DriverCertSubject, allowedParents, bEnableLogging, logFileName ); ProtectedSettingsMemory.Protect(); // Make settings write-protected try { // Create AntiCheat instance - automatically initializes all protections std::unique_ptr AC = std::make_unique(Config); // Check if any critical threads were suspended by attacker if (AC->IsAnyThreadSuspended()) { // Handle tampering detection Logger::logf(Detection, "Critical thread suspended!"); } // Main application loop while (running) { // Your game logic here // Check if cheating was detected if (AC->GetMonitor()->IsUserCheater()) { // Handle cheater detection auto flags = AC->GetMonitor()->GetDetectedFlags(); for (auto flag : flags) { Logger::logf(Detection, "Cheat flag detected: %d", flag); } } } // Cleanup on exit AC->FastCleanup(); } catch (const AntiCheatInitFail& e) { Logger::logf(Err, "AntiCheat init failed: %d - %s", e.reasonEnum, e.what()); return 1; } return 0; } ``` -------------------------------- ### Initialize NetClient and Connect to Server (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Initializes the NetClient with server details and a license key. It establishes a connection and logs success or failure. Dependencies include Settings and Logger classes. ```cpp #include "Network/NetClient.hpp" // Initialize network client void SetupNetworking(Settings* config) { NetClient* client = new NetClient(); // Initialize connection with license key Error result = client->Initialize( config->serverIP, config->serverPort, "GAMECODE-MYGAME123" // License/game code ); if (result != Error::OK) { Logger::logf(Err, "Failed to connect to server"); return; } if (client->HandshakeCompleted) { Logger::logf(Info, "Connected to %s:%d", client->GetConnectedIP().c_str(), client->GetConnectedPort()); } } ``` -------------------------------- ### Initialize and Access Anti-Cheat Settings in C++ Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Demonstrates the instantiation of the Settings object with various security flags and network parameters. It also shows how to retrieve and utilize these settings to verify system state and process whitelists. ```cpp #include "Common/Settings.hpp" // Create settings with full configuration Settings* CreateAntiCheatConfig() { return new Settings( "192.168.1.100", // serverIP - Server endpoint for heartbeat 5445, // serverPort - Network port true, // bNetworkingEnabled - Enable client-server comms true, // bEnforceSecureBoot - Require UEFI secure boot true, // bEnforceDSE - Require driver signature enforcement true, // bEnforceNoKDbg - Block kernel debugging true, // bUseAntiDebugging - Enable anti-debug checks true, // bCheckIntegrity - Enable memory integrity checks true, // bCheckThreads - Monitor thread integrity false, // bCheckHypervisor - Detect hypervisors true, // bRequireRunAsAdministrator - Require admin rights false, // bUsingDriver - Use kernelmode driver L"YourCompany", // DriverSignerSubject - Expected driver signer {L"explorer.exe"}, // allowedParents - Whitelisted parent processes true, // bEnableLogging - Enable logging "anticheat.log" // logFileName - Log file path ); } // Access settings properties void CheckSettings(Settings* config) { if (config->bNetworkingEnabled) { std::cout << "Server: " << config->serverIP << ":" << config->serverPort << std::endl; } if (config->bUsingDriver) { std::wcout << L"Driver path: " << config->GetKMDriverPath() << std::endl; std::wcout << L"Driver name: " << config->GetKMDriverName() << std::endl; } for (const auto& parent : config->allowedParents) { std::wcout << L"Allowed parent: " << parent << std::endl; } } ``` -------------------------------- ### Deploy All Protections (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Deploys all configured prevention techniques within the Preventions class. It returns an error code indicating success or failure in applying the barrier techniques. This function is essential for initializing the anti-cheat's core defenses. ```cpp #include "Core/Preventions.hpp" // Deploy all prevention techniques void DeployAllProtections(Preventions* barrier) { Error result = barrier->DeployBarrier(); if (result == Error::OK) { Logger::logf(Info, "All barrier techniques applied successfully"); } else { Logger::logf(Err, "Failed to apply some barrier techniques"); } } ``` -------------------------------- ### Encapsulate Library Logic with PIMPL Idiom Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Demonstrates the PIMPL (Pointer to Implementation) idiom to hide private members and implementation details from library consumers. This approach improves compilation times and maintains binary compatibility. ```cpp // AntiCheatLib.hpp #include "Common/Settings.hpp" class AntiCheat final { private: struct Impl; Impl* pImpl; public: explicit AntiCheat(Settings* config); void Destroy(); AntiCheat(const AntiCheat&) = delete; AntiCheat& operator=(const AntiCheat&) = delete; }; // Usage Example #include "AntiCheatLib.hpp" class GameApplication { private: AntiCheat* anticheat = nullptr; public: bool Initialize() { Settings* config = new Settings("", 0, false, true, true, true, true, true, true, false, false, false, L"", {L"explorer.exe"}, true, "game.log"); try { anticheat = new AntiCheat(config); return true; } catch (const AntiCheatInitFail& e) { return false; } } void Shutdown() { if (anticheat) { anticheat->Destroy(); delete anticheat; anticheat = nullptr; } } }; ``` -------------------------------- ### Manage Module Checksum Storage Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Shows how to retrieve and store module checksum data to maintain a baseline for future integrity comparisons. ```cpp void ManageChecksums(Integrity* checker) { HMODULE hMod = GetModuleHandle(L"ntdll.dll"); uintptr_t storedChecksum = checker->RetrieveModuleChecksum(hMod, ".text"); ModuleChecksumData moduleData; moduleData.hMod = hMod; moduleData.Name = L"ntdll.dll"; moduleData.SectionChecksums[".text"] = storedChecksum; checker->StoreModuleChecksum(moduleData); } ``` -------------------------------- ### Query and Send Memory Data (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Queries a specified memory address for a given number of bytes and sends the data to the server. Requires a NetClient instance and valid memory parameters. The data is transmitted securely. ```cpp // Send memory query response void QueryAndSendMemory(NetClient* client) { // Query specific memory address and send bytes to server client->QueryMemory( 0x00400000, // Address to read 256 // Size in bytes ); } ``` -------------------------------- ### Configure Thread Creation Prevention (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Configures and enables thread creation blocking using TLS callbacks. It also includes functionality to randomize the module name to evade enumeration. This helps in preventing unauthorized thread execution and detection. ```cpp // Control thread creation prevention void ConfigureThreadPrevention(Preventions* barrier) { // Enable thread creation blocking via TLS callback barrier->SetThreadCreationPrevention(true); if (barrier->IsPreventingThreads()) { Logger::logf(Info, "Unknown thread creation will be blocked"); } // Randomize module name to evade enumeration if (barrier->RandomizeModuleName()) { Logger::logf(Info, "Module name randomized successfully"); } } ``` -------------------------------- ### Report Detection Flags to Server (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Sends detection flags to the server, with options for simple flags or detailed reports including additional data and process IDs. Requires a valid NetClient instance. Returns an Error code indicating success or failure. ```cpp // Send detection flags to server void ReportCheater(NetClient* client, DetectionFlags flag) { // Simple flag report Error result = client->FlagCheater(flag); // Flag with additional data and process ID result = client->FlagCheater( DetectionFlags::EXTERNAL_ILLEGAL_PROGRAM, "CheatEngine.exe", // Additional data 1234 // Suspicious process ID ); if (result == Error::OK) { Logger::logf(Info, "Detection reported to server"); } } ``` -------------------------------- ### Apply Individual Protections (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Applies individual prevention techniques such as remapping program sections, blocking APC injection, preventing multiple process instances, and enabling Windows process mitigations. It also includes functionality to unload blacklisted drivers. ```cpp // Remap program sections to prevent memory patching // Creates copy-on-write pages that detect modifications if (Preventions::RemapProgramSections()) { Logger::logf(Info, "Program sections remapped successfully"); } // Block APC injection by patching ntdll.Ordinal8 if (Preventions::StopAPCInjection()) { Logger::logf(Info, "APC injection blocked"); } // Prevent multiple process instances using shared memory if (Preventions::StopMultipleProcessInstances()) { Logger::logf(Info, "Multi-client prevention active"); } else { Logger::logf(Err, "Another instance already running!"); exit(1); } // Enable Windows process mitigation policies (Windows 8+) #if _WIN32_WINNT >= 0x0602 Preventions::EnableProcessMitigations( true, // useDEP - Data Execution Prevention true, // useASLR - Address Space Layout Randomization false, // useDynamicCode - Block dynamic code generation true, // useStrictHandles - Strict handle validation true // useSystemCallDisable - Block Win32k syscalls ); #endif // Unload known malicious drivers std::list blacklistedDrivers = {L"DBK64.sys", L"malicious.sys"}; Preventions::UnloadBlacklistedDrivers(blacklistedDrivers); ``` -------------------------------- ### Manual Cheat Detection Checks in C++ Source: https://context7.com/alsch092/ultimateanticheat/llms.txt This C++ code demonstrates how to perform various manual cheat detection checks using the Detections class. It covers detecting blacklisted processes and windows, checking for external process handles, identifying IAT and function hooks, detecting manual mapping, verifying process remapping, and finding writable code sections. It logs any detected violations. ```cpp #include "Core/Detections.hpp" // Detection methods can be called directly or run via the monitor thread void ManualDetectionChecks(Detections* monitor) { // Check for blacklisted processes running on the system if (monitor->IsBlacklistedProcessRunning()) { Logger::logf(Detection, "Blacklisted cheat process detected!"); } // Check for blacklisted window titles (cheat tool windows) if (monitor->IsBlacklistedWindowPresent()) { Logger::logf(Detection, "Blacklisted window detected!"); } // Check for open handles to our process (external cheats) if (Detections::CheckOpenHandles()) { Logger::logf(Detection, "External process has handle to our process!"); } // Check for IAT hooking if (Detections::DoesIATContainHooked()) { auto hookedEntries = Detections::FetchHookedIATEntries(); for (const auto& entry : hookedEntries) { Logger::logf(Detection, "Hooked IAT entry: %s", entry.name.c_str()); } } // Check for function hooks on specific APIs if (Detections::DoesFunctionAppearHooked("kernel32.dll", "VirtualProtect")) { Logger::logf(Detection, "VirtualProtect appears to be hooked!"); } // Detect manual mapping (shellcode/injected modules) auto manualMaps = Detections::DetectManualMapping(); if (!manualMaps.empty()) { for (auto addr : manualMaps) { Logger::logf(Detection, "Manual mapped module at: 0x%llX", addr); } } // Check if process remapping was bypassed if (Detections::WasProcessNotRemapped()) { Logger::logf(Detection, "Section remapping was bypassed!"); } // Find writable pages in code sections (indicates tampering) uint64_t writableAddr = Detections::FindWritableAddress("game.exe", ".text"); if (writableAddr != 0) { Logger::logf(Detection, "Writable .text page found at: 0x%llX", writableAddr); } // Get all detected flags if (monitor->IsUserCheater()) { auto flags = monitor->GetDetectedFlags(); Logger::logf(Info, "Total violations: %zu", flags.size()); } } ``` -------------------------------- ### Configure CMake Build System for UltimateAnticheat Source: https://github.com/alsch092/ultimateanticheat/blob/main/CMakeLists.txt This script sets up the C++14 environment, collects source files recursively, and configures build targets. It includes logic for handling MSVC/Clang compiler-specific definitions, linking external libraries, and managing post-build tasks like asset copying. ```cmake cmake_minimum_required(VERSION 3.13) project(UltimateAnticheat VERSION 1.0) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED True) set(EXECUTABLE_NAME "UltimateAntiCheat.exe") set(LIB_DIR "${CMAKE_SOURCE_DIR}/Libs") file(GLOB_RECURSE SOURCES "*.cpp") file(GLOB_RECURSE HEADERS "*.h" "*.hpp") file(GLOB_RECURSE RESOURCES "*.aps" "*.rc") list(FILTER SOURCES EXCLUDE REGEX ".*CMakeCXXCompilerId.cpp$") add_executable(UltimateAnticheat ${SOURCES} ${HEADERS} ${RESOURCES}) target_sources(UltimateAnticheat PRIVATE "${CMAKE_SOURCE_DIR}/Obscure/ASMStubs.asm") target_compile_definitions(UltimateAnticheat PUBLIC _MAIN_MODULE_NAME="${EXECUTABLE_NAME}") if(MSVC) target_compile_definitions(UltimateAnticheat PRIVATE _CRT_SECURE_NO_WARNINGS) target_compile_options(UltimateAnticheat PRIVATE /W3) endif() target_link_libraries(UltimateAnticheat PRIVATE ntdll.lib "${LIB_DIR}/brotlicommon.lib") add_custom_command(TARGET UltimateAnticheat POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/splash.png" $/splash.png ) ``` -------------------------------- ### Perform Memory Integrity Checks and Tamper Detection Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Demonstrates how to calculate section checksums, compare them against disk images, identify writable code sections, and detect unauthorized modifications in loaded modules using the Integrity class. ```cpp #include "AntiTamper/Integrity.hpp" void UseIntegrityChecker(std::shared_ptr checker) { uintptr_t checksum = Integrity::CalculateChecksumFromSection("game.exe", ".text"); Logger::logf(Info, ".text checksum: 0x%llX", checksum); uintptr_t cachedChecksum = 0xDEADBEEF; if (!Integrity::CompareChecksum("game.exe", ".text", cachedChecksum)) { Logger::logf(Detection, ".text section has been modified!"); } if (!Integrity::CompareChecksumToFileOnDisc(L"game.exe", ".text", cachedChecksum)) { Logger::logf(Detection, "Module differs from disk image!"); } uintptr_t writableAddr = Integrity::FindWritableAddress("kernel32.dll", ".text"); if (writableAddr != 0) { Logger::logf(Detection, "Writable code at: 0x%llX", writableAddr); } auto modules = Process::GetLoadedModules(); uintptr_t suspiciousAddr = 0x12345678; if (!Integrity::IsAddressInModule(modules, suspiciousAddr)) { Logger::logf(Detection, "Address not in any loaded module!"); } if (Integrity::IsTLSCallbackStructureModified()) { Logger::logf(Detection, "TLS callback structure was modified!"); } auto violations = checker->GetViolations(); for (const auto& v : violations) { Logger::logfw(Detection, L"Violation in %s.%s at 0x%llX: %s", v.module.c_str(), v.section.c_str(), v.address, v.description.c_str()); } } ``` -------------------------------- ### Gracefully Disconnect from Server (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Initiates a graceful disconnection from the server. The function takes an error code to indicate the reason for disconnection. Requires a NetClient instance. ```cpp // Graceful disconnect void Disconnect(NetClient* client) { client->EndConnection(0); // 0 = normal disconnect } ``` -------------------------------- ### Send Custom Data Packet (C++) Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Constructs and sends a custom data packet to the server using PacketWriter. The packet includes an opcode and arbitrary data. Requires a NetClient instance and a populated PacketWriter. ```cpp // Send custom packet void SendCustomData(NetClient* client) { PacketWriter packet; packet.WriteInt16(CS_HELLO); // Opcode packet.WriteString("CustomData"); packet.WriteInt32(12345); client->SendData(&packet); } ``` -------------------------------- ### Prevent Debugger Attachment and Add Custom Detection Source: https://context7.com/alsch092/ultimateanticheat/llms.txt Provides methods to hide threads from debuggers, patch Windows debugger entry points, and register custom detection logic via lambda functions. ```cpp void PreventDebugging() { Debugger::AntiDebug::HideThreadFromDebugger(GetCurrentThread()); Debugger::AntiDebug::HideAllThreadsFromDebugger(); if (Debugger::AntiDebug::PreventWindowsDebuggers()) { Logger::logf(Info, "Debugger entry points patched"); } } void AddCustomDetection(DebuggerDetections* antiDebug) { antiDebug->AddDetectionFunction([]() -> DetectionFlags { if (IsDebuggerPresent()) { return DetectionFlags::DEBUG_WINAPI_DEBUGGER; } return DetectionFlags::NONE; }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.