ModernUO/Projects/UOContent/Accounting/AccountHandler.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

385 lines
12 KiB
C#

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Net;
using System.Runtime.CompilerServices;
using ModernUO.CodeGeneratedEvents;
using Server.Accounting;
using Server.Engines.CharacterCreation;
using Server.Engines.Help;
using Server.Logging;
using Server.Network;
using Server.Regions;
namespace Server.Misc;
public static class AccountHandler
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(AccountHandler));
private static int MaxAccountsPerIP;
private static bool AutoAccountCreation;
private static readonly bool RestrictDeletion = !TestCenter.Enabled;
private static readonly TimeSpan DeleteDelay = TimeSpan.FromDays(7.0);
private static bool PasswordCommandEnabled;
private static Dictionary<IPAddress, int> m_IPTable;
private static readonly SearchValues<char> ForbiddenChars = SearchValues.Create("<>:\"/\\|?*");
public static AccessLevel LockdownLevel { get; set; }
public static Dictionary<IPAddress, int> IPTable
{
get
{
if (m_IPTable == null)
{
m_IPTable = new Dictionary<IPAddress, int>();
foreach (Account a in Accounts.GetAccounts())
{
if (a.LoginIPs.Length > 0)
{
var ip = a.LoginIPs[0];
m_IPTable[ip] = (m_IPTable.TryGetValue(ip, out var value) ? value : 0) + 1;
}
}
}
return m_IPTable;
}
}
public static void Configure()
{
MaxAccountsPerIP = ServerConfiguration.GetOrUpdateSetting("accountHandler.maxAccountsPerIP", 1);
AutoAccountCreation = ServerConfiguration.GetOrUpdateSetting("accountHandler.enableAutoAccountCreation", true);
PasswordCommandEnabled = ServerConfiguration.GetOrUpdateSetting(
"accountHandler.enablePlayerPasswordCommand",
false
);
if (PasswordCommandEnabled)
{
CommandSystem.Register("Password", AccessLevel.Player, Password_OnCommand);
}
}
public static void Initialize()
{
EventSink.AccountLogin += EventSink_AccountLogin;
}
[Usage("Password <newPassword> <repeatPassword>")]
[Description(
"Changes the password of the commanding players account. Requires the same C-class IP address as the account's creator."
)]
public static void Password_OnCommand(CommandEventArgs e)
{
var from = e.Mobile;
if (from.Account is not Account acct)
{
return;
}
var accessList = acct.LoginIPs;
if (accessList.Length == 0)
{
return;
}
var ns = from.NetState;
if (ns == null)
{
return;
}
if (e.Length == 0)
{
from.SendMessage("You must specify the new password.");
return;
}
if (e.Length == 1)
{
from.SendMessage("To prevent potential typing mistakes, you must type the password twice. Use the format:");
from.SendMessage("Password \"(newPassword)\" \"(repeated)\"");
return;
}
var pass = e.GetString(0);
var pass2 = e.GetString(1);
if (pass != pass2)
{
from.SendMessage("The passwords do not match.");
return;
}
var isSafe = true;
for (var i = 0; isSafe && i < pass.Length; ++i)
{
isSafe = pass[i] >= 0x20 && pass[i] < 0x7F;
}
if (!isSafe)
{
from.SendMessage("That is not a valid password.");
return;
}
try
{
var ipAddress = ns.Address;
if (accessList[0].MatchClassC(ipAddress))
{
acct.SetPassword(pass);
from.SendMessage("The password to your account has changed.");
}
else
{
var entry = PageQueue.GetEntry(from);
if (entry != null)
{
if (entry.Message.StartsWithOrdinal("[Automated: Change Password]"))
{
from.SendMessage("You already have a password change request in the help system queue.");
}
else
{
from.SendMessage("Your IP address does not match that which created this account.");
}
}
else if (PageQueue.CheckAllowedToPage(from))
{
from.SendMessage(
"Your IP address does not match that which created this account. A page has been entered into the help system on your behalf."
);
/* The next available Counselor/Game Master will respond as soon as possible.
* Please check your Journal for messages every few minutes.
*/
from.SendLocalizedMessage(501234, "", 0x35);
PageQueue.Enqueue(
new PageEntry(
from,
$"[Automated: Change Password]<br>Desired password: {pass}<br>Current IP address: {ipAddress}<br>Account IP address: {accessList[0]}",
PageType.Account
)
);
}
}
}
catch
{
// ignored
}
}
public static void DeleteRequest(NetState state, int index)
{
if (state.Account is not Account acct)
{
state.Disconnect("Attempted to delete a character but the account could not be found.");
return;
}
DeleteResultType res;
if (index < 0 || index >= acct.Length)
{
res = DeleteResultType.BadRequest;
}
else
{
var m = acct[index];
if (m == null)
{
res = DeleteResultType.CharNotExist;
}
else if (m.NetState != null)
{
res = DeleteResultType.CharBeingPlayed;
}
else if (acct.AccessLevel == AccessLevel.Player && RestrictDeletion && Core.Now < m.Created + DeleteDelay)
{
res = DeleteResultType.CharTooYoung;
}
// Don't need to check current location, if netstate is null, they're logged out
else if (
m.AccessLevel == AccessLevel.Player &&
Region.Find(m.LogoutLocation, m.LogoutMap).IsPartOf<JailRegion>()
)
{
res = DeleteResultType.BadRequest;
}
else
{
state.LogInfo($"Deleting character {index} ({m.Serial})");
acct.Comments.Add(new AccountComment("System", $"Character #{index + 1} {m} deleted by {state}"));
m.Delete();
state.SendCharacterListUpdate(acct);
return;
}
}
state.SendCharacterDeleteResult(res);
state.SendCharacterListUpdate(acct);
}
public static bool CanCreate(IPAddress ip) =>
!IPTable.TryGetValue(ip, out var result) || result < MaxAccountsPerIP;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsValidUsername(ReadOnlySpan<char> username) =>
username.Length > 0 &&
// Usernames must not start with a space, end with a space, or end with a period
!username.StartsWith(' ') && !username.EndsWith(' ') && !username.EndsWith('.') &&
!username.ContainsAny(ForbiddenChars);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsValidPassword(ReadOnlySpan<char> password) => password.Length > 0;
private static Account CreateAccount(NetState state, string username, string password)
{
if (!IsValidUsername(username) || !IsValidPassword(password))
{
return null;
}
if (!CanCreate(state.Address))
{
logger.Information(
$"Login: {{NetState}} Account '{{Username}}' not created, ip already has {{AccountCount}} account{(MaxAccountsPerIP == 1 ? "" : "s")}.",
state,
username,
MaxAccountsPerIP
);
return null;
}
logger.Information("Login: {NetState}: Creating new account '{Username}'", state, username);
return new Account(username, password);
}
public static void EventSink_AccountLogin(AccountLoginEventArgs e)
{
var un = e.Username;
var pw = e.Password;
e.Accepted = false;
if (Accounts.GetAccount(un) is not Account acct)
{
// To prevent someone from making an account of just '' or a bunch of meaningless spaces
if (AutoAccountCreation && !string.IsNullOrWhiteSpace(un))
{
e.State.Account = acct = CreateAccount(e.State, un, pw);
e.Accepted = acct?.CheckAccess(e.State) ?? false;
if (!e.Accepted)
{
e.RejectReason = ALRReason.BadComm;
}
}
else
{
logger.Information("Login: {NetState} Invalid username '{Username}'", e.State, un);
e.RejectReason = ALRReason.Invalid;
}
}
else if (!acct.HasAccess(e.State))
{
logger.Information("Login: {NetState} Access denied for '{Username}'", e.State, un);
e.RejectReason = LockdownLevel > AccessLevel.Player ? ALRReason.BadComm : ALRReason.BadPass;
}
else if (!acct.CheckPassword(pw))
{
logger.Information("Login: {NetState} Invalid password for '{Username}'", e.State, un);
e.RejectReason = ALRReason.BadPass;
}
else if (acct.Banned)
{
logger.Information("Login: {NetState} Banned account '{Username}'", e.State, un);
e.RejectReason = ALRReason.Blocked;
}
else
{
logger.Information("Login: {NetState} Valid credentials for '{Username}'", e.State, un);
e.State.Account = acct;
e.Accepted = true;
acct.LogAccess(e.State);
LoginAllowlist.RecordLogin(e.State?.Address);
}
}
[OnEvent(nameof(GameServer.GameServerLoginEvent))]
public static void OnGameServerLogin(GameServer.GameLoginEventArgs e)
{
var un = e.Username;
var pw = e.Password;
if (Accounts.GetAccount(un) is not Account acct)
{
e.Accepted = false;
}
else if (!acct.HasAccess(e.State))
{
logger.Information("Login: {NetState} Access denied for '{Username}'", e.State, un);
e.Accepted = false;
}
// The auth id was only issued after the account login packet verified this password, so
// re-deriving the hash costs a second Argon2 verify to answer the same question.
else if (!e.PreAuthenticated && !acct.CheckPassword(pw))
{
logger.Information("Login: {NetState} Invalid password for '{Username}'", e.State, un);
e.Accepted = false;
}
else if (acct.Banned)
{
logger.Information("Login: {NetState} Banned account '{Username}'", e.State, un);
e.Accepted = false;
}
else
{
acct.LogAccess(e.State);
LoginAllowlist.RecordLogin(e.State?.Address);
logger.Information("Login: {NetState} Account '{Username}' at character list", e.State, un);
e.State.Account = acct;
e.Accepted = true;
e.CityInfo = CharacterCreation.GetStartingCities();
}
}
public static bool CheckAccount(Mobile mobCheck, Mobile accCheck)
{
if (accCheck?.Account is Account a)
{
for (var i = 0; i < a.Length; ++i)
{
if (a[i] == mobCheck)
{
return true;
}
}
}
return false;
}
}