## What - Bind the login auth id to the account **and** origin address that earned it, make it a CSPRNG draw, expire it after two minutes, and spend it only once its owner presents it. - Skip the password verify on `GameLogin` (0x91) when the presented id vouches for the submitted username and address. ## Why A full client login hashes the password twice — `AccountLogin` (0x80) and then `GameLogin` (0x91). At the current Argon2 parameters that is **most of a 16 ms frame each, on the single-threaded game loop**, for every login attempt. The second verify is redundant. `GameLogin` already requires an id from `_authIDWindow`, and that window is only populated by `GenerateAuthID`, called from `PlayServer` — reachable only after 0x80 has already authenticated the account **in this same process**. ModernUO Gateway has its own auth-id passing mechanism and is out of scope here. ## Why the id needed hardening first Skipping the verify promotes the id from a correlation token to a bearer token, and it was not one: - drawn from `Utility.Random` → `BuiltInRng`, a non-cryptographic PRNG - bound to nothing — `AuthIDPersistence` carried only `Age` and `Version` - never expiring; `Age` was only read to pick an eviction victim A guessed id got you nothing while the password was still checked. Without that check it would have been an account takeover, so the id is now a CSPRNG draw, single-use, two-minute TTL, and bound to both the account and the origin address. What remains is observing a live id on the client's network or machine — which the server cannot defend against under any design, and which already yields the password itself, since the client transmits it in the same handshake. Network switching mid-login is deliberately unsupported. ## Behaviour A full verify was always required before this change, and ids never expired, so every "before" is a password check. | Case | Before | After | |---|---|---| | Id absent | Disconnect | Disconnect | | Address mismatch | Verify | **Disconnect** | | Account mismatch | Verify | **Disconnect** | | Expired | Verify | **Verify** | | Id vouches | Verify | **Skip** | No case grants access the previous code would have denied. Expiry deliberately falls back to the verify rather than disconnecting — a player can idle, and turning that into a lockout would be a regression for no gain. ## Look, then take An id is not consumed until the presenter has shown it is theirs. Removing it first would let anyone who lands on a live id burn it, and its owner would arrive to `"Unable to find auth id."` and have to log in again over a packet they had no part in. The **address is compared before the account**, so a guesser from anywhere else is rejected before a username is ever looked at. That is what makes it safe to leave the id in place on a mismatch: there is no username-enumeration risk to trade against, and the only presenter who could enumerate is already on the victim's own address. ## The window is not a cap It was 128 entries with the oldest evicted to make room. That is a cap on *concurrent logins*, not a resource bound: 800 people picking a server at once would have live ids discarded and those clients would arrive to `"Unable to find auth id."` — a failed login caused by nothing except other people logging in. Issuing now sweeps expired entries and lets the window grow if everything in it is still live. Unbounded is safe here: an entry costs a **successful** password verify to create and dies after two minutes, so its size tracks logins genuinely in flight. Removing an id when its connection drops is not an option, and this was checked rather than assumed — `NetState.cs:787` disconnects the login connection *deliberately*, immediately after the id is issued, and that disconnect is never cancelled. Surviving it is the whole purpose of the id. Expiry is the only correct reclamation. ## Handshake hardening Choosing a server queues a disconnect, but the queue drains on the *next* slice, so a client pipelining into the same recv buffer can reach the handshake handlers again. Two had no do-once guard: - `LoginServerSeed` (0xEF) now rejects when `state.Seeded` is already set. - `PlayServer` (0xA0) now rejects when `state.AuthId != 0` — otherwise a connection that had already spent its id would be handed the spent one back. Issuing is also idempotent (`EnsureAuthId`), so a connection holds exactly one id by construction and an orphan is impossible rather than something to clean up. The login state machine itself is untouched. Also fixes a fall-through: the "Unable to find auth id" branch disconnected without returning, then continued with a default entry and nulled `state.Version`. ## Testing `ConsumeAuthId` is a seam with no `NetState` dependency, so the auth decision is tested directly: vouching, account mismatch, address mismatch, case-insensitive usernames, IPv4-mapped-IPv6, unknown ids, single-use by the owner, **a rejected attempt leaving the id redeemable**, expiry-into-verify, and an 800-id login rush that must evict nobody. Expiry is driven by moving `Core._now`, not by waiting. Every new clause was verified to discriminate by removing it and confirming only its own tests fail. ## Cost Halves the per-login game-loop cost. This does not make hashing cheaper or move it off the loop — that is gated on a measurement described in `docs/handoffs/2026-08-07-off-loop-argon2-hashing.md`.
164 lines
7 KiB
C#
164 lines
7 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Reflection;
|
|
using System.Threading;
|
|
using Server.Items;
|
|
using Server.Misc;
|
|
using Server.Movement;
|
|
using Server.PathAlgorithms;
|
|
using Server.Tests.Maps;
|
|
|
|
namespace Server.Tests;
|
|
|
|
/// <summary>
|
|
/// Single, process-wide ModernUO bootstrap for the UOContent test host. Mirrors Server.Tests'
|
|
/// TestServerInitializer in name and shape; kept as a separate (non-shared) copy because this
|
|
/// one loads the UOContent assembly and configures the UOContent-specific systems. Both types
|
|
/// are <c>internal</c> so the shared name stays scoped to each assembly.
|
|
///
|
|
/// ModernUO bootstraps its global singletons (Core, ServerConfiguration, AssemblyHandler,
|
|
/// NetState/io-ring, World, Timer, the serialization workers, and TileData) exactly once per
|
|
/// process. <see cref="World.Load"/> is guarded to run once, and
|
|
/// <see cref="World.ExitSerializationThreads"/> must run once against the live workers. Each
|
|
/// xUnit collection gets its own fixture instance, so this guard makes the bootstrap run a
|
|
/// single time regardless of how many collection fixtures are constructed. The two stateful
|
|
/// collections use <c>[CollectionDefinition(DisableParallelization = true)]</c> so they never
|
|
/// overlap; pure tests still run in parallel.
|
|
/// </summary>
|
|
internal static class TestServerInitializer
|
|
{
|
|
private static bool _initialized;
|
|
private static readonly Lock _lock = new();
|
|
|
|
/// <summary>
|
|
/// True if the UO client tile data was found and loaded. When false (e.g. CI, where the
|
|
/// copyrighted client files are absent), tile/map/multi-dependent tests must skip rather than
|
|
/// fail. Guard such tests with <c>Skip.If(!TestServerInitializer.TileDataLoaded, ...)</c>.
|
|
/// </summary>
|
|
public static bool TileDataLoaded { get; private set; }
|
|
|
|
public static void Initialize()
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (_initialized)
|
|
{
|
|
return;
|
|
}
|
|
|
|
Core.ApplicationAssembly = Assembly.GetExecutingAssembly();
|
|
Core.LoopContext = new EventLoopContext();
|
|
Core.Expansion = Expansion.EJ;
|
|
|
|
ServerConfiguration.Load(true);
|
|
ServerConfiguration.AssemblyDirectories.Add(Core.BaseDirectory);
|
|
|
|
// Required for the pathfinding tests (real .mul tile data). Harmless for the rest.
|
|
var clientFiles = Environment.GetEnvironmentVariable("MODERNUO_TEST_DATA_DIR")
|
|
?? @"C:\Ultima Online Classic";
|
|
ServerConfiguration.DataDirectories.Add(clientFiles);
|
|
|
|
AssemblyHandler.LoadAssemblies(["Server.dll", "UOContent.dll"]);
|
|
|
|
SkillsInfo.Configure();
|
|
|
|
// Seed the loop clock as Main.cs does before the Configure sweep; otherwise Core.Now is
|
|
// DateTime.MinValue for the whole test host.
|
|
Core._now = DateTime.UtcNow;
|
|
|
|
// Timer wheel must exist before NetState.Configure(), which schedules a recurring
|
|
// sweep via Timer.DelayCall (matches production ordering in Main.cs: Timer.Init runs
|
|
// before AssemblyHandler.Invoke("Configure")).
|
|
Timer.Init(0);
|
|
Server.Network.NetState.Configure();
|
|
TestMapDefinitions.ConfigureTestMapDefinitions();
|
|
|
|
// TileData's static cctor short-circuits when running under xUnit
|
|
// (see Server/TileData.cs:295). Force-load via reflection so LandTable/ItemTable
|
|
// flags are populated before anything that reads TileData (MultiData, MovementImpl,
|
|
// CheckMovement). Without this, TileData.MaxItemValue is 0 at MultiData.Configure()
|
|
// time, causing every MCL tile ID to be masked to 0 and stored as ID=0 in Tiles[x][y].
|
|
// The copyrighted client files are absent on CI; when tiledata.mul is missing we skip
|
|
// the tile/map/multi-dependent bootstrap and leave TileDataLoaded false so those tests
|
|
// skip instead of failing the whole collection from the fixture constructor.
|
|
TileDataLoaded = TryForceLoadTileData();
|
|
|
|
// Production runs every static Configure() via AssemblyHandler.Invoke("Configure");
|
|
// the fixture calls a curated subset, so configure the pathfinding singleton here so
|
|
// BitmapAStarAlgorithm.Instance carries its configured MaxSearchNodes before any test
|
|
// calls Find. ServerConfiguration is already loaded above, so the setting resolves.
|
|
BitmapAStarAlgorithm.Configure();
|
|
|
|
if (TileDataLoaded)
|
|
{
|
|
// Multi component lists (multi.mul / MultiCollection.uop). Production invokes this via
|
|
// AssemblyHandler.Invoke("Configure"); the curated fixture subset must call it so that
|
|
// BaseMulti.Components (MultiData.GetComponents) returns real footprints instead of
|
|
// MultiComponentList.Empty. Required by the Multi pathfinding tests. Depends on the
|
|
// client files, so it only runs when tile data loaded.
|
|
MultiData.Configure();
|
|
}
|
|
|
|
World.Configure();
|
|
// Registers the Accounts entity persistence; without it no test can construct an Account.
|
|
Server.Accounting.Accounts.Configure();
|
|
RaceDefinitions.Configure();
|
|
MovementImpl.Configure();
|
|
PathFollower.Configure();
|
|
World.Load();
|
|
World.ExitSerializationThreads();
|
|
DecayScheduler.Configure();
|
|
Server.Engines.Spawners.SpawnerJsonSerializer.Configure();
|
|
|
|
if (TileDataLoaded)
|
|
{
|
|
VerifyTrammelTileDataLoaded();
|
|
}
|
|
|
|
_initialized = true;
|
|
}
|
|
}
|
|
|
|
private static bool TryForceLoadTileData()
|
|
{
|
|
var tileDataPath = Core.FindDataFile("tiledata.mul", false);
|
|
if (string.IsNullOrEmpty(tileDataPath) || !File.Exists(tileDataPath))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var loadMethod = typeof(TileData).GetMethod(
|
|
"Load",
|
|
BindingFlags.Static | BindingFlags.NonPublic
|
|
);
|
|
if (loadMethod == null)
|
|
{
|
|
throw new InvalidOperationException(
|
|
"TileData.Load not found via reflection — engine may have refactored."
|
|
);
|
|
}
|
|
loadMethod.Invoke(null, null);
|
|
return true;
|
|
}
|
|
|
|
private static void VerifyTrammelTileDataLoaded()
|
|
{
|
|
var trammel = Map.Maps[1];
|
|
if (trammel == null)
|
|
{
|
|
throw new InvalidOperationException(
|
|
"Trammel (mapId=1) was not registered. Check TestMapDefinitions."
|
|
);
|
|
}
|
|
|
|
var tile = trammel.Tiles.GetLandTile(1500, 1600);
|
|
if (tile.ID == 0)
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Trammel tile data did not load — GetLandTile(1500,1600) returned ID 0. " +
|
|
$"Verify Distribution/Data/map1*.mul (or map1LegacyMUL.uop) is present at " +
|
|
$"{Path.Combine(Core.BaseDirectory, "Data")}."
|
|
);
|
|
}
|
|
}
|
|
}
|