using System.Buffers.Binary; using System.Globalization; using System.Security.Cryptography; using System.Text; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Chat; /// The native client's 20-byte IRC challenge response, for the recorded game build. internal static class NativeIrcAuthentication { private static readonly Lazy<(string Build, byte[] Key)> Protocol = new(() => { var data = Assets.Json("irc-auth.json"); return (data.Value("BuildLabel")!, Convert.FromBase64String(data.Value("KeyBase64")!)); }); public static bool Supports(string build) => build.Split('/')[0] == Protocol.Value.Build; public static bool Verify(string credential, ChatIdentity identity, uint challenge) { if (!Supports(identity.Build) || credential.Length != 40 || !credential.All(Uri.IsHexDigit)) return false; var received = Convert.FromHexString(credential); var seed = BinaryPrimitives.ReadUInt32BigEndian(received); if (seed > int.MaxValue) return false; var key = Protocol.Value.Key; var serverSplit = (int)((challenge & int.MaxValue) % key.Length); var clientSplit = (int)(seed % key.Length); var session = Encoding.UTF8.GetBytes($"accountId={identity.Id}&nonce={identity.Nonce.ToString(CultureInfo.InvariantCulture)}"); ReadOnlyMemory[] pieces = [key.AsMemory(0, serverSplit), key.AsMemory(serverSplit), session, key.AsMemory(0, clientSplit), key.AsMemory(clientSplit)]; // MD5 is required by the game's wire protocol; this is not password storage. // Alternate seventeen pieces between two contexts, then XOR the final digests. using var first = IncrementalHash.CreateHash(HashAlgorithmName.MD5); using var second = IncrementalHash.CreateHash(HashAlgorithmName.MD5); for (var i = 0; i < 17; i++) (i % 2 == 0 ? first : second).AppendData(pieces[i % pieces.Length].Span); var a = first.GetHashAndReset(); var b = second.GetHashAndReset(); for (var i = 0; i < a.Length; i++) a[i] ^= b[i]; return CryptographicOperations.FixedTimeEquals(received.AsSpan(4), a); } }