ModernUO/Projects/UOContent.Tests/Tests/Network/Packets/AuthIdTests.cs
Kamron Batman f33bcd6006
fix: Bind the login auth id to its account and drop the redundant verify (#2564)
## 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`.
2026-08-08 09:25:42 -07:00

382 lines
12 KiB
C#

using System;
using System.Net;
using Server.Accounting;
using Server.Accounting.Security;
using Server.Network;
using Server.Tests.Network;
using Xunit;
namespace Server.Tests.Network.Packets;
[Collection("Sequential UOContent Tests")]
public class AuthIdTests : IDisposable
{
private static readonly IPAddress AddressX = IPAddress.Parse("203.0.113.10");
private static readonly IPAddress AddressY = IPAddress.Parse("203.0.113.11");
private readonly PasswordProtectionAlgorithm _originalAlgorithm = AccountSecurity.CurrentAlgorithm;
public AuthIdTests()
{
AccountSecurity.CurrentAlgorithm = PasswordProtectionAlgorithm.Argon2;
IncomingAccountPackets.ClearAuthIdWindow();
}
public void Dispose()
{
IncomingAccountPackets.ClearAuthIdWindow();
AccountSecurity.CurrentAlgorithm = _originalAlgorithm;
}
private static IAccount CreateAccount(string username) =>
Accounts.GetAccount(username) ?? new Account(username, "hunter2");
private static int Register(IAccount account, IPAddress address) =>
IncomingAccountPackets.RegisterAuthId(account, address, new ClientVersion(7, 0, 0, 0));
[Fact]
public void VouchesForTheAccountAndAddressItWasIssuedTo()
{
var account = CreateAccount("authid-match-user");
var authId = Register(account, AddressX);
var result = IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out var entry);
Assert.Equal(IncomingAccountPackets.AuthIdResult.Vouched, result);
Assert.Same(account, entry.Account);
}
[Fact]
public void RejectsADifferentAccount()
{
var issued = CreateAccount("authid-owner-user");
var other = CreateAccount("authid-other-user");
var authId = Register(issued, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId, other.Username, AddressX, out _)
);
}
[Fact]
public void RejectsADifferentAddress()
{
var account = CreateAccount("authid-switch-user");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressY, out _)
);
}
[Fact]
public void MatchesTheUsernameCaseInsensitively()
{
var account = CreateAccount("AuthId-Case-User");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(authId, "authid-case-user", AddressX, out _)
);
}
[Fact]
public void MatchesAnIPv4MappedIPv6Address()
{
var account = CreateAccount("authid-mapped-user");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX.MapToIPv6(), out _)
);
}
[Fact]
public void RejectsAnUnknownAuthId()
{
var account = CreateAccount("authid-unknown-user");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId + 1, account.Username, AddressX, out _)
);
}
[Fact]
public void IsSingleUseAfterASuccess()
{
var account = CreateAccount("authid-once-user");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out _)
);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out _)
);
}
// A rejected attempt must not consume the id, or anyone landing on a live one could burn it and
// force its owner to log in again.
[Fact]
public void SurvivesAnAttemptFromTheWrongAddress()
{
var account = CreateAccount("authid-not-burned-address-user");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressY, out _)
);
Assert.Equal(1, IncomingAccountPackets.AuthIdWindowCount);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out _)
);
}
[Fact]
public void SurvivesAnAttemptForTheWrongAccount()
{
var account = CreateAccount("authid-not-burned-account-user");
var authId = Register(account, AddressX);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId, "not-the-owner", AddressX, out _)
);
Assert.Equal(1, IncomingAccountPackets.AuthIdWindowCount);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out _)
);
}
[Fact]
public void ARejectedAttemptYieldsNoEntry()
{
var account = CreateAccount("authid-no-leak-user");
var authId = Register(account, AddressX);
IncomingAccountPackets.ConsumeAuthId(authId, "not-the-owner", AddressX, out var entry);
Assert.Null(entry.Account);
}
[Fact]
public void AnExpiredIdIsSpentByItsOwner()
{
var account = CreateAccount("authid-expired-spent-user");
var authId = Register(account, AddressX);
var now = Core._now;
try
{
Core._now = now + TimeSpan.FromMinutes(30.0);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Expired,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out _)
);
Assert.Equal(0, IncomingAccountPackets.AuthIdWindowCount);
}
finally
{
Core._now = now;
}
}
// Expiry is not a lockout. The game login always verified the password before any of this
// existed, so falling back to that verify is the behaviour we started from.
[Fact]
public void ExpiresIntoAPasswordVerifyRatherThanARejection()
{
var account = CreateAccount("authid-expired-user");
var authId = Register(account, AddressX);
var now = Core._now;
try
{
Core._now = now + TimeSpan.FromMinutes(30.0);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Expired,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressX, out var entry)
);
// Still carries the client version the game login needs.
Assert.Equal(new ClientVersion(7, 0, 0, 0), entry.Version);
}
finally
{
Core._now = now;
}
}
[Fact]
public void AnExpiredIdFromAnotherAddressIsStillRejected()
{
var account = CreateAccount("authid-expired-elsewhere-user");
var authId = Register(account, AddressX);
var now = Core._now;
try
{
Core._now = now + TimeSpan.FromMinutes(30.0);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Rejected,
IncomingAccountPackets.ConsumeAuthId(authId, account.Username, AddressY, out _)
);
}
finally
{
Core._now = now;
}
}
private static int Ensure(int existingAuthId, IAccount account, IPAddress address) =>
IncomingAccountPackets.EnsureAuthId(
existingAuthId,
account,
address,
new ClientVersion(7, 0, 0, 0)
);
[Fact]
public void IssuesAnIdWhenTheConnectionHasNone()
{
var account = CreateAccount("authid-first-select-user");
var authId = Ensure(0, account, AddressX);
Assert.NotEqual(0, authId);
Assert.Equal(1, IncomingAccountPackets.AuthIdWindowCount);
}
// Handing the same id back rather than minting another is what makes an orphan impossible,
// instead of something to clean up afterwards.
[Fact]
public void ReSelectingReturnsTheSameIdAndAddsNothingToTheWindow()
{
var account = CreateAccount("authid-reselect-user");
var first = Ensure(0, account, AddressX);
for (var i = 0; i < 10; i++)
{
Assert.Equal(first, Ensure(first, account, AddressX));
}
Assert.Equal(1, IncomingAccountPackets.AuthIdWindowCount);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(first, account.Username, AddressX, out _)
);
}
[Fact]
public void AbandonedIdsAreSweptWhenNewOnesAreIssued()
{
var abandoned = CreateAccount("authid-abandoned-user");
var live = CreateAccount("authid-live-user");
var now = Core._now;
try
{
for (var i = 0; i < 128; i++)
{
Register(abandoned, AddressX);
}
Assert.Equal(128, IncomingAccountPackets.AuthIdWindowCount);
Core._now = now + TimeSpan.FromMinutes(30.0);
var liveId = Register(live, AddressX);
Assert.Equal(1, IncomingAccountPackets.AuthIdWindowCount);
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(liveId, live.Username, AddressX, out _)
);
}
finally
{
Core._now = now;
}
}
// A login rush is not a backlog. Every id belongs to a client on its way to redeem it, so none
// may be discarded to hold the window at some arbitrary size.
[Fact]
public void ALoginRushDoesNotEvictAnyonesAuthId()
{
var account = CreateAccount("authid-rush-user");
var ids = new int[800];
for (var i = 0; i < ids.Length; i++)
{
ids[i] = Register(account, AddressX);
}
Assert.Equal(ids.Length, IncomingAccountPackets.AuthIdWindowCount);
// Every id issued during the rush is still redeemable, including the first one.
for (var i = 0; i < ids.Length; i++)
{
Assert.Equal(
IncomingAccountPackets.AuthIdResult.Vouched,
IncomingAccountPackets.ConsumeAuthId(ids[i], account.Username, AddressX, out _)
);
}
}
[Fact]
public void PreAuthenticatedGameLogin_SkipsThePasswordCheck()
{
var account = CreateAccount("authid-preauth-user");
using var ns = PacketTestUtilities.CreateTestNetState();
// A wrong password is accepted only because the auth id already vouched for the account.
var e = new GameServer.GameLoginEventArgs(ns, account.Username, "wrong-password", true);
GameServer.GameServerLoginEvent(e);
Assert.True(e.Accepted);
}
[Fact]
public void GameLoginWithoutPreAuthentication_StillChecksThePassword()
{
var account = CreateAccount("authid-nopreauth-user");
using var ns = PacketTestUtilities.CreateTestNetState();
var wrong = new GameServer.GameLoginEventArgs(ns, account.Username, "wrong-password", false);
GameServer.GameServerLoginEvent(wrong);
Assert.False(wrong.Accepted);
var right = new GameServer.GameLoginEventArgs(ns, account.Username, "hunter2", false);
GameServer.GameServerLoginEvent(right);
Assert.True(right.Accepted);
}
[Fact]
public void GeneratesDistinctAuthIds()
{
var account = CreateAccount("authid-distinct-user");
Assert.NotEqual(Register(account, AddressX), Register(account, AddressX));
}
}