using System; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Security.Cryptography; using System.Diagnostics; using System.Runtime.InteropServices; using System.Collections.Generic; using Microsoft.Win32; namespace LegitAuth { /// /// LegitAuth Response Object /// public class Response { public bool success { get; set; } = false; public string message { get; set; } = string.Empty; } /// /// Authenticated User Metadata /// public class UserData { public string username { get; set; } = string.Empty; public string expires_at { get; set; } = string.Empty; public string hwid { get; set; } = string.Empty; public string rank { get; set; } = "Member"; public string ip { get; set; } = string.Empty; public string created_at { get; set; } = string.Empty; } /// /// Application Global Metadata /// public class AppData { public string app_name { get; set; } = string.Empty; public string version { get; set; } = string.Empty; public string dev_message { get; set; } = string.Empty; public bool status_enabled { get; set; } = true; } /// /// LegitAuth Universal High-Performance C# Client SDK (v2.5) /// 100% Native AOT Compatible | Zero Reflection | .NET Framework 4.5+ to .NET 9 Compatible /// public static class LegitAuthApp { public static string name { get; set; } = string.Empty; public static string ownerid { get; set; } = string.Empty; public static string secret { get; set; } = string.Empty; public static string version { get; set; } = "1.0.0"; public static Response response { get; set; } = new Response(); public static UserData user_data { get; set; } = new UserData(); public static AppData app_data { get; set; } = new AppData(); public static string dev_message { get; set; } = string.Empty; public static string server_version { get; set; } = string.Empty; private static bool initialized = false; private static readonly HttpClient client; private static string _apiUrl = "https://legitauth.site/api/client"; public static string apiUrl { get => _apiUrl; set => _apiUrl = value != null ? value.TrimEnd('/') : "https://legitauth.site/api/client"; } // Blacklisted Reverse Engineering, Debugger & Cracking Tool Signatures private static readonly string[] BlacklistedProcesses = new string[] { "x64dbg", "x32dbg", "x96dbg", "cheatengine-x86_64", "cheatengine-i386", "cheat engine", "cheatengine", "httpdebuggerui", "httpdebuggersvc", "httpdebugger", "httpdebuggermemoryanalyzer", "dnspy", "dnspy-x86", "processhacker", "processhacker2", "ida", "ida64", "idaq", "idaq64", "wireshark", "fiddler", "ollydbg", "scylla_x64", "scylla_x86", "scylla", "pestudio", "de4dot", "ilspy", "megadumper", "extremedumper", "ghidra", "titanengine", "titanhide", "hxd", "reclass.net", "simpleassemblyexplorer" }; private static readonly string[] BlacklistedWindowClasses = new string[] { "Qt5QWindowIcon", "OLLYDBG", "PROC_EXPLORER", "CheatEngine", "IDA_QT_WINDOW", "Zeta Debugger", "WinDbgFrameClass", "ProcessHacker" }; private static readonly string[] BlacklistedModules = new string[] { "scylla.dll", "titanengine.dll", "httpdebugger.dll", "vehdebug-x86_64.dll", "vehdebug-i386.dll", "hooking.dll", "x64dbg.dll", "x32dbg.dll", "cheatengine.dll" }; [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] private static extern bool IsDebuggerPresent(); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] private static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr FindWindowA(string lpClassName, string lpWindowName); [DllImport("user32.dll", EntryPoint = "MessageBoxW", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type); static LegitAuthApp() { try { // Force modern TLS 1.2 & TLS 1.3 across all .NET Framework & Windows versions ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)12288 | SecurityProtocolType.Tls12; ServicePointManager.DefaultConnectionLimit = 64; ServicePointManager.Expect100Continue = false; } catch { } var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) }; client.DefaultRequestHeaders.Add("User-Agent", "LegitAuth-NativeClient/2.5"); } private static bool _autoProtect = true; /// /// Initialize LegitAuth with application credentials /// public static void init(string _name, string _ownerid, string _secret, string _version = "auto", bool autoProtect = true) { name = _name ?? string.Empty; ownerid = _ownerid ?? string.Empty; secret = _secret ?? string.Empty; if (string.IsNullOrWhiteSpace(_version) || _version.Equals("auto", StringComparison.OrdinalIgnoreCase)) { try { var asm = System.Reflection.Assembly.GetEntryAssembly() ?? System.Reflection.Assembly.GetExecutingAssembly(); var v = asm?.GetName()?.Version; if (v != null && (v.Major > 0 || v.Minor > 0 || v.Build > 0)) { version = $"{v.Major}.{v.Minor}.{(v.Build >= 0 ? v.Build : 0)}"; } else { var proc = System.Diagnostics.Process.GetCurrentProcess(); var fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(proc.MainModule.FileName); version = !string.IsNullOrEmpty(fvi.ProductVersion) ? fvi.ProductVersion : (!string.IsNullOrEmpty(fvi.FileVersion) ? fvi.FileVersion : "1.0.0"); } } catch { version = "1.0.0"; } } else { version = _version; } _autoProtect = autoProtect; initialized = true; response.success = true; response.message = "Initialized Successfully"; // Spawn background security watchdog thread if enabled if (autoProtect) { ScanAntiTamper(); try { Thread sentinelThread = new Thread(SentinelWatchdogLoop) { IsBackground = true, Name = "LegitAuthWatchdog" }; sentinelThread.Start(); } catch { } } } /// /// Authenticate user via Username and Password (Async) /// public static async Task login(string username, string password) { if (!CheckInit()) return; string hwid = GetHWID(); string jsonPayload = $"{{\"owner_id\":\"{EscapeJson(ownerid)}\",\"secret\":\"{EscapeJson(secret)}\",\"app_name\":\"{EscapeJson(name)}\",\"username\":\"{EscapeJson(username)}\",\"password\":\"{EscapeJson(password)}\",\"hwid\":\"{EscapeJson(hwid)}\"}}"; await SendAuthRequestAsync("/login", jsonPayload, "Login successful!"); } /// /// Authenticate user via Username and Password (Synchronous helper) /// public static bool login_sync(string username, string password) { try { Task.Run(() => login(username, password)).GetAwaiter().GetResult(); return response.success; } catch (Exception ex) { response.success = false; response.message = $"Sync execution error: {ex.Message}"; return false; } } /// /// Authenticate user via License Key (Async) /// public static async Task license(string key) { if (!CheckInit()) return; string hwid = GetHWID(); string jsonPayload = $"{{\"owner_id\":\"{EscapeJson(ownerid)}\",\"secret\":\"{EscapeJson(secret)}\",\"app_name\":\"{EscapeJson(name)}\",\"license_key\":\"{EscapeJson(key)}\",\"hwid\":\"{EscapeJson(hwid)}\"}}"; await SendAuthRequestAsync("/login", jsonPayload, "License verified successfully!"); } /// /// Authenticate user via License Key (Synchronous helper) /// public static bool license_sync(string key) { try { Task.Run(() => license(key)).GetAwaiter().GetResult(); return response.success; } catch (Exception ex) { response.success = false; response.message = $"Sync execution error: {ex.Message}"; return false; } } /// /// Register a new user account with License Key (Async) /// public static async Task register(string username, string password, string key) { if (!CheckInit()) return; string hwid = GetHWID(); string jsonPayload = $"{{\"owner_id\":\"{EscapeJson(ownerid)}\",\"secret\":\"{EscapeJson(secret)}\",\"app_name\":\"{EscapeJson(name)}\",\"username\":\"{EscapeJson(username)}\",\"password\":\"{EscapeJson(password)}\",\"license_key\":\"{EscapeJson(key)}\",\"hwid\":\"{EscapeJson(hwid)}\"}}"; await SendAuthRequestAsync("/register", jsonPayload, "Registered successfully!"); } /// /// Register a new user account with License Key (Synchronous helper) /// public static bool register_sync(string username, string password, string key) { try { Task.Run(() => register(username, password, key)).GetAwaiter().GetResult(); return response.success; } catch (Exception ex) { response.success = false; response.message = $"Sync execution error: {ex.Message}"; return false; } } /// /// Verify active session and connection integrity (Async) /// public static async Task check_session() { if (!CheckInit()) return; string hwid = GetHWID(); string jsonPayload = $"{{\"owner_id\":\"{EscapeJson(ownerid)}\",\"secret\":\"{EscapeJson(secret)}\",\"app_name\":\"{EscapeJson(name)}\",\"username\":\"{EscapeJson(user_data.username)}\",\"hwid\":\"{EscapeJson(hwid)}\"}}"; await SendAuthRequestAsync("/session-check", jsonPayload, "Session is active."); } /// /// Log action or telemetry string to LegitAuth Console (Async) /// public static async Task log(string message) { if (!CheckInit()) return; try { string jsonPayload = $"{{\"owner_id\":\"{EscapeJson(ownerid)}\",\"secret\":\"{EscapeJson(secret)}\",\"app_name\":\"{EscapeJson(name)}\",\"username\":\"{EscapeJson(user_data.username)}\",\"message\":\"{EscapeJson(message)}\"}}"; var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); await client.PostAsync($"{_apiUrl}/log", content); } catch { } } /// /// Perform zero-reflection HTTP request and parse response safely for Native AOT /// private static async Task SendAuthRequestAsync(string endpoint, string jsonPayload, string defaultSuccessMsg) { try { var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); var apiResponse = await client.PostAsync($"{_apiUrl}{endpoint}", content); string responseBody = await apiResponse.Content.ReadAsStringAsync(); var jsonMap = LegitJson.Parse(responseBody); bool isSuccess = jsonMap.ContainsKey("success") && jsonMap["success"].Equals("true", StringComparison.OrdinalIgnoreCase); if (apiResponse.IsSuccessStatusCode && isSuccess) { response.success = true; response.message = jsonMap.ContainsKey("message") && !string.IsNullOrEmpty(jsonMap["message"]) ? jsonMap["message"] : defaultSuccessMsg; if (jsonMap.ContainsKey("dev_message")) dev_message = jsonMap["dev_message"]; if (jsonMap.ContainsKey("version")) server_version = jsonMap["version"]; // Parse nested user data without reflection if (jsonMap.ContainsKey("user.username")) user_data.username = jsonMap["user.username"]; else if (jsonMap.ContainsKey("username")) user_data.username = jsonMap["username"]; if (jsonMap.ContainsKey("user.expires_at")) user_data.expires_at = jsonMap["user.expires_at"]; else if (jsonMap.ContainsKey("expires_at")) user_data.expires_at = jsonMap["expires_at"]; if (jsonMap.ContainsKey("user.hwid")) user_data.hwid = jsonMap["user.hwid"]; if (jsonMap.ContainsKey("user.ip")) user_data.ip = jsonMap["user.ip"]; } else { response.success = false; // Extract exact custom message or backend detail if (jsonMap.ContainsKey("message") && !string.IsNullOrEmpty(jsonMap["message"])) { response.message = jsonMap["message"]; } else if (jsonMap.ContainsKey("detail") && !string.IsNullOrEmpty(jsonMap["detail"])) { response.message = jsonMap["detail"]; } else if (jsonMap.ContainsKey("error") && !string.IsNullOrEmpty(jsonMap["error"])) { response.message = jsonMap["error"]; } else { response.message = $"Authentication failed (HTTP {(int)apiResponse.StatusCode}: {apiResponse.ReasonPhrase})"; } // Auto-popup native MessageBox when app is in Maintenance Mode if ((int)apiResponse.StatusCode == 503 || response.message.ToLower().Contains("maintenance") || response.message.ToLower().Contains("paused")) { try { MessageBox(IntPtr.Zero, response.message, $"{name} - Maintenance Notice", 0x30); } catch { } } } } catch (HttpRequestException httpEx) { response.success = false; response.message = $"Network Connection Error: {httpEx.Message}"; } catch (TaskCanceledException) { response.success = false; response.message = "Connection timeout: Server took too long to respond."; } catch (Exception ex) { response.success = false; response.message = $"Security Error: {ex.Message}"; } } private static bool CheckInit() { if (!initialized) { response.success = false; response.message = "LegitAuth has not been initialized. Please call LegitAuthApp.init(...) first."; return false; } return true; } /// /// High-Performance Robust Hardware ID (HWID) Generator /// Multi-layer fallbacks: Registry MachineGuid -> System Profile -> SHA-256 64-char Hash /// public static string GetHWID() { try { string rawHwid = string.Empty; // Layer 1: Windows 64-bit Registry MachineGuid try { using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\Microsoft\Cryptography")) { if (key != null) { object val = key.GetValue("MachineGuid"); if (val != null) { rawHwid = val.ToString().Trim(); } } } } catch { } // Layer 2: Windows 32-bit Registry MachineGuid fallback if (string.IsNullOrEmpty(rawHwid)) { try { using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Cryptography")) { if (key != null) { object val = key.GetValue("MachineGuid"); if (val != null) { rawHwid = val.ToString().Trim(); } } } } catch { } } // Layer 3: Legacy Registry fallback if (string.IsNullOrEmpty(rawHwid)) { try { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography")) { if (key != null) { object val = key.GetValue("MachineGuid"); if (val != null) { rawHwid = val.ToString().Trim(); } } } } catch { } } // Layer 4: Universal Hardware Fallback if (string.IsNullOrEmpty(rawHwid)) { rawHwid = Environment.MachineName.Trim() + "_LEGIT_HWID_" + Environment.ProcessorCount; } // Compute standard cryptographic SHA-256 digest using (SHA256 sha256 = SHA256.Create()) { byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(rawHwid.Trim())); StringBuilder builder = new StringBuilder(64); for (int i = 0; i < bytes.Length; i++) { builder.Append(bytes[i].ToString("x2")); } return builder.ToString(); } } catch { return "LEGIT_DEFAULT_HWID_FALLBACK"; } } /// /// Active Anti-Tamper, Debugger & Memory Cracking Detection Engine /// public static void ScanAntiTamper() { if (!_autoProtect) return; try { // Check if running under Visual Studio managed debugging bool isVsDebugging = Debugger.IsAttached; // 1. Win32 Local Debugger Present (Ignore if Visual Studio IDE debugger) if (!isVsDebugging && IsDebuggerPresent()) { ReportTamperAndKill("Win32 Native Debugger Attached (IsDebuggerPresent)", "Native debugger detected attached to process."); } // 2. Win32 Remote Kernel Debugger Present if (!isVsDebugging) { bool isRemote = false; try { CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref isRemote); if (isRemote) { ReportTamperAndKill("Remote Debugger Attached (CheckRemoteDebuggerPresent)", "Remote kernel debugger attached."); } } catch { } } // 3. Window Class Name Heuristic Scanner foreach (string badClass in BlacklistedWindowClasses) { try { if (FindWindowA(badClass, null) != IntPtr.Zero) { ReportTamperAndKill($"Cracking Window Class Detected: {badClass}", $"Debugger/Sniffer window class '{badClass}' active on desktop."); break; } } catch { } } // 4. Scan Active Processes for Blacklisted Cracking / Sniffing Tools Process[] processes = Process.GetProcesses(); foreach (Process p in processes) { try { string pName = p.ProcessName.ToLower(); foreach (string blacklisted in BlacklistedProcesses) { if (pName.Contains(blacklisted)) { ReportTamperAndKill($"Cracking Tool Detected: {p.ProcessName}.exe", $"Process '{p.ProcessName}' found running."); break; } } } catch { } } // 5. Scan Loaded Process Modules for Injected DLLs try { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; foreach (ProcessModule mod in modules) { string mName = mod.ModuleName.ToLower(); foreach (string badMod in BlacklistedModules) { if (mName.Contains(badMod)) { ReportTamperAndKill($"Injected Hooking Module Detected: {mod.ModuleName}", $"Unauthorized DLL '{mod.ModuleName}' injected into process space."); break; } } } } catch { } } catch { } } private static void SentinelWatchdogLoop() { while (true) { try { ScanAntiTamper(); } catch { } Thread.Sleep(2500); } } private static string _lastReportedThreat = string.Empty; private static DateTime _lastReportedTime = DateTime.MinValue; private static void ReportTamperAndKill(string threatTool, string details, bool forceKill = true) { try { // Debounce: Avoid sending duplicate alerts for the same threat within 60 seconds if (_lastReportedThreat != threatTool || (DateTime.UtcNow - _lastReportedTime).TotalSeconds >= 60) { _lastReportedThreat = threatTool; _lastReportedTime = DateTime.UtcNow; string hwid = GetHWID(); string userOrKey = !string.IsNullOrEmpty(user_data.username) ? user_data.username : "Pre-Auth Client"; string jsonPayload = $"{{\"owner_id\":\"{EscapeJson(ownerid)}\",\"secret\":\"{EscapeJson(secret)}\",\"app_name\":\"{EscapeJson(name)}\",\"threat_tool\":\"{EscapeJson(threatTool)}\",\"file_type\":\"C# Executable (Windows x64)\",\"hwid\":\"{EscapeJson(hwid)}\",\"username_or_key\":\"{EscapeJson(userOrKey)}\",\"details\":\"{EscapeJson(details)}\"}}"; var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); var alertTask = client.PostAsync($"{_apiUrl}/tamper-alert", content); alertTask.Wait(1200); } } catch { } finally { if (forceKill) { try { Process.GetCurrentProcess().Kill(); } catch { } Environment.Exit(0); } } } private static readonly string CredentialFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "legitauth_creds.dat"); /// /// Auto-Save credentials to local encrypted storage /// public static void SaveCredentials(string username, string password) { try { string data = $"{username}\n{password}"; File.WriteAllText(CredentialFile, Convert.ToBase64String(Encoding.UTF8.GetBytes(data))); } catch { } } /// /// Auto-Load credentials from local encrypted storage /// public static void LoadCredentials(out string username, out string password) { username = string.Empty; password = string.Empty; try { if (File.Exists(CredentialFile)) { string base64 = File.ReadAllText(CredentialFile).Trim(); string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(base64)); string[] lines = decoded.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length >= 2) { username = lines[0].Trim(); password = lines[1].Trim(); } } } catch { } } private static string EscapeJson(string s) { if (string.IsNullOrEmpty(s)) return string.Empty; return s.Replace("\\", "\\\\") .Replace("\"", "\\\"") .Replace("\r", "\\r") .Replace("\n", "\\n") .Replace("\t", "\\t"); } } /// /// Zero-Reflection, Zero-NuGet Native JSON Parser /// 100% Compatible with Native AOT, Trimming, and All .NET Versions /// internal static class LegitJson { public static Dictionary Parse(string json) { var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrEmpty(json)) return dict; json = json.Trim(); ParseObjectRecursive(json, string.Empty, dict); return dict; } private static void ParseObjectRecursive(string json, string prefix, Dictionary dict) { if (string.IsNullOrEmpty(json)) return; json = json.Trim(); if (json.StartsWith("{") && json.EndsWith("}")) { json = json.Substring(1, json.Length - 2).Trim(); } int index = 0; while (index < json.Length) { // Skip whitespaces & commas while (index < json.Length && (char.IsWhiteSpace(json[index]) || json[index] == ',')) index++; if (index >= json.Length) break; // Read Key if (json[index] != '"') { index++; continue; } index++; // Skip opening quote int keyStart = index; while (index < json.Length && json[index] != '"') { if (json[index] == '\\') index++; index++; } if (index >= json.Length) break; string key = json.Substring(keyStart, index - keyStart); index++; // Skip closing quote // Find Colon while (index < json.Length && json[index] != ':') index++; if (index >= json.Length) break; index++; // Skip colon // Skip spaces while (index < json.Length && char.IsWhiteSpace(json[index])) index++; if (index >= json.Length) break; string fullKey = string.IsNullOrEmpty(prefix) ? key : $"{prefix}.{key}"; // Read Value if (json[index] == '"') { index++; // Skip opening quote int valStart = index; StringBuilder valSb = new StringBuilder(); while (index < json.Length) { if (json[index] == '\\' && index + 1 < json.Length) { char next = json[index + 1]; if (next == '"') { valSb.Append('"'); index += 2; continue; } if (next == '\\') { valSb.Append('\\'); index += 2; continue; } if (next == 'n') { valSb.Append('\n'); index += 2; continue; } if (next == 'r') { valSb.Append('\r'); index += 2; continue; } if (next == 't') { valSb.Append('\t'); index += 2; continue; } } if (json[index] == '"') break; valSb.Append(json[index]); index++; } if (index < json.Length) index++; // Skip closing quote dict[fullKey] = valSb.ToString(); dict[key] = valSb.ToString(); // Also store without prefix for convenience } else if (json[index] == '{') { // Nested Object int startObj = index; int braceCount = 0; while (index < json.Length) { if (json[index] == '{') braceCount++; if (json[index] == '}') braceCount--; index++; if (braceCount == 0) break; } string subJson = json.Substring(startObj, index - startObj); ParseObjectRecursive(subJson, fullKey, dict); } else { // Primitive (boolean, number, null) int valStart = index; while (index < json.Length && json[index] != ',' && json[index] != '}' && !char.IsWhiteSpace(json[index])) { index++; } string val = json.Substring(valStart, index - valStart).Trim(); dict[fullKey] = val; dict[key] = val; } } } } /// /// Backward Compatibility Alias for Legacy Projects /// public static class AXCAuthApp { public static void init(string _name, string _ownerid, string _secret, string _version = "auto", bool autoProtect = true) => LegitAuthApp.init(_name, _ownerid, _secret, _version, autoProtect); public static Response response { get => LegitAuthApp.response; set => LegitAuthApp.response = value; } public static UserData user_data { get => LegitAuthApp.user_data; set => LegitAuthApp.user_data = value; } public static string dev_message { get => LegitAuthApp.dev_message; set => LegitAuthApp.dev_message = value; } public static string server_version { get => LegitAuthApp.server_version; set => LegitAuthApp.server_version = value; } public static Task login(string username, string password) => LegitAuthApp.login(username, password); public static Task license(string key) => LegitAuthApp.license(key); public static Task register(string username, string password, string key) => LegitAuthApp.register(username, password, key); public static Task check_session() => LegitAuthApp.check_session(); } }