Skip to content

Commit

Permalink
Optimize mobile authenticator, add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JustArchi committed Aug 11, 2024
1 parent bae8dc3 commit 90f2d93
Show file tree
Hide file tree
Showing 3 changed files with 166 additions and 13 deletions.
37 changes: 37 additions & 0 deletions ArchiSteamFarm.Tests/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<BotConfig>();

if (botConfig == null) {
throw new InvalidOperationException(nameof(botConfig));
}

BotDatabase? botDatabase = emptyObject.ToJsonObject<BotDatabase>();

if (botDatabase == null) {
throw new InvalidOperationException(nameof(botDatabase));
}

ASF.GlobalDatabase ??= emptyObject.ToJsonObject<GlobalDatabase>();

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;
Expand Down
97 changes: 97 additions & 0 deletions ArchiSteamFarm.Tests/MobileAuthenticator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// ----------------------------------------------------------------------------------------------
// _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
// ----------------------------------------------------------------------------------------------
// |
// Copyright 2015-2024 Łukasz "JustArchi" Domeradzki
// Contact: [email protected]
// |
// 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<Steam.Security.MobileAuthenticator>();

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
45 changes: 32 additions & 13 deletions ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<byte>.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<byte> 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<byte>.Shared.Return(bytes);
}

return string.Create(
CodeDigits, fullCode, static (buffer, state) => {
Expand Down Expand Up @@ -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<byte>.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<byte>.Shared.Return(buffer);
}

return Convert.ToBase64String(hash);
}
Expand Down

0 comments on commit 90f2d93

Please sign in to comment.