From 90f2d93768793684f634302a4f8486691fdf65d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Domeradzki?= Date: Sun, 11 Aug 2024 02:21:00 +0200 Subject: [PATCH] Optimize mobile authenticator, add unit tests --- ArchiSteamFarm.Tests/Bot.cs | 37 +++++++ ArchiSteamFarm.Tests/MobileAuthenticator.cs | 97 +++++++++++++++++++ .../Steam/Security/MobileAuthenticator.cs | 45 ++++++--- 3 files changed, 166 insertions(+), 13 deletions(-) create mode 100644 ArchiSteamFarm.Tests/MobileAuthenticator.cs diff --git a/ArchiSteamFarm.Tests/Bot.cs b/ArchiSteamFarm.Tests/Bot.cs index 8c3d0ccc65cb8..a98264c5deee0 100644 --- a/ArchiSteamFarm.Tests/Bot.cs +++ b/ArchiSteamFarm.Tests/Bot.cs @@ -25,7 +25,14 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Nodes; +using ArchiSteamFarm.Core; +using ArchiSteamFarm.Helpers.Json; using ArchiSteamFarm.Steam.Data; +using ArchiSteamFarm.Steam.Storage; +using ArchiSteamFarm.Storage; using Microsoft.VisualStudio.TestTools.UnitTesting; using static ArchiSteamFarm.Steam.Bot; @@ -34,6 +41,36 @@ namespace ArchiSteamFarm.Tests; #pragma warning disable CA1812 // False positive, the class is used during MSTest [TestClass] internal sealed class Bot { + internal static Steam.Bot GenerateBot() { + ConstructorInfo? constructor = typeof(Steam.Bot).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, [typeof(string), typeof(BotConfig), typeof(BotDatabase)]); + + if (constructor == null) { + throw new InvalidOperationException(nameof(constructor)); + } + + JsonElement emptyObject = new JsonObject().ToJsonElement(); + + BotConfig? botConfig = emptyObject.ToJsonObject(); + + if (botConfig == null) { + throw new InvalidOperationException(nameof(botConfig)); + } + + BotDatabase? botDatabase = emptyObject.ToJsonObject(); + + if (botDatabase == null) { + throw new InvalidOperationException(nameof(botDatabase)); + } + + ASF.GlobalDatabase ??= emptyObject.ToJsonObject(); + + if (constructor.Invoke(["Test", botConfig, botDatabase]) is not Steam.Bot result) { + throw new InvalidOperationException(nameof(result)); + } + + return result; + } + [TestMethod] internal void MaxItemsBarelyEnoughForOneSet() { const uint relevantAppID = 42; diff --git a/ArchiSteamFarm.Tests/MobileAuthenticator.cs b/ArchiSteamFarm.Tests/MobileAuthenticator.cs new file mode 100644 index 0000000000000..0d8d595fb08ca --- /dev/null +++ b/ArchiSteamFarm.Tests/MobileAuthenticator.cs @@ -0,0 +1,97 @@ +// ---------------------------------------------------------------------------------------------- +// _ _ _ ____ _ _____ +// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ +// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ +// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | +// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| +// ---------------------------------------------------------------------------------------------- +// | +// Copyright 2015-2024 Ɓukasz "JustArchi" Domeradzki +// Contact: JustArchi@JustArchi.net +// | +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// | +// http://www.apache.org/licenses/LICENSE-2.0 +// | +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using System.Reflection; +using System.Text.Json.Nodes; +using ArchiSteamFarm.Helpers.Json; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ArchiSteamFarm.Tests; + +#pragma warning disable CA1812 // False positive, the class is used during MSTest +[TestClass] +public sealed class MobileAuthenticator { + [DataRow("qrg+wW8/u/TDt2i/+FQuPhuVrmY=", (ulong) 1337, "QFo72j9TnG+uRXe9EIJs4zyBPo0=")] + [DataRow("qrg+wW8/u/TDt2i/+FQuPhuVrmY=", (ulong) 1337, "mYbCKs8ZvsVN2odCMxpvidrIu1c=", "conf")] + [DataRow("qrg+wW8/u/TDt2i/+FQuPhuVrmY=", (ulong) 1723332288, "hiEx+JBqJqFJnSSL+dEthPHOmsc=")] + [DataRow("qrg+wW8/u/TDt2i/+FQuPhuVrmY=", (ulong) 1723332288, "hpZUxyNgwBvtKPROvedjuvVPQiE=", "conf")] + [DataTestMethod] + internal void GenerateConfirmationHash(string identitySecret, ulong time, string expectedCode, string? tag = null) { + ArgumentException.ThrowIfNullOrEmpty(identitySecret); + ArgumentOutOfRangeException.ThrowIfZero(time); + ArgumentException.ThrowIfNullOrEmpty(expectedCode); + + MethodInfo? method = typeof(Steam.Security.MobileAuthenticator).GetMethod(nameof(GenerateConfirmationHash), BindingFlags.Instance | BindingFlags.NonPublic, [typeof(ulong), typeof(string)]); + + if (method == null) { + throw new InvalidOperationException(nameof(method)); + } + + using Steam.Security.MobileAuthenticator authenticator = GenerateMobileAuthenticator(identitySecret, identitySecret); + + string? result = method.Invoke(authenticator, [time, tag]) as string; + + Assert.IsNotNull(result); + Assert.AreEqual(expectedCode, result); + } + + [DataRow("KDHC3rsY8+CmiswnXJcE5e5dRfd=", (ulong) 1337, "47J4D")] + [DataRow("KDHC3rsY8+CmiswnXJcE5e5dRfd=", (ulong) 1723332288, "JQ3HQ")] + [DataTestMethod] + internal void GenerateTokenForTime(string sharedSecret, ulong time, string expectedCode) { + ArgumentException.ThrowIfNullOrEmpty(sharedSecret); + ArgumentOutOfRangeException.ThrowIfZero(time); + ArgumentException.ThrowIfNullOrEmpty(expectedCode); + + using Steam.Security.MobileAuthenticator authenticator = GenerateMobileAuthenticator(sharedSecret, sharedSecret); + + string? result = authenticator.GenerateTokenForTime(time); + + Assert.IsNotNull(result); + Assert.AreEqual(expectedCode, result); + } + + private static Steam.Security.MobileAuthenticator GenerateMobileAuthenticator(string identitySecret, string sharedSecret) { + ArgumentException.ThrowIfNullOrEmpty(identitySecret); + ArgumentException.ThrowIfNullOrEmpty(sharedSecret); + + JsonObject jsonObject = new() { + ["identity_secret"] = identitySecret, + ["shared_secret"] = sharedSecret + }; + + Steam.Security.MobileAuthenticator? result = jsonObject.ToJsonElement().ToJsonObject(); + + if (result == null) { + throw new InvalidOperationException(nameof(result)); + } + + Steam.Bot bot = Bot.GenerateBot(); + + result.Init(bot); + + return result; + } +} +#pragma warning restore CA1812 // False positive, the class is used during MSTest diff --git a/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs b/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs index b87e3d523c9a7..c39365b476431 100644 --- a/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs +++ b/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs @@ -22,6 +22,7 @@ // limitations under the License. using System; +using System.Buffers; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; @@ -124,17 +125,29 @@ public sealed class MobileAuthenticator : IDisposable { // The last 4 bits of the mac say where the code starts int start = hash[^1] & 0x0f; + uint fullCode; + // Extract those 4 bytes - byte[] bytes = new byte[4]; + byte[] bytes = ArrayPool.Shared.Rent(4); - Array.Copy(hash, start, bytes, 0, 4); + try { + Array.Copy(hash, start, bytes, 0, 4); - if (BitConverter.IsLittleEndian) { - Array.Reverse(bytes); - } + Span span; - // Build the alphanumeric code - uint fullCode = BitConverter.ToUInt32(bytes, 0) & 0x7fffffff; + if (BitConverter.IsLittleEndian) { + Array.Reverse(bytes); + + span = bytes.AsSpan()[^4..]; + } else { + span = bytes.AsSpan()[..4]; + } + + // Build the alphanumeric code + fullCode = BitConverter.ToUInt32(span) & 0x7fffffff; + } finally { + ArrayPool.Shared.Return(bytes); + } return string.Create( CodeDigits, fullCode, static (buffer, state) => { @@ -347,17 +360,23 @@ internal static async Task ResetSteamTimeDifference() { Array.Reverse(timeArray); } - byte[] buffer = new byte[bufferSize]; + byte[] hash; - Array.Copy(timeArray, buffer, 8); + byte[] buffer = ArrayPool.Shared.Rent(bufferSize); - if (!string.IsNullOrEmpty(tag)) { - Array.Copy(Encoding.UTF8.GetBytes(tag), 0, buffer, 8, bufferSize - 8); - } + try { + Array.Copy(timeArray, buffer, timeArray.Length); + + if (!string.IsNullOrEmpty(tag)) { + Array.Copy(Encoding.UTF8.GetBytes(tag), 0, buffer, timeArray.Length, bufferSize - timeArray.Length); + } #pragma warning disable CA5350 // This is actually a fair warning, but there is nothing we can do about Steam using weak cryptographic algorithms - byte[] hash = HMACSHA1.HashData(identitySecret, buffer); + hash = HMACSHA1.HashData(identitySecret, buffer.AsSpan()[..bufferSize]); #pragma warning restore CA5350 // This is actually a fair warning, but there is nothing we can do about Steam using weak cryptographic algorithms + } finally { + ArrayPool.Shared.Return(buffer); + } return Convert.ToBase64String(hash); }