diff --git a/Console/KeyAuth.cs b/Console/KeyAuth.cs index c374181..d28841a 100644 --- a/Console/KeyAuth.cs +++ b/Console/KeyAuth.cs @@ -33,6 +33,11 @@ public class api private static extern ushort GlobalFindAtom(string lpString); public string name, ownerid, version, path, seed; + + private static readonly object _sigLock = new object(); + private static readonly object _sessionLock = new object(); + private static readonly object _networkLock = new object(); + /// /// Set up your application credentials in order to use keyauth /// @@ -56,7 +61,7 @@ public api(string name, string ownerid, string version, string path = null) this.version = version; - this.path = path; + this.path = path; } #region structures @@ -157,65 +162,68 @@ private class app_data_structure /// public void init() { - Random random = new Random(); - - // Generate a random length for the string (let's assume between 5 and 50 characters) - int length = random.Next(5, 51); // Min length: 5, Max length: 50 + lock (_sessionLock) + { + Random random = new Random(); - StringBuilder sb = new StringBuilder(length); + // Generate a random length for the string (let's assume between 5 and 50 characters) + int length = random.Next(5, 51); // Min length: 5, Max length: 50 - // Define the range of printable ASCII characters (32-126) - for (int i = 0; i < length; i++) - { - // Generate a random printable ASCII character - char randomChar = (char)random.Next(32, 127); // ASCII 32 to 126 - sb.Append(randomChar); - } + StringBuilder sb = new StringBuilder(length); - seed = sb.ToString(); - checkAtom(); + // Define the range of printable ASCII characters (32-126) + for (int i = 0; i < length; i++) + { + // Generate a random printable ASCII character + char randomChar = (char)random.Next(32, 127); // ASCII 32 to 126 + sb.Append(randomChar); + } - var values_to_upload = new NameValueCollection - { - ["type"] = "init", - ["ver"] = version, - ["hash"] = checksum(Process.GetCurrentProcess().MainModule.FileName), - ["name"] = name, - ["ownerid"] = ownerid - }; + seed = sb.ToString(); + checkAtom(); - if (!string.IsNullOrEmpty(path)) - { - values_to_upload.Add("token", File.ReadAllText(path)); - values_to_upload.Add("thash", TokenHash(path)); - } + var values_to_upload = new NameValueCollection + { + ["type"] = "init", + ["ver"] = version, + ["hash"] = checksum(Process.GetCurrentProcess().MainModule.FileName), + ["name"] = name, + ["ownerid"] = ownerid + }; + + if (!string.IsNullOrEmpty(path)) + { + values_to_upload.Add("token", File.ReadAllText(path)); + values_to_upload.Add("thash", TokenHash(path)); + } - var response = req(values_to_upload); + var response = req(values_to_upload); - if (response == "KeyAuth_Invalid") - { - error("Application not found"); - TerminateProcess(GetCurrentProcess(), 1); - } + if (response == "KeyAuth_Invalid") + { + error("Application not found"); + TerminateProcess(GetCurrentProcess(), 1); + } - var json = response_decoder.string_to_generic(response); - if (json.ownerid == ownerid) - { - load_response_struct(json); - if (json.success) + var json = response_decoder.string_to_generic(response); + if (json.ownerid == ownerid) { - sessionid = json.sessionid; - initialized = true; + load_response_struct(json); + if (json.success) + { + sessionid = json.sessionid; + initialized = true; + } + else if (json.message == "invalidver") + { + app_data.downloadLink = json.download; + } } - else if (json.message == "invalidver") + else { - app_data.downloadLink = json.download; + TerminateProcess(GetCurrentProcess(), 1); } } - else - { - TerminateProcess(GetCurrentProcess(), 1); - } } void checkAtom() @@ -240,15 +248,15 @@ void checkAtom() public static string TokenHash(string tokenPath) { - using (var sha256 = SHA256.Create()) - { + using (var sha256 = SHA256.Create()) + { using (var s = File.OpenRead(tokenPath)) { - byte[] bytes = sha256.ComputeHash(s); - return BitConverter.ToString(bytes).Replace("-", string.Empty); + byte[] bytes = sha256.ComputeHash(s); + return BitConverter.ToString(bytes).Replace("-", string.Empty); } } - } + } /// /// Checks if Keyauth is been Initalized /// @@ -266,7 +274,7 @@ public void CheckInit() /// /// Subscription Number /// You can choose between Days,Hours,Months - public string expirydaysleft(string Type,int subscription) + public string expirydaysleft(string Type, int subscription) { CheckInit(); @@ -372,7 +380,7 @@ public void login(string username, string pass, string code = null) ["sessionid"] = sessionid, ["name"] = name, ["ownerid"] = ownerid, - ["code"] = code ?? string.Empty + ["code"] = code ?? null }; var response = req(values_to_upload); @@ -393,8 +401,8 @@ public void login(string username, string pass, string code = null) } } - public void logout() - { + public void logout() + { CheckInit(); var values_to_upload = new NameValueCollection @@ -426,7 +434,7 @@ public void web_login() string datastore, datastore2, outputten; - start: + start: HttpListener listener = new HttpListener(); @@ -617,7 +625,7 @@ public void license(string key, string code = null) ["sessionid"] = sessionid, ["name"] = name, ["ownerid"] = ownerid, - ["code"] = code ?? string.Empty + ["code"] = code ?? null }; var response = req(values_to_upload); @@ -685,8 +693,6 @@ public void disable2fa(string code) var json = response_decoder.string_to_generic(response); load_response_struct(json); - - Console.WriteLine(json.message); } /// /// Enable two factor authentication (2fa) @@ -711,23 +717,20 @@ public void enable2fa(string code = null) if (json.success) { - if (code == null) + if (code == null) // First time enabling 2FA, no code provided { - Console.WriteLine($"Your 2FA Secret is: {json.twoFactor.SecretCode}"); + // Display the secret code to the user + Clipboard.SetText(json.twoFactor.SecretCode); + System.Windows.MessageBox.Show($"Your 2FA Secret Code has been copied to your clipboard! \n\n: {json.twoFactor.SecretCode}", "2FA Secret"); - Console.Write("Enter the 6 digit authentication code from your authentication app: "); - string code6Digit = Console.ReadLine(); - this.enable2fa(code6Digit); } - else + else // Code provided by the user { - Console.WriteLine("2FA has been successfully enabled!"); - Thread.Sleep(3000); + System.Windows.MessageBox.Show("2FA has been successfully enabled!", "2FA Setup"); } } else { - Console.WriteLine($"Error: {json.message}"); Thread.Sleep(3000); TerminateProcess(GetCurrentProcess(), 1); } @@ -1137,7 +1140,7 @@ public static void error(string message) } File.AppendAllText(file, DateTime.Now + $" > {message}" + Environment.NewLine); - + Process.Start(new ProcessStartInfo("cmd.exe", $"/c start cmd /C \"color b && title Error && echo {message} && timeout /t 5\"") { CreateNoWindow = true, @@ -1147,49 +1150,52 @@ public static void error(string message) }); TerminateProcess(GetCurrentProcess(), 1); } - + private static string req(NameValueCollection post_data) { - try + lock (_networkLock) { - using (WebClient client = new WebClient()) + try { - client.Proxy = null; + using (WebClient client = new WebClient()) + { + client.Proxy = null; - ServicePointManager.ServerCertificateValidationCallback += assertSSL; + ServicePointManager.ServerCertificateValidationCallback += assertSSL; - var raw_response = client.UploadValues("https://keyauth.win/api/1.3/", post_data); + var raw_response = client.UploadValues("https://keyauth.win/api/1.3/", post_data); - ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; + ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; - sigCheck(Encoding.UTF8.GetString(raw_response), client.ResponseHeaders, post_data.Get(0)); + sigCheck(Encoding.UTF8.GetString(raw_response), client.ResponseHeaders, post_data.Get(0)); - Logger.LogEvent(Encoding.Default.GetString(raw_response) + "\n"); + Logger.LogEvent(Encoding.Default.GetString(raw_response) + "\n"); - return Encoding.Default.GetString(raw_response); + return Encoding.Default.GetString(raw_response); + } } - } - catch (WebException webex) - { - var response = (HttpWebResponse)webex.Response; - switch (response.StatusCode) + catch (WebException webex) { - case (HttpStatusCode)429: // client hit our rate limit - error("You're connecting too fast to loader, slow down."); - Logger.LogEvent("You're connecting too fast to loader, slow down."); - TerminateProcess(GetCurrentProcess(), 1); - return ""; - default: // site won't resolve. you should use keyauth.uk domain since it's not blocked by any ISPs - error("Connection failure. Please try again, or contact us for help."); - Logger.LogEvent("Connection failure. Please try again, or contact us for help."); - TerminateProcess(GetCurrentProcess(), 1); - return ""; + var response = (HttpWebResponse)webex.Response; + switch (response.StatusCode) + { + case (HttpStatusCode)429: // client hit our rate limit + error("You're connecting too fast to loader, slow down."); + Logger.LogEvent("You're connecting too fast to loader, slow down."); + TerminateProcess(GetCurrentProcess(), 1); + return ""; + default: // site won't resolve. you should use keyauth.uk domain since it's not blocked by any ISPs + error("Connection failure. Please try again, or contact us for help."); + Logger.LogEvent("Connection failure. Please try again, or contact us for help."); + TerminateProcess(GetCurrentProcess(), 1); + return ""; + } } } } private static bool assertSSL(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) - { + { if ((!certificate.Issuer.Contains("Google Trust Services") && !certificate.Issuer.Contains("Let's Encrypt")) || sslPolicyErrors != SslPolicyErrors.None) { error("SSL assertion fail, make sure you're not debugging Network. Disable internet firewall on router if possible. & echo: & echo If not, ask the developer of the program to use custom domains to fix this."); @@ -1201,60 +1207,63 @@ private static bool assertSSL(object sender, X509Certificate certificate, X509Ch private static void sigCheck(string resp, WebHeaderCollection headers, string type) { - if(type == "log" || type == "file" || type == "2faenable" || type == "2fadisable") // log doesn't return a response. + if (type == "log" || type == "file") // log doesn't return a response. { return; } - - try + lock (_sigLock) { - string signature = headers["x-signature-ed25519"]; - string timestamp = headers["x-signature-timestamp"]; - // Try to parse the input string to a long Unix timestamp - if (!long.TryParse(timestamp, out long unixTimestamp)) + try { - TerminateProcess(GetCurrentProcess(), 1); - } + string signature = headers["x-signature-ed25519"]; + string timestamp = headers["x-signature-timestamp"]; - // Convert the Unix timestamp to a DateTime object (in UTC) - DateTime timestampTime = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime; + // Try to parse the input string to a long Unix timestamp + if (!long.TryParse(timestamp, out long unixTimestamp)) + { + TerminateProcess(GetCurrentProcess(), 1); + } - // Get the current UTC time - DateTime currentTime = DateTime.UtcNow; + // Convert the Unix timestamp to a DateTime object (in UTC) + DateTime timestampTime = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime; - // Calculate the difference between the current time and the timestamp - TimeSpan timeDifference = currentTime - timestampTime; + // Get the current UTC time + DateTime currentTime = DateTime.UtcNow; - // Check if the timestamp is within 20 seconds of the current time - if (timeDifference.TotalSeconds > 20) - { - TerminateProcess(GetCurrentProcess(), 1); - } + // Calculate the difference between the current time and the timestamp + TimeSpan timeDifference = currentTime - timestampTime; + + // Check if the timestamp is within 20 seconds of the current time + if (timeDifference.TotalSeconds > 20) + { + TerminateProcess(GetCurrentProcess(), 1); + } - var byteSig = encryption.str_to_byte_arr(signature); - var byteKey = encryption.str_to_byte_arr("5586b4bc69c7a4b487e4563a4cd96afd39140f919bd31cea7d1c6a1e8439422b"); - // ... read the body from the request ... - // ... add the timestamp and convert it to a byte[] ... - string body = timestamp + resp; - var byteBody = Encoding.Default.GetBytes(body); + var byteSig = encryption.str_to_byte_arr(signature); + var byteKey = encryption.str_to_byte_arr("5586b4bc69c7a4b487e4563a4cd96afd39140f919bd31cea7d1c6a1e8439422b"); + // ... read the body from the request ... + // ... add the timestamp and convert it to a byte[] ... + string body = timestamp + resp; + var byteBody = Encoding.Default.GetBytes(body); - Console.Write(" Authenticating"); // there's also ... dots being created inside the CheckValid() function BELOW + Console.Write(" Authenticating"); // there's also ... dots being created inside the CheckValid() function BELOW - bool signatureValid = Ed25519.CheckValid(byteSig, byteBody, byteKey); // the ... dots in the console are from this function! - if (!signatureValid) + bool signatureValid = Ed25519.CheckValid(byteSig, byteBody, byteKey); // the ... dots in the console are from this function! + if (!signatureValid) + { + error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); + Logger.LogEvent(resp + "\n"); + TerminateProcess(GetCurrentProcess(), 1); + } + } + catch { error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); Logger.LogEvent(resp + "\n"); TerminateProcess(GetCurrentProcess(), 1); } } - catch - { - error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); - Logger.LogEvent(resp + "\n"); - TerminateProcess(GetCurrentProcess(), 1); - } } #region app_data @@ -1334,7 +1343,7 @@ private void load_response_struct(response_structure data) { response.success = data.success; response.message = data.message; - } + } #endregion private json_wrapper response_decoder = new json_wrapper(new response_structure()); diff --git a/Form/KeyAuth.cs b/Form/KeyAuth.cs index 21be223..7ebf5e9 100644 --- a/Form/KeyAuth.cs +++ b/Form/KeyAuth.cs @@ -34,6 +34,11 @@ public class api private static extern ushort GlobalFindAtom(string lpString); public string name, ownerid, version, path, seed; + + private static readonly object _sigLock = new object(); + private static readonly object _sessionLock = new object(); + private static readonly object _networkLock = new object(); + /// /// Set up your application credentials in order to use keyauth /// @@ -158,65 +163,68 @@ private class app_data_structure /// public void init() { - Random random = new Random(); + lock (_sessionLock) + { + Random random = new Random(); - // Generate a random length for the string (let's assume between 5 and 50 characters) - int length = random.Next(5, 51); // Min length: 5, Max length: 50 + // Generate a random length for the string (let's assume between 5 and 50 characters) + int length = random.Next(5, 51); // Min length: 5, Max length: 50 - StringBuilder sb = new StringBuilder(length); + StringBuilder sb = new StringBuilder(length); - // Define the range of printable ASCII characters (32-126) - for (int i = 0; i < length; i++) - { - // Generate a random printable ASCII character - char randomChar = (char)random.Next(32, 127); // ASCII 32 to 126 - sb.Append(randomChar); - } - - seed = sb.ToString(); - checkAtom(); + // Define the range of printable ASCII characters (32-126) + for (int i = 0; i < length; i++) + { + // Generate a random printable ASCII character + char randomChar = (char)random.Next(32, 127); // ASCII 32 to 126 + sb.Append(randomChar); + } - var values_to_upload = new NameValueCollection - { - ["type"] = "init", - ["ver"] = version, - ["hash"] = checksum(Process.GetCurrentProcess().MainModule.FileName), - ["name"] = name, - ["ownerid"] = ownerid - }; + seed = sb.ToString(); + checkAtom(); - if (!string.IsNullOrEmpty(path)) - { - values_to_upload.Add("token", File.ReadAllText(path)); - values_to_upload.Add("thash", TokenHash(path)); - } + var values_to_upload = new NameValueCollection + { + ["type"] = "init", + ["ver"] = version, + ["hash"] = checksum(Process.GetCurrentProcess().MainModule.FileName), + ["name"] = name, + ["ownerid"] = ownerid + }; + + if (!string.IsNullOrEmpty(path)) + { + values_to_upload.Add("token", File.ReadAllText(path)); + values_to_upload.Add("thash", TokenHash(path)); + } - var response = req(values_to_upload); + var response = req(values_to_upload); - if (response == "KeyAuth_Invalid") - { - error("Application not found"); - TerminateProcess(GetCurrentProcess(), 1); - } + if (response == "KeyAuth_Invalid") + { + error("Application not found"); + TerminateProcess(GetCurrentProcess(), 1); + } - var json = response_decoder.string_to_generic(response); - if (json.ownerid == ownerid) - { - load_response_struct(json); - if (json.success) + var json = response_decoder.string_to_generic(response); + if (json.ownerid == ownerid) { - sessionid = json.sessionid; - initialized = true; + load_response_struct(json); + if (json.success) + { + sessionid = json.sessionid; + initialized = true; + } + else if (json.message == "invalidver") + { + app_data.downloadLink = json.download; + } } - else if (json.message == "invalidver") + else { - app_data.downloadLink = json.download; + TerminateProcess(GetCurrentProcess(), 1); } } - else - { - TerminateProcess(GetCurrentProcess(), 1); - } } void checkAtom() @@ -1146,40 +1154,43 @@ public static void error(string message) private static string req(NameValueCollection post_data) { - try + lock (_networkLock) { - using (WebClient client = new WebClient()) + try { - client.Proxy = null; + using (WebClient client = new WebClient()) + { + client.Proxy = null; - ServicePointManager.ServerCertificateValidationCallback += assertSSL; + ServicePointManager.ServerCertificateValidationCallback += assertSSL; - var raw_response = client.UploadValues("https://keyauth.win/api/1.3/", post_data); + var raw_response = client.UploadValues("https://keyauth.win/api/1.3/", post_data); - ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; + ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; - sigCheck(Encoding.UTF8.GetString(raw_response), client.ResponseHeaders, post_data.Get(0)); + sigCheck(Encoding.UTF8.GetString(raw_response), client.ResponseHeaders, post_data.Get(0)); - Logger.LogEvent(Encoding.Default.GetString(raw_response) + "\n"); + Logger.LogEvent(Encoding.Default.GetString(raw_response) + "\n"); - return Encoding.Default.GetString(raw_response); + return Encoding.Default.GetString(raw_response); + } } - } - catch (WebException webex) - { - var response = (HttpWebResponse)webex.Response; - switch (response.StatusCode) + catch (WebException webex) { - case (HttpStatusCode)429: // client hit our rate limit - error("You're connecting too fast to loader, slow down."); - Logger.LogEvent("You're connecting too fast to loader, slow down."); - TerminateProcess(GetCurrentProcess(), 1); - return ""; - default: // site won't resolve. you should use keyauth.uk domain since it's not blocked by any ISPs - error("Connection failure. Please try again, or contact us for help."); - Logger.LogEvent("Connection failure. Please try again, or contact us for help."); - TerminateProcess(GetCurrentProcess(), 1); - return ""; + var response = (HttpWebResponse)webex.Response; + switch (response.StatusCode) + { + case (HttpStatusCode)429: // client hit our rate limit + error("You're connecting too fast to loader, slow down."); + Logger.LogEvent("You're connecting too fast to loader, slow down."); + TerminateProcess(GetCurrentProcess(), 1); + return ""; + default: // site won't resolve. you should use keyauth.uk domain since it's not blocked by any ISPs + error("Connection failure. Please try again, or contact us for help."); + Logger.LogEvent("Connection failure. Please try again, or contact us for help."); + TerminateProcess(GetCurrentProcess(), 1); + return ""; + } } } } @@ -1201,56 +1212,59 @@ private static void sigCheck(string resp, WebHeaderCollection headers, string ty { return; } - - try + lock (_sigLock) { - string signature = headers["x-signature-ed25519"]; - string timestamp = headers["x-signature-timestamp"]; - // Try to parse the input string to a long Unix timestamp - if (!long.TryParse(timestamp, out long unixTimestamp)) + try { - TerminateProcess(GetCurrentProcess(), 1); - } + string signature = headers["x-signature-ed25519"]; + string timestamp = headers["x-signature-timestamp"]; + + // Try to parse the input string to a long Unix timestamp + if (!long.TryParse(timestamp, out long unixTimestamp)) + { + TerminateProcess(GetCurrentProcess(), 1); + } - // Convert the Unix timestamp to a DateTime object (in UTC) - DateTime timestampTime = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime; + // Convert the Unix timestamp to a DateTime object (in UTC) + DateTime timestampTime = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime; - // Get the current UTC time - DateTime currentTime = DateTime.UtcNow; + // Get the current UTC time + DateTime currentTime = DateTime.UtcNow; - // Calculate the difference between the current time and the timestamp - TimeSpan timeDifference = currentTime - timestampTime; + // Calculate the difference between the current time and the timestamp + TimeSpan timeDifference = currentTime - timestampTime; - // Check if the timestamp is within 20 seconds of the current time - if (timeDifference.TotalSeconds > 20) - { - TerminateProcess(GetCurrentProcess(), 1); - } + // Check if the timestamp is within 20 seconds of the current time + if (timeDifference.TotalSeconds > 20) + { + TerminateProcess(GetCurrentProcess(), 1); + } - var byteSig = encryption.str_to_byte_arr(signature); - var byteKey = encryption.str_to_byte_arr("5586b4bc69c7a4b487e4563a4cd96afd39140f919bd31cea7d1c6a1e8439422b"); - // ... read the body from the request ... - // ... add the timestamp and convert it to a byte[] ... - string body = timestamp + resp; - var byteBody = Encoding.Default.GetBytes(body); + var byteSig = encryption.str_to_byte_arr(signature); + var byteKey = encryption.str_to_byte_arr("5586b4bc69c7a4b487e4563a4cd96afd39140f919bd31cea7d1c6a1e8439422b"); + // ... read the body from the request ... + // ... add the timestamp and convert it to a byte[] ... + string body = timestamp + resp; + var byteBody = Encoding.Default.GetBytes(body); - Console.Write(" Authenticating"); // there's also ... dots being created inside the CheckValid() function BELOW + Console.Write(" Authenticating"); // there's also ... dots being created inside the CheckValid() function BELOW - bool signatureValid = Ed25519.CheckValid(byteSig, byteBody, byteKey); // the ... dots in the console are from this function! - if (!signatureValid) + bool signatureValid = Ed25519.CheckValid(byteSig, byteBody, byteKey); // the ... dots in the console are from this function! + if (!signatureValid) + { + error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); + Logger.LogEvent(resp + "\n"); + TerminateProcess(GetCurrentProcess(), 1); + } + } + catch { error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); Logger.LogEvent(resp + "\n"); TerminateProcess(GetCurrentProcess(), 1); } } - catch - { - error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); - Logger.LogEvent(resp + "\n"); - TerminateProcess(GetCurrentProcess(), 1); - } } #region app_data