From b9137e094848b2d002dca1ee9e304f550b527bfc Mon Sep 17 00:00:00 2001 From: Lucas Rayan Date: Thu, 5 Nov 2026 06:27:38 -0300 Subject: [PATCH] feat(auth): cap login guessing with a per-account budget Failures from unknown addresses are capped at 100 per rolling 24 hours per username, refused before Argon2 and before the hashing queue. Addresses with a completed login in the last 30 days skip the budget, stored hashed on the user. IPv6 counts per /48 for the pair throttle and the budget. Unknown names take the same path, with their budget in the stand-in table. Crossing the cap audits login.budget_exhausted once per account per 24 hours. Eviction drops faded entries, then the least counted, not the oldest. Co-Authored-By: Claude Opus 5.5 --- crates/acaua-cli/src/auth_http.rs | 39 +- crates/acaua-cli/src/web_tests.rs | 101 +++++ crates/acaua-core/src/auth/mod.rs | 8 +- crates/acaua-core/src/auth/service.rs | 311 ++++++++++--- crates/acaua-core/src/auth/service_tests.rs | 399 ++++++++++++++++- crates/acaua-core/src/auth/store.rs | 21 + crates/acaua-core/src/auth/throttle.rs | 455 ++++++++++++++------ 7 files changed, 1128 insertions(+), 206 deletions(-) diff --git a/crates/acaua-cli/src/auth_http.rs b/crates/acaua-cli/src/auth_http.rs index 00896d9..ed0166c 100644 --- a/crates/acaua-cli/src/auth_http.rs +++ b/crates/acaua-cli/src/auth_http.rs @@ -7,7 +7,8 @@ use crate::web::{access_of, is_public, is_public_asset, Access, AppState}; use acaua_core::auth::{ - csrf_matches, csrf_token, NewSession, PendingMfa, Principal, Role, Scope, TotpEnrollment, Via, + csrf_matches, csrf_token, AuthService, LoginAttempt, NewSession, PendingMfa, Principal, Role, + Scope, TotpEnrollment, Via, }; use acaua_core::{AcauaError, AuthFailure}; use axum::extract::rejection::JsonRejection; @@ -20,6 +21,7 @@ use axum::{Extension, Json}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; pub const MAX_BODY_BYTES: usize = 64 * 1024; @@ -544,15 +546,46 @@ pub async fn login( Extension(ClientIp(ip)): Extension, JsonBody(b): JsonBody, ) -> Result { - let auth = state.auth.clone(); let now = unix_now(); + // Whatever can be refused without Argon2 is, before the queue for a permit, + // or a flood of hopeless attempts would stand in front of the owner. + let auth = state.auth.clone(); + let username = b.username; + let mut queued = blocking(move || { + let attempt = auth.login_begin(&username, ip, now)?; + Ok(QueuedLogin { + auth, + attempt: Some(attempt), + }) + }) + .await?; + let password = b.password; let step = hashing(&state, move || { - auth.login(&b.username, &b.password, ip, now) + let attempt = queued + .attempt + .take() + .ok_or(AuthFailure::InvalidCredentials)?; + queued.auth.login_finish(attempt, &password, now) }) .await?; Ok(step_reply(&state, &step)) } +/// A login between its checks and its evaluation. A client that disconnects +/// while queued made no guess, so what it reserved goes back. +struct QueuedLogin { + auth: Arc, + attempt: Option, +} + +impl Drop for QueuedLogin { + fn drop(&mut self) { + if let Some(attempt) = self.attempt.take() { + self.auth.login_abandon(attempt); + } + } +} + #[derive(Deserialize)] pub struct MfaBody { pending: String, diff --git a/crates/acaua-cli/src/web_tests.rs b/crates/acaua-cli/src/web_tests.rs index f24f09d..c5d86d5 100644 --- a/crates/acaua-cli/src/web_tests.rs +++ b/crates/acaua-cli/src/web_tests.rs @@ -86,6 +86,20 @@ fn fresh(transport: Transport) -> (tempfile::TempDir, Arc, Router) (dir, auth, build_app(state)) } +fn fresh_with_state( + transport: Transport, +) -> (tempfile::TempDir, Arc, AppState, Router) { + let dir = tempfile::tempdir().unwrap(); + let auth = Arc::new(AuthService::open(dir.path(), None).unwrap()); + let state = AppState::new( + Arc::new(Storage::open(dir.path()).unwrap()), + auth.clone(), + transport, + ); + let app = build_app(state.clone()); + (dir, auth, state, app) +} + /// Server with `root` (admin, MFA active) and analyst `ana` (no MFA). fn harness(transport: Transport) -> H { let (dir, auth, app) = fresh(transport); @@ -1180,3 +1194,90 @@ async fn auth_state_tells_whether_mfa_is_on() { let on = send(&h.app, state(&cookie)).await; assert_eq!(on.json()["mfa_enabled"], serde_json::json!(true)); } + +async fn login_from(app: &Router, peer: IpAddr, user: &str, pw: &str) -> Reply { + let mut r = post_json( + "/api/auth/login", + serde_json::json!({"username": user, "password": pw}), + ); + r.extensions_mut() + .insert(axum::extract::ConnectInfo(SocketAddr::new(peer, 4000))); + send(app, r).await +} + +fn v4_peer(i: u32) -> IpAddr { + IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i)) +} + +fn spend_budget(auth: &AuthService, user: &str, n: u32, t: u64) { + for i in 0..n { + let attempt = auth.login_begin(user, v4_peer(i), t).unwrap(); + let _ = auth.login_failed(attempt, t); + } +} + +#[tokio::test] +async fn a_refused_login_takes_no_hashing_permit() { + let (_d, auth, state, app) = fresh_with_state(Transport::Local); + let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); + auth.complete_bootstrap(&code, "root", PW, peer(), now()) + .unwrap(); + auth.create_user("root", "ana", PW, Role::Analyst, now()) + .unwrap(); + spend_budget(&auth, "ana", 100, now()); + let held = state + .argon2 + .clone() + .acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32) + .await + .unwrap(); + let refused = tokio::time::timeout( + std::time::Duration::from_secs(5), + login_from(&app, v4_peer(500), "ana", PW), + ) + .await + .expect("a refusal must not wait for a permit"); + assert_eq!(refused.status, StatusCode::TOO_MANY_REQUESTS); + assert!(refused.headers.contains_key(header::RETRY_AFTER)); + // An attempt that can still succeed does wait for one. + let waits = tokio::time::timeout( + std::time::Duration::from_millis(300), + login_from(&app, v4_peer(501), "root", PW), + ) + .await; + assert!(waits.is_err()); + drop(held); + // That cancelled attempt gave back what it held. + assert_eq!( + login_from(&app, v4_peer(501), "root", PW).await.status, + StatusCode::OK + ); +} + +#[tokio::test] +async fn parallel_requests_stop_at_the_cap() { + let (_d, auth, _state, app) = fresh_with_state(Transport::Local); + let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); + auth.complete_bootstrap(&code, "root", PW, peer(), now()) + .unwrap(); + auth.create_user("root", "ana", PW, Role::Analyst, now()) + .unwrap(); + spend_budget(&auth, "ana", 96, now()); + let mut tasks = Vec::new(); + for i in 0..16 { + let app = app.clone(); + tasks.push(tokio::spawn(async move { + login_from(&app, v4_peer(1000 + i), "ana", PW2).await.status + })); + } + let mut wrong = 0; + let mut refused = 0; + for t in tasks { + match t.await.unwrap() { + StatusCode::UNAUTHORIZED => wrong += 1, + StatusCode::TOO_MANY_REQUESTS => refused += 1, + other => panic!("{other}"), + } + } + assert_eq!((wrong, refused), (4, 12)); +} diff --git a/crates/acaua-core/src/auth/mod.rs b/crates/acaua-core/src/auth/mod.rs index 61deca4..55595f6 100644 --- a/crates/acaua-core/src/auth/mod.rs +++ b/crates/acaua-core/src/auth/mod.rs @@ -12,8 +12,12 @@ pub mod tokens; pub use audit::{AuditEntry, AuditEvent, AuditLog}; pub use secrets::{hash_token, random_token, Secrets}; -pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment, UserView}; -pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Role, Scope, Session, User}; +pub use service::{ + AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa, TotpEnrollment, UserView, +}; +pub use store::{ + ApiToken, AuthState, AuthStore, Bootstrap, KnownAddress, Role, Scope, Session, User, +}; pub use tokens::{csrf_matches, csrf_token, NewToken, Principal, SessionView, TokenView, Via}; use crate::error::Result; diff --git a/crates/acaua-core/src/auth/service.rs b/crates/acaua-core/src/auth/service.rs index abff896..259ea76 100644 --- a/crates/acaua-core/src/auth/service.rs +++ b/crates/acaua-core/src/auth/service.rs @@ -10,8 +10,10 @@ use super::credentials::{ hash_password, hash_recovery_code, new_recovery_codes, new_totp_secret, normalize, totp_uri_and_qr, validate_password, verify_password, verify_totp, }; -use super::store::{AuthState, AuthStore, Bootstrap, Role, Scope, Session, User}; -use super::throttle::{decayed, lock_until, IpLimiter, LoginThrottle}; +use super::store::{AuthState, AuthStore, Bootstrap, KnownAddress, Role, Scope, Session, User}; +use super::throttle::{ + address_key, decayed, lock_until, BudgetState, IpLimiter, LoginThrottle, BUDGET_MAX_FAILURES, +}; use super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets}; use crate::error::{AcauaError, AuthFailure, Result}; use serde::{Deserialize, Serialize}; @@ -29,6 +31,9 @@ const SESSION_ABSOLUTE_SECS: u64 = 43_200; const USERNAME_MAX_CHARS: usize = 64; const ID_BYTES: usize = 16; const TEMP_PASSWORD_BYTES: usize = 24; +/// A completed login makes its address known for this long. +const KNOWN_ADDRESS_SECS: u64 = 30 * 86_400; +const KNOWN_ADDRESS_MAX: usize = 10; /// A session just created. The token exists only here; the store has its hash. pub struct NewSession { @@ -98,12 +103,40 @@ pub struct UserView { pub must_change_password: bool, } +struct Known { + id: String, + name: String, + hash: String, +} + +/// A login that passed every check that needs no Argon2. Holds reservations: +/// see `AuthService::login_begin`. +pub struct LoginAttempt { + throttle_key: String, + /// `None` for a username with no account. + account: Option, + ip: IpAddr, + /// Hash that makes `ip` known to this account once the login completes. + address: String, + /// The reservation was charged to the budget. + budgeted: bool, +} + +impl std::fmt::Debug for LoginAttempt { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LoginAttempt()") + } +} + #[derive(Serialize, Deserialize)] struct PendingClaims { purpose: String, user_id: String, epoch: u64, exp: u64, + /// Address hash of the password step, known once the login completes. + #[serde(default)] + address: Option, } pub struct AuthService { @@ -242,9 +275,60 @@ fn issue_session(st: &mut AuthState, user_id: &str, now: u64) -> NewSession { } } +/// Only ever a hash, salted per account so lists cannot be compared. The IPv4 +/// space is small enough to enumerate for someone who can read `state.json`, who +/// has far better things to take from it. +fn address_hash(user_id: &str, ip: IpAddr) -> String { + hash_token(&format!("known-address\0{user_id}\0{}", address_key(ip))) +} + +fn is_known(u: &User, hash: &str, now: u64) -> bool { + u.known_addresses + .iter() + .any(|k| k.hash == hash && now.saturating_sub(k.last_seen) < KNOWN_ADDRESS_SECS) +} + +fn remember_address(u: &mut User, hash: &str, now: u64) { + let list = &mut u.known_addresses; + list.retain(|k| k.hash != hash && now.saturating_sub(k.last_seen) < KNOWN_ADDRESS_SECS); + list.push(KnownAddress { + hash: hash.to_string(), + last_seen: now, + }); + while list.len() > KNOWN_ADDRESS_MAX { + let oldest = list + .iter() + .enumerate() + .min_by_key(|(_, k)| k.last_seen) + .map(|(i, _)| i); + match oldest { + Some(i) => list.remove(i), + None => break, + }; + } +} + +fn stored_budget(u: &User) -> BudgetState { + BudgetState { + failures: u.budget_failures, + last: u.budget_at, + audited_at: u.budget_audited_at, + generation: u.budget_generation, + } +} + /// Clears the throttle, voids outstanding pending tokens and opens a session. -fn complete_login(st: &mut AuthState, user_id: &str, now: u64) -> Result { +/// `address` is where the login came from, the only thing that makes one known. +fn complete_login( + st: &mut AuthState, + user_id: &str, + address: Option<&str>, + now: u64, +) -> Result { let u = user_or_missing(st, user_id)?; + if let Some(hash) = address { + remember_address(u, hash, now); + } u.failed_attempts = 0; u.locked_until = 0; u.auth_epoch = u.auth_epoch.wrapping_add(1); @@ -258,6 +342,7 @@ fn finish_required_change( st: &mut AuthState, user_id: &str, ticket_epoch: u64, + address: Option<&str>, now: u64, ) -> Result { let u = user_mut(st, user_id).ok_or_else(invalid)?; @@ -267,7 +352,7 @@ fn finish_required_change( { return Err(invalid()); } - complete_login(st, user_id, now) + complete_login(st, user_id, address, now) } fn bootstrap_valid(st: &AuthState, code_hash: &str, now: u64) -> bool { @@ -389,7 +474,13 @@ impl AuthService { password_hash: password_hash.clone(), ..Default::default() }); - Ok(Some(self.seal_pending(&id, 0, PENDING_PURPOSE, now)?)) + Ok(Some(self.seal_pending( + &id, + 0, + PENDING_PURPOSE, + None, + now, + )?)) })?; let Some(pending) = done else { return self.refuse_bootstrap(ip); @@ -412,6 +503,7 @@ impl AuthService { user_id: &str, epoch: u64, purpose: &str, + address: Option<&str>, now: u64, ) -> Result { let exp = now.saturating_add(PENDING_TTL_SECS); @@ -420,6 +512,7 @@ impl AuthService { user_id: user_id.to_string(), epoch, exp, + address: address.map(str::to_string), }; Ok(PendingMfa { token: self.secrets.seal(&serde_json::to_vec(&claims)?)?, @@ -438,14 +531,16 @@ impl AuthService { } /// First factor. Unknown user and wrong password are indistinguishable: - /// same error, same Argon2 cost, same throttle schedule, and no store write - /// for either. A refused attempt writes nothing at all. + /// same error, same Argon2 cost, same throttle schedule. pub fn login(&self, username: &str, password: &str, ip: IpAddr, now: u64) -> Result { - struct Known { - id: String, - name: String, - hash: String, - } + let attempt = self.login_begin(username, ip, now)?; + self.login_finish(attempt, password, now) + } + + /// Everything that can refuse a login without Argon2. On `Ok` the attempt + /// already counts as a failure: pass it to `login_finish`, or to + /// `login_abandon` if it will never be evaluated. A refusal writes nothing. + pub fn login_begin(&self, username: &str, ip: IpAddr, now: u64) -> Result { self.ips.acquire(ip, now).map_err(throttled)?; let key = username_key(username); let found = self.store.read(|st| { @@ -453,10 +548,18 @@ impl AuthService { st.users .iter() .find(|u| username_key(&u.username) == key) - .map(|u| Known { - id: u.id.clone(), - name: u.username.clone(), - hash: u.password_hash.clone(), + .map(|u| { + let address = address_hash(&u.id, ip); + ( + Known { + id: u.id.clone(), + name: u.username.clone(), + hash: u.password_hash.clone(), + }, + is_known(u, &address, now), + address, + stored_budget(u), + ) }) }) })?; @@ -464,29 +567,100 @@ impl AuthService { self.ips.release(ip); return Err(AuthFailure::SetupRequired.into()); }; + // A name with no account is never known; its budget lives only in the + // throttle's table. + let (account, known, address, stored) = match found { + Some((account, known, address, stored)) => (Some(account), known, address, stored), + None => (None, false, String::new(), BudgetState::default()), + }; // The hash keeps a password typed into the wrong field out of memory. let throttle_key = hash_token(&key); - if let Err(left) = self.logins.acquire(&throttle_key, ip, now) { - self.ips.release(ip); - return Err(throttled(left)); - } - let Some(Known { id, name, hash }) = found else { - verify_password(None, password); - // The typed name stays out of the log: it may be a password - // entered in the wrong field. - self.log("login", None, Some(ip), false, Some("invalid credentials"))?; - return Err(invalid()); + let budgeted = match self.logins.acquire(&throttle_key, ip, known, stored, now) { + Ok(budgeted) => budgeted, + Err(left) => { + self.ips.release(ip); + return Err(throttled(left)); + } }; - if !verify_password(Some(&hash), password) { - self.log( - "login", - Some(&name), - Some(ip), - false, - Some("invalid credentials"), - )?; - return Err(invalid()); + Ok(LoginAttempt { + throttle_key, + account, + ip, + address, + budgeted, + }) + } + + /// Returns the reservations of an attempt that was never evaluated. + pub fn login_abandon(&self, attempt: LoginAttempt) { + self.ips.release(attempt.ip); + self.logins + .abandon(&attempt.throttle_key, attempt.ip, attempt.budgeted); + } + + /// Records an evaluated failure and returns its refusal. + pub fn login_failed(&self, attempt: LoginAttempt, now: u64) -> Result { + let note = if attempt.budgeted { + self.logins.failed(&attempt.throttle_key, now) + } else { + Default::default() + }; + let id = attempt.account.as_ref().map(|k| k.id.as_str()); + if let Some(state) = note.write { + // A name with no account writes too, with nothing to store: a real + // name must not answer slower once a minute. + self.store.update(|st| { + if let Some(u) = id + .and_then(|id| user_mut(st, id)) + .filter(|u| u.budget_generation == state.generation) + { + u.budget_failures = state.failures; + u.budget_at = state.last; + u.budget_audited_at = state.audited_at; + } + Ok(()) + })?; } + let name = attempt.account.map(|k| k.name); + // An unknown name stays out of the log: it may be a password entered + // in the wrong field. + self.log( + "login", + name.as_deref(), + Some(attempt.ip), + false, + Some("invalid credentials"), + )?; + if note.audit { + self.log( + "login.budget_exhausted", + name.as_deref(), + None, + false, + Some(&format!( + "{BUDGET_MAX_FAILURES}+ failures from unknown addresses in 24 h" + )), + )?; + } + Err(invalid()) + } + + /// Runs Argon2 for an attempt `login_begin` let through. + pub fn login_finish( + &self, + attempt: LoginAttempt, + password: &str, + now: u64, + ) -> Result { + let Some(known) = &attempt.account else { + verify_password(None, password); + return self.login_failed(attempt, now); + }; + if !verify_password(Some(&known.hash), password) { + return self.login_failed(attempt, now); + } + let (id, name, hash) = (known.id.clone(), known.name.clone(), known.hash.clone()); + let address = attempt.address.as_str(); let step = self.store.update(|st| { // The account may have changed while Argon2 ran. let Some(u) = user_mut(st, &id).filter(|u| u.password_hash == hash) else { @@ -494,40 +668,47 @@ impl AuthService { }; let epoch = u.auth_epoch; let step = if u.totp_sealed.is_some() { - LoginStep::MfaRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?) + LoginStep::MfaRequired(self.seal_pending( + &id, + epoch, + PENDING_PURPOSE, + Some(address), + now, + )?) } else if u.role == Role::Admin { - LoginStep::MfaEnrollRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?) + LoginStep::MfaEnrollRequired(self.seal_pending( + &id, + epoch, + PENDING_PURPOSE, + Some(address), + now, + )?) } else if u.must_change_password { LoginStep::PasswordChangeRequired(self.seal_pending( &id, epoch, PASSWORD_CHANGE_PURPOSE, + Some(address), now, )?) } else { - LoginStep::Session(complete_login(st, &id, now)?) + LoginStep::Session(complete_login(st, &id, Some(address), now)?) }; Ok(Some(step)) })?; let Some(step) = step else { - self.log( - "login", - Some(&name), - Some(ip), - false, - Some("invalid credentials"), - )?; - return Err(invalid()); + return self.login_failed(attempt, now); }; - self.ips.release(ip); - self.logins.right_password(&throttle_key, ip); + self.ips.release(attempt.ip); + self.logins + .right_password(&attempt.throttle_key, attempt.ip, attempt.budgeted); let detail = match step { LoginStep::Session(_) => "session", LoginStep::MfaRequired(_) => "mfa required", LoginStep::MfaEnrollRequired(_) => "mfa enrollment required", LoginStep::PasswordChangeRequired(_) => "password change required", }; - self.log("login", Some(&name), Some(ip), true, Some(detail))?; + self.log("login", Some(&name), Some(attempt.ip), true, Some(detail))?; Ok(step) } @@ -572,10 +753,16 @@ impl AuthService { &claims.user_id, u.auth_epoch, PASSWORD_CHANGE_PURPOSE, + claims.address.as_deref(), now, )?) } else { - LoginStep::Session(complete_login(st, &claims.user_id, now)?) + LoginStep::Session(complete_login( + st, + &claims.user_id, + claims.address.as_deref(), + now, + )?) }; Ok(Outcome::Done { step, name, method }) })?; @@ -710,6 +897,7 @@ impl AuthService { u.totp_pending_sealed = None; u.totp_last_step = Some(step); u.recovery_hashes = hashes; + u.known_addresses.clear(); end_sessions(st, user_id, None); drop_admin_tokens(st, user_id); Ok((name, true)) @@ -876,6 +1064,7 @@ impl AuthService { refund_attempt(u); u.password_hash = new_hash; u.must_change_password = false; + u.known_addresses.clear(); u.auth_epoch = u.auth_epoch.wrapping_add(1); end_sessions(st, user_id, keep_session_token); drop_admin_tokens(st, user_id); @@ -907,8 +1096,15 @@ impl AuthService { return Err(invalid()); } self.change_password(&claims.user_id, current, new, None, now)?; - self.store - .update(|st| finish_required_change(st, &claims.user_id, claims.epoch, now)) + self.store.update(|st| { + finish_required_change( + st, + &claims.user_id, + claims.epoch, + claims.address.as_deref(), + now, + ) + }) } /// Refused for administrators, and when MFA is already off, which changes @@ -933,6 +1129,7 @@ impl AuthService { u.totp_pending_sealed = None; u.totp_last_step = None; u.recovery_hashes.clear(); + u.known_addresses.clear(); end_sessions(st, user_id, keep_session_token); drop_admin_tokens(st, user_id); Ok(name) @@ -946,8 +1143,9 @@ impl AuthService { /// Local recovery for anyone who lost access: removes MFA, sessions and /// tokens, clears the user-bound throttle, and returns a temporary password /// that is shown once. The next login must change the password before any - /// ordinary session; an administrator must enroll MFA again first. Login - /// counts live in the daemon's memory and are not touched from here. + /// ordinary session; an administrator must enroll MFA again first. Clears the + /// known addresses and the login budget; a running daemon notices through + /// `budget_generation`. pub fn reset_account(&self, username: &str, _now: u64) -> Result { let key = username_key(username); let temp = random_token(TEMP_PASSWORD_BYTES); @@ -968,6 +1166,11 @@ impl AuthService { u.recovery_hashes.clear(); u.failed_attempts = 0; u.locked_until = 0; + u.known_addresses.clear(); + u.budget_failures = 0; + u.budget_at = 0; + u.budget_audited_at = 0; + u.budget_generation = u.budget_generation.wrapping_add(1); u.auth_epoch = u.auth_epoch.wrapping_add(1); let (id, name) = (u.id.clone(), u.username.clone()); end_sessions(st, &id, None); diff --git a/crates/acaua-core/src/auth/service_tests.rs b/crates/acaua-core/src/auth/service_tests.rs index 844512b..4dac719 100644 --- a/crates/acaua-core/src/auth/service_tests.rs +++ b/crates/acaua-core/src/auth/service_tests.rs @@ -380,7 +380,7 @@ fn same_error_for_unknown_user_and_bad_password() { assert_eq!(unknown, bad); assert_eq!(unknown.to_string(), bad.to_string()); // The throttle must not tell them apart either, per address or past the - // account-wide limit. + // failure budget. let spent: IpAddr = "192.0.2.2".parse().unwrap(); for _ in 0..5 { let _ = s.login("ghost", PW, spent, T0); @@ -398,7 +398,9 @@ fn same_error_for_unknown_user_and_bad_password() { for name in ["ghost", "ana"] { for i in 0..100u32 { let addr = IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i)); - let _ = s.logins.acquire(&hash_token(name), addr, T0); + let _ = s + .logins + .acquire(&hash_token(name), addr, false, Default::default(), T0); } } let fresh: IpAddr = "192.0.2.3".parse().unwrap(); @@ -407,7 +409,7 @@ fn same_error_for_unknown_user_and_bad_password() { assert_eq!( unknown, AuthFailure::Throttled { - retry_after_secs: 60 + retry_after_secs: crate::auth::throttle::BUDGET_DECAY_SECS } ); assert_eq!(unknown, bad); @@ -536,26 +538,34 @@ fn user_bound_failures_decay_over_time() { } #[test] -fn wrong_passwords_and_refusals_write_no_state() { +fn refusals_write_nothing_and_failures_store_only_the_budget() { let (_d, s) = svc(); admin(&s); - analyst(&s, "ana"); + let id = analyst(&s, "ana"); let state = s.auth_dir.join(crate::auth::STATE_FILE); let before = std::fs::read(&state).unwrap(); - let modified = std::fs::metadata(&state).unwrap().modified().unwrap(); + // A name with no account leaves no trace in the state. for _ in 0..8 { - let _ = s.login("ana", WRONG, ip(), T0); let _ = s.login("ghost", WRONG, ip(), T0); } assert_eq!(std::fs::read(&state).unwrap(), before); + for _ in 0..8 { + let _ = s.login("ana", WRONG, ip(), T0); + } + let u = user_of(&s, &id); + assert_eq!((u.budget_failures, u.budget_at), (1, T0), "written once"); + assert_eq!(u.failed_attempts, 0); + // Refusals reach neither the state nor the audit log. + let before = std::fs::read(&state).unwrap(); + let modified = std::fs::metadata(&state).unwrap().modified().unwrap(); + let lines = s.audit_tail(1000).unwrap().len(); + let _ = s.login("ana", WRONG, ip(), T0); + assert_eq!(s.audit_tail(1000).unwrap().len(), lines); + assert_eq!(std::fs::read(&state).unwrap(), before); assert_eq!( std::fs::metadata(&state).unwrap().modified().unwrap(), modified ); - // Refusals do not reach the audit log either. - let lines = s.audit_tail(1000).unwrap().len(); - let _ = s.login("ana", WRONG, ip(), T0); - assert_eq!(s.audit_tail(1000).unwrap().len(), lines); } #[test] @@ -580,7 +590,7 @@ fn required_change_final_step_refuses_a_changed_account() { let ana = analyst(&s, "ana"); let finish = |id: &str, epoch: u64| { s.store - .update(|st| finish_required_change(st, id, epoch, T0)) + .update(|st| finish_required_change(st, id, epoch, None, T0)) }; // An administrator without MFA, as after a promotion in between. let epoch = s @@ -1212,3 +1222,368 @@ fn csrf_value_is_bound_to_the_session_and_is_not_its_token_hash() { assert!(!crate::auth::tokens::csrf_matches("session-b", &a)); assert!(!crate::auth::tokens::csrf_matches("session-a", "")); } + +// ---- Failure budget -------------------------------------------------------- + +const DAY: u64 = 86_400; + +fn v4(i: u32) -> IpAddr { + IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i)) +} + +/// Spends `n` failures from distinct addresses, without the cost of Argon2; +/// `login_failed` is what a wrong password ends in. +fn burn(s: &AuthService, name: &str, n: u32, first: u32, now: u64) -> u32 { + let mut evaluated = 0; + for i in 0..n { + if let Ok(a) = s.login_begin(name, v4(first + i), now) { + evaluated += 1; + let _ = s.login_failed(a, now); + } + } + evaluated +} + +fn user_of(s: &AuthService, id: &str) -> User { + s.store + .read(|st| st.users.iter().find(|u| u.id == id).unwrap().clone()) + .unwrap() +} + +fn exhausted_events(s: &AuthService) -> Vec { + s.audit_tail(100_000) + .unwrap() + .into_iter() + .filter(|e| e.event.action == "login.budget_exhausted") + .collect() +} + +const OWNER: &str = "203.0.113.50"; + +#[test] +fn budget_stops_a_distributed_guesser_before_argon2() { + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + assert_eq!(burn(&s, "ana", 1000, 0, T0), 100); + let fresh: IpAddr = "198.51.100.200".parse().unwrap(); + // `login_begin` is all that runs before Argon2. + assert!(matches!( + failure(s.login_begin("ana", fresh, T0)), + AuthFailure::Throttled { retry_after_secs } if retry_after_secs > 0 + )); + assert!(matches!( + failure(s.login("ana", PW, fresh, T0)), + AuthFailure::Throttled { .. } + )); + // A cap, not a delay: waiting a minute or an hour gets no guess through. + assert!(s.login_begin("ana", fresh, T0 + 61).is_err()); + assert!(s.login_begin("ana", fresh, T0 + 800).is_err()); +} + +#[test] +fn a_known_address_logs_in_during_exhaustion_and_a_session_survives() { + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + let owner: IpAddr = OWNER.parse().unwrap(); + let live = session_of(s.login("ana", PW, owner, T0).unwrap()); + burn(&s, "ana", 100, 0, T0 + 1); + session_of(s.login("ana", PW, owner, T0 + 1).unwrap()); + assert!(s.authenticate_session(&live.token, T0 + 1).is_ok()); + let stranger: IpAddr = "198.51.100.200".parse().unwrap(); + assert!(matches!( + failure(s.login("ana", PW, stranger, T0 + 1)), + AuthFailure::Throttled { .. } + )); + // Still under the pair throttle. + for _ in 0..5 { + assert_eq!( + failure(s.login("ana", WRONG, owner, T0 + 2)), + AuthFailure::InvalidCredentials + ); + } + assert!(matches!( + failure(s.login("ana", PW, owner, T0 + 2)), + AuthFailure::Throttled { .. } + )); +} + +#[test] +fn a_known_address_requires_the_full_login_and_expires() { + let (_d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + enroll(&s, &id, T0); + let owner: IpAddr = OWNER.parse().unwrap(); + let p = pending_of(s.login("ana", PW, owner, T0 + 60).unwrap()); + assert!( + user_of(&s, &id).known_addresses.is_empty(), + "password alone" + ); + let _ = s.confirm_mfa(&p.token, "000000", T0 + 60); + assert!(user_of(&s, &id).known_addresses.is_empty(), "wrong code"); + let code = code_at(&s, &id, T0 + 90); + session_of(s.confirm_mfa(&p.token, &code, T0 + 90).unwrap()); + assert_eq!(user_of(&s, &id).known_addresses.len(), 1); + burn(&s, "ana", 100, 0, T0 + 100); + assert!(s.login_begin("ana", owner, T0 + 100).is_ok()); + // Past 30 days the entry is worth nothing, while a new attack exhausts. + let later = T0 + 31 * DAY; + burn(&s, "ana", 100, 1000, later); + assert!(s.login_begin("ana", owner, later).is_err()); +} + +#[test] +fn the_known_list_is_bounded_and_holds_no_raw_address() { + let (d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + for i in 0..12u32 { + session_of(s.login("ana", PW, v4(i), T0 + u64::from(i)).unwrap()); + } + let known = user_of(&s, &id).known_addresses; + assert_eq!(known.len(), 10); + assert_eq!(known.iter().map(|k| k.last_seen).min(), Some(T0 + 2)); + let state = std::fs::read_to_string(d.path().join("auth/state.json")).unwrap(); + assert!(!state.contains("10.0.0."), "raw address stored"); +} + +#[test] +fn a_48_counts_as_one_address() { + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + for i in 0..5 { + let ip: IpAddr = format!("2001:db8:1:{i:x}::1").parse().unwrap(); + assert_eq!( + failure(s.login("ana", WRONG, ip, T0)), + AuthFailure::InvalidCredentials + ); + } + let same: IpAddr = "2001:db8:1:ffff::2".parse().unwrap(); + assert!(matches!( + failure(s.login("ana", PW, same, T0)), + AuthFailure::Throttled { .. } + )); + // Known by prefix too, and a mapped IPv4 is the IPv4. + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + session_of( + s.login("ana", PW, "2001:db8:2:1::1".parse().unwrap(), T0) + .unwrap(), + ); + session_of( + s.login("ana", PW, "203.0.113.9".parse().unwrap(), T0) + .unwrap(), + ); + burn(&s, "ana", 100, 0, T0); + assert!(s + .login_begin("ana", "2001:db8:2:ffff::9".parse().unwrap(), T0) + .is_ok()); + assert!(s + .login_begin("ana", "::ffff:203.0.113.9".parse().unwrap(), T0) + .is_ok()); + assert!(s + .login_begin("ana", "2001:db8:3::1".parse().unwrap(), T0) + .is_err()); +} + +#[test] +fn the_budget_decays_and_survives_reopening() { + let (d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + burn(&s, "ana", 100, 0, T0); + let reopened = AuthService::open(d.path(), None).unwrap(); + let fresh: IpAddr = "198.51.100.200".parse().unwrap(); + assert!(reopened.login_begin("ana", fresh, T0 + 1).is_err()); + // One failure fades per 864 s, so one guess fits and no more. + let later = T0 + 864; + assert_eq!(burn(&reopened, "ana", 5, 500, later), 1); + // A day later the budget is back. + assert_eq!(burn(&reopened, "ana", 100, 600, later + DAY), 100); +} + +#[test] +fn budget_writes_are_coalesced_and_a_refusal_writes_nothing() { + let (d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + burn(&s, "ana", 3, 0, T0); + assert_eq!(user_of(&s, &id).budget_failures, 1, "first failure writes"); + burn(&s, "ana", 1, 10, T0 + 59); + assert_eq!(user_of(&s, &id).budget_failures, 1, "within the minute"); + burn(&s, "ana", 1, 20, T0 + 60); + assert_eq!(user_of(&s, &id).budget_failures, 5); + burn(&s, "ana", 95, 100, T0 + 120); + let path = d.path().join("auth/state.json"); + let before = std::fs::read(&path).unwrap(); + assert_eq!(user_of(&s, &id).budget_failures, 100, "the crossing writes"); + assert_eq!(burn(&s, "ana", 10, 300, T0 + 121), 0); + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn an_unknown_username_exhausts_like_a_real_one() { + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + let run = |name: &str| -> Vec> { + let mut seen = Vec::new(); + for (step, now) in [(90u32, T0), (20, T0 + 100), (3, T0 + 864), (3, T0 + 2000)] { + for i in 0..step { + seen.push(match s.login_begin(name, v4(10_000 + i), now) { + Ok(a) => { + let _ = s.login_failed(a, now); + Ok(()) + } + Err(AcauaError::Auth(AuthFailure::Throttled { retry_after_secs })) => { + Err(retry_after_secs) + } + Err(other) => panic!("{other}"), + }); + } + } + seen + }; + // Pairs differ per name, so both use the same addresses in order. + let real = run("ana"); + let ghost = run("nobody"); + assert_eq!(real, ghost); + assert!(real.iter().any(|r| r.is_err())); +} + +#[test] +fn exhaustion_is_audited_once_per_window_without_a_guessed_name() { + let (d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + burn(&s, "ana", 300, 0, T0); + let events = exhausted_events(&s); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.actor.as_deref(), Some("ana")); + assert!(events[0].event.detail.as_deref().unwrap().contains("100")); + // Hovering at the cap, reopened or not, stays quiet inside the window. + let s = AuthService::open(d.path(), None).unwrap(); + burn(&s, "ana", 5, 400, T0 + 864); + assert_eq!(exhausted_events(&s).len(), 1); + // Still under attack a day later: one more. + burn(&s, "ana", 100, 500, T0 + DAY + 1); + assert_eq!(exhausted_events(&s).len(), 2); + + burn(&s, "secret-typed-in-wrong-field", 100, 700, T0); + let events = exhausted_events(&s); + assert_eq!(events.len(), 3); + let last = serde_json::to_string(events.last().unwrap()).unwrap(); + assert!(!last.contains("secret-typed"), "{last}"); + assert_eq!(events[2].event.actor, None); +} + +#[test] +fn credential_changes_clear_known_addresses_and_reset_reopens_login() { + let (d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + let owner: IpAddr = OWNER.parse().unwrap(); + let live = session_of(s.login("ana", PW, owner, T0).unwrap()); + assert_eq!(user_of(&s, &id).known_addresses.len(), 1); + s.change_password(&id, PW, PW2, Some(&live.token), T0) + .unwrap(); + assert!(user_of(&s, &id).known_addresses.is_empty(), "password"); + + session_of(s.login("ana", PW2, owner, T0).unwrap()); + enroll(&s, &id, T0); + assert!(user_of(&s, &id).known_addresses.is_empty(), "enrolling"); + let p = pending_of(s.login("ana", PW2, owner, T0 + 60).unwrap()); + let code = code_at(&s, &id, T0 + 60); + session_of(s.confirm_mfa(&p.token, &code, T0 + 60).unwrap()); + assert_eq!(user_of(&s, &id).known_addresses.len(), 1); + s.disable_mfa("ana", &id, None, T0 + 60).unwrap(); + assert!(user_of(&s, &id).known_addresses.is_empty(), "disabling"); + + session_of(s.login("ana", PW2, owner, T0 + 60).unwrap()); + burn(&s, "ana", 100, 0, T0 + 60); + // A locked owner on a new address. The CLI is another process. + let stranger: IpAddr = "198.51.100.200".parse().unwrap(); + assert!(s.login_begin("ana", stranger, T0 + 61).is_err()); + let cli = AuthService::open(d.path(), None).unwrap(); + let temp = cli.reset_account("ana", T0 + 61).unwrap(); + let u = user_of(&s, &id); + assert!(u.known_addresses.is_empty()); + assert_eq!(u.budget_failures, 0); + assert!(matches!( + s.login("ana", &temp, stranger, T0 + 62).unwrap(), + LoginStep::PasswordChangeRequired(_) + )); +} + +#[test] +fn a_required_password_change_makes_the_address_known() { + let (_d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + let temp = s.reset_account("ana", T0).unwrap(); + let owner: IpAddr = OWNER.parse().unwrap(); + let LoginStep::PasswordChangeRequired(t) = s.login("ana", &temp, owner, T0).unwrap() else { + panic!("expected a ticket"); + }; + assert!(user_of(&s, &id).known_addresses.is_empty()); + s.change_required_password(&t.token, &temp, PW2, T0) + .unwrap(); + assert_eq!(user_of(&s, &id).known_addresses.len(), 1); +} + +#[test] +fn a_flood_of_junk_usernames_keeps_a_real_budget() { + let (_d, mut s) = svc(); + s.logins = LoginThrottle::with_capacity(64, 16); + admin(&s); + analyst(&s, "ana"); + assert_eq!(burn(&s, "ana", 50, 0, T0), 50); + for i in 0..200 { + // Newer than the real entry, which is what an oldest-first eviction drops. + burn(&s, &format!("junk{i}"), 1, 1000 + i, T0 + 1); + } + assert_eq!( + burn(&s, "ana", 60, 2000, T0 + 1), + 50, + "the budget stayed spent" + ); +} + +#[test] +fn parallel_attempts_cannot_overrun_the_cap() { + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + let s = std::sync::Arc::new(s); + let handles: Vec<_> = (0..8u32) + .map(|t| { + let s = s.clone(); + std::thread::spawn(move || { + (0..50u32) + .filter(|i| s.login_begin("ana", v4(t * 100 + i), T0).is_ok()) + .count() + }) + }) + .collect(); + let through: usize = handles.into_iter().map(|h| h.join().unwrap()).sum(); + assert_eq!(through, 100); +} + +#[test] +fn an_abandoned_attempt_returns_its_reservations() { + let (_d, s) = svc(); + admin(&s); + analyst(&s, "ana"); + let held: Vec<_> = (0..100u32) + .map(|i| s.login_begin("ana", v4(i), T0).unwrap()) + .collect(); + assert!(s.login_begin("ana", v4(500), T0).is_err()); + for a in held { + s.login_abandon(a); + } + assert_eq!(burn(&s, "ana", 100, 600, T0), 100); +} diff --git a/crates/acaua-core/src/auth/store.rs b/crates/acaua-core/src/auth/store.rs index de88194..c7abbcb 100644 --- a/crates/acaua-core/src/auth/store.rs +++ b/crates/acaua-core/src/auth/store.rs @@ -50,6 +50,27 @@ pub struct User { pub auth_epoch: u64, /// Set by `reset_account`: no ordinary session until the password changes. pub must_change_password: bool, + /// Addresses of recent completed logins, for `throttle`'s budget exception. + /// Hashes only: never a raw address. + pub known_addresses: Vec, + /// Login failures from unknown addresses, as last written. The daemon's + /// memory leads this by at most a minute. + pub budget_failures: u32, + /// Start of the current decay period of `budget_failures`. + pub budget_at: u64, + /// When `login.budget_exhausted` was last audited for this account. + pub budget_audited_at: u64, + /// Moved by `reset_account`, which may run in another process: the daemon + /// drops what it holds in memory for this account when this changes. + pub budget_generation: u64, +} + +/// A hashed address prefix and when a login from it last completed. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct KnownAddress { + pub hash: String, + pub last_seen: u64, } impl std::fmt::Debug for User { diff --git a/crates/acaua-core/src/auth/throttle.rs b/crates/acaua-core/src/auth/throttle.rs index 95a66e3..85c3384 100644 --- a/crates/acaua-core/src/auth/throttle.rs +++ b/crates/acaua-core/src/auth/throttle.rs @@ -1,11 +1,12 @@ //! Attempt limits: the delay schedule, the in-memory IP limiter and the //! in-memory login throttle. //! -//! Login failures count per username + client IP, so one address cannot lock -//! the owner out from another. A much looser count per username answers -//! guessing spread over many addresses: past it, every address waits a short, -//! fixed time, which an attacker cannot extend for anyone else. Usernames with -//! no account go through the same code, so the schedule reveals nobody. +//! Login failures count per username + address prefix, so one address cannot +//! lock the owner out from another. Each username also has a budget for +//! failures from addresses it has not logged in from: guessing spread over many +//! addresses ends there, before Argon2. Addresses with a recent completed login +//! skip the budget, which is what keeps the owner in during an attack. Usernames +//! with no account go through the same code, so the schedule reveals nobody. use std::collections::{HashMap, VecDeque}; use std::net::{IpAddr, Ipv6Addr}; @@ -19,13 +20,14 @@ const ACCOUNT_FREE_FAILURES: u32 = 5; const ACCOUNT_DELAY_BASE_SECS: u64 = 30; /// One failure is forgotten per this many seconds without another. pub const DECAY_SECS: u64 = 900; -/// Failures on one username, from any address, before every address is delayed. -/// At one forgotten per 900 s, a steady 96 guesses a day never reach it. -pub const ACCOUNT_WIDE_LIMIT: u32 = 100; -/// The count stops here so that an attack ends within about 50 hours of decay. -const ACCOUNT_WIDE_MAX: u32 = 2 * ACCOUNT_WIDE_LIMIT; -/// Past the limit: what a fresh address waits for its first evaluated attempt. -pub const OVER_LIMIT_WAIT_SECS: u64 = 60; +/// Failures from unknown addresses that one username can take in a rolling day. +pub const BUDGET_MAX_FAILURES: u32 = 100; +pub const BUDGET_WINDOW_SECS: u64 = 86_400; +/// One budget failure is forgotten per this many seconds, so the window holds +/// the whole budget. +pub const BUDGET_DECAY_SECS: u64 = BUDGET_WINDOW_SECS / BUDGET_MAX_FAILURES as u64; +/// A budget is written to disk at most this often, bar crossing the cap. +pub const BUDGET_WRITE_SECS: u64 = 60; const IP_TABLE_CAPACITY: usize = 100_000; const PAIR_TABLE_CAPACITY: usize = 100_000; const ACCOUNT_TABLE_CAPACITY: usize = 10_000; @@ -53,20 +55,16 @@ pub(super) fn lock_until(failures: u32, now: u64) -> u64 { /// `(failures, last)` after forgiving one failure per `DECAY_SECS` elapsed. pub(super) fn decayed(failures: u32, last: u64, now: u64) -> (u32, u64) { - let steps = now.saturating_sub(last) / DECAY_SECS; + decayed_by(failures, last, now, DECAY_SECS) +} + +fn decayed_by(failures: u32, last: u64, now: u64, period: u64) -> (u32, u64) { + let steps = now.saturating_sub(last) / period; if steps >= u64::from(failures) { return (0, now); } // `steps` is below `failures`, so it fits in u32. - (failures - steps as u32, last + steps * DECAY_SECS) -} - -/// Delay of an address past the account-wide limit: no free failures. -fn over_limit_delay(failures: u32) -> u64 { - OVER_LIMIT_WAIT_SECS - .checked_shl(failures.saturating_sub(1)) - .filter(|d| failures <= 32 && *d < ACCOUNT_DELAY_CAP_SECS) - .unwrap_or(ACCOUNT_DELAY_CAP_SECS) + (failures - steps as u32, last + steps * period) } fn guard(m: &Mutex) -> MutexGuard<'_, T> { @@ -89,6 +87,19 @@ fn ip_key(ip: IpAddr) -> IpAddr { } } +/// What the login throttle and the budget treat as one address: an IPv4 address, +/// or an IPv6 /48, the size routinely handed to one customer. An IPv4-mapped +/// address is the IPv4 address. +pub fn address_key(ip: IpAddr) -> IpAddr { + match ip_key(ip) { + IpAddr::V6(v6) => { + let s = v6.segments(); + IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0)) + } + v4 => v4, + } +} + /// Sliding window of failures per IP. Kept in memory: a restart clears it. #[derive(Debug)] pub struct IpLimiter { @@ -163,29 +174,47 @@ struct PairEntry { failures: u32, last: u64, locked_until: u64, - /// Already waited out `OVER_LIMIT_WAIT_SECS` during this period over limit. - waited: bool, +} + +/// A budget as the store holds it, for an account the daemon has not met yet. +/// A username with no account starts from the default. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BudgetState { + pub failures: u32, + pub last: u64, + pub audited_at: u64, + pub generation: u64, } #[derive(Debug, Clone, Copy, Default)] -struct AccountEntry { - failures: u32, - last: u64, +struct BudgetEntry { + state: BudgetState, + written_at: u64, + written_failures: u32, +} + +/// What an evaluated failure asks of the caller, outside the throttle's lock. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FailureNote { + /// The state to persist, when a write is due. + pub write: Option, + /// The cap was crossed and this window has no audit event yet. + pub audit: bool, } #[derive(Debug, Default)] struct LoginTables { pairs: HashMap<(String, IpAddr), PairEntry>, - accounts: HashMap, + budgets: HashMap, } /// Failure counts for login attempts, known username or not. In memory and -/// bounded: nothing here reaches the disk, whatever an anonymous caller sends, -/// and a restart clears it. +/// bounded; only budgets of real accounts reach the disk, by way of the caller, +/// and a restart clears the rest. #[derive(Debug)] pub struct LoginThrottle { pair_capacity: usize, - account_capacity: usize, + budget_capacity: usize, tables: Mutex, } @@ -196,21 +225,37 @@ impl Default for LoginThrottle { } impl LoginThrottle { - pub fn with_capacity(pair_capacity: usize, account_capacity: usize) -> Self { + pub fn with_capacity(pair_capacity: usize, budget_capacity: usize) -> Self { Self { pair_capacity, - account_capacity, + budget_capacity, tables: Mutex::new(LoginTables::default()), } } - /// Counts the attempt as failed before Argon2 runs, so parallel guesses - /// cannot all pass. `right_password` undoes it. `Err` carries the seconds - /// to wait; a refused attempt never lengthens any delay. - pub fn acquire(&self, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> { - let pair_key = (account.to_string(), ip_key(ip)); + /// Counts the attempt as failed before Argon2 runs, in one step under one + /// lock, so parallel guesses cannot pass the cap. `right_password` or + /// `abandon` undoes it. `Ok` says whether the budget was charged; `Err` + /// carries the seconds to wait, and a refused attempt changes no count. + pub fn acquire( + &self, + account: &str, + ip: IpAddr, + known: bool, + stored: BudgetState, + now: u64, + ) -> Result { + let pair_key = (account.to_string(), address_key(ip)); let mut guard = guard(&self.tables); let t = &mut *guard; + // A reset, possibly from another process, starts this account over. + if t.budgets + .get(account) + .is_some_and(|e| e.state.generation != stored.generation) + { + t.budgets.remove(account); + t.pairs.retain(|k, _| k.0 != account); + } let known_pair = t.pairs.get(&pair_key).copied(); if let Some(left) = known_pair .map(|e| e.locked_until.saturating_sub(now)) @@ -218,84 +263,139 @@ impl LoginThrottle { { return Err(left); } - let account_entry = t.accounts.get(account).copied().unwrap_or_default(); - let (account_failures, _) = decayed(account_entry.failures, account_entry.last, now); - let over = account_failures >= ACCOUNT_WIDE_LIMIT; + let mut budget = t.budgets.get(account).copied().unwrap_or(BudgetEntry { + state: stored, + written_at: 0, + written_failures: stored.failures, + }); + let (failures, last) = budget_now(&budget.state, now); + if !known && failures >= BUDGET_MAX_FAILURES { + return Err((last + BUDGET_DECAY_SECS).saturating_sub(now).max(1)); + } if known_pair.is_none() && t.pairs.len() >= self.pair_capacity { - evict_pair(&mut t.pairs, now); + evict_pair(&mut t.pairs, self.pair_capacity, now); } let pair = t.pairs.entry(pair_key).or_default(); - if !over { - pair.waited = false; - } else if !pair.waited { - pair.waited = true; - pair.last = now; - pair.locked_until = now.saturating_add(OVER_LIMIT_WAIT_SECS); - return Err(OVER_LIMIT_WAIT_SECS); - } - let (failures, last) = decayed(pair.failures, pair.last, now); - pair.failures = failures.saturating_add(1); - pair.last = if failures == 0 { now } else { last }; - pair.locked_until = if over { - now.saturating_add(over_limit_delay(pair.failures)) - } else { - lock_until(pair.failures, now) - }; + let (pair_failures, pair_last) = decayed(pair.failures, pair.last, now); + pair.failures = pair_failures.saturating_add(1); + pair.last = if pair_failures == 0 { now } else { pair_last }; + pair.locked_until = lock_until(pair.failures, now); - if !t.accounts.contains_key(account) && t.accounts.len() >= self.account_capacity { - evict_account(&mut t.accounts); + // A known address charges nothing, but the entry carries the generation + // that a later reset is noticed by. + if !known { + budget.state.failures = failures.saturating_add(1); + budget.state.last = if failures == 0 { now } else { last }; } - let entry = t.accounts.entry(account.to_string()).or_default(); - let (failures, last) = decayed(entry.failures, entry.last, now); - entry.failures = failures.saturating_add(1).min(ACCOUNT_WIDE_MAX); - entry.last = if failures == 0 { now } else { last }; - Ok(()) + if !t.budgets.contains_key(account) && t.budgets.len() >= self.budget_capacity { + evict_budget(&mut t.budgets, self.budget_capacity, now); + } + t.budgets.insert(account.to_string(), budget); + Ok(!known) + } + + /// An attempt charged to the budget was evaluated and failed. Says what the + /// caller must write and audit, once the throttle's lock is gone. + pub fn failed(&self, account: &str, now: u64) -> FailureNote { + let mut t = guard(&self.tables); + let Some(e) = t.budgets.get_mut(account) else { + return FailureNote::default(); + }; + let (failures, last) = budget_now(&e.state, now); + e.state.failures = failures; + e.state.last = last; + let over = failures >= BUDGET_MAX_FAILURES; + let audit = over + && (e.state.audited_at == 0 + || now.saturating_sub(e.state.audited_at) >= BUDGET_WINDOW_SECS); + if audit { + e.state.audited_at = now; + } + let due = e.written_at == 0 || now.saturating_sub(e.written_at) >= BUDGET_WRITE_SECS; + // Once over the cap nothing is evaluated, so a later write would not come. + let crossing = over && e.written_failures < BUDGET_MAX_FAILURES; + let write = (due || crossing || audit).then(|| { + e.written_at = now; + e.written_failures = failures; + e.state + }); + FailureNote { write, audit } } /// The password was right: this address is clear, and the reserved failure - /// leaves the account-wide count. The rest of that count stays, or each - /// login by the owner would hand a distributed attacker a fresh budget. - pub fn right_password(&self, account: &str, ip: IpAddr) { + /// leaves the budget. The rest of the budget stays spent, or each login by + /// the owner would hand a distributed attacker a fresh one. + pub fn right_password(&self, account: &str, ip: IpAddr, budgeted: bool) { let mut t = guard(&self.tables); - if let Some(pair) = t.pairs.get_mut(&(account.to_string(), ip_key(ip))) { + if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) { pair.failures = 0; pair.locked_until = 0; } - if let Some(entry) = t.accounts.get_mut(account) { - entry.failures = entry.failures.saturating_sub(1); + if budgeted { + refund_budget(&mut t, account); + } + } + + /// The attempt was never evaluated: it gives back what it reserved. + pub fn abandon(&self, account: &str, ip: IpAddr, budgeted: bool) { + let mut t = guard(&self.tables); + if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) { + pair.failures = pair.failures.saturating_sub(1); + if account_delay(pair.failures) == 0 { + pair.locked_until = 0; + } + } + if budgeted { + refund_budget(&mut t, account); } } #[cfg(test)] fn tracked(&self) -> (usize, usize) { let t = guard(&self.tables); - (t.pairs.len(), t.accounts.len()) + (t.pairs.len(), t.budgets.len()) } } -/// Drops what no longer matters, or else the entry idle the longest. -fn evict_pair(pairs: &mut HashMap<(String, IpAddr), PairEntry>, now: u64) { +fn budget_now(state: &BudgetState, now: u64) -> (u32, u64) { + decayed_by(state.failures, state.last, now, BUDGET_DECAY_SECS) +} + +fn refund_budget(t: &mut LoginTables, account: &str) { + if let Some(e) = t.budgets.get_mut(account) { + e.state.failures = e.state.failures.saturating_sub(1); + } +} + +/// Drops what no longer matters; if that frees no room, the entry with the +/// fewest failures. Never the oldest: a flood of new entries must not be able +/// to erase a count someone has run up. +fn evict_pair(pairs: &mut HashMap<(String, IpAddr), PairEntry>, capacity: usize, now: u64) { pairs.retain(|_, e| e.locked_until > now || decayed(e.failures, e.last, now).0 > 0); - if pairs.is_empty() { + if pairs.len() < capacity { return; } - let stalest = pairs + let least = pairs .iter() - .min_by_key(|(_, e)| e.last) + .min_by_key(|(_, e)| (e.failures, e.last)) .map(|(k, _)| k.clone()); - if let Some(k) = stalest { + if let Some(k) = least { pairs.remove(&k); } } -fn evict_account(accounts: &mut HashMap) { - let stalest = accounts +fn evict_budget(budgets: &mut HashMap, capacity: usize, now: u64) { + budgets.retain(|_, e| budget_now(&e.state, now).0 > 0); + if budgets.len() < capacity { + return; + } + let least = budgets .iter() - .min_by_key(|(_, e)| e.last) + .min_by_key(|(_, e)| (budget_now(&e.state, now).0, e.state.last)) .map(|(k, _)| k.clone()); - if let Some(k) = stalest { - accounts.remove(&k); + if let Some(k) = least { + budgets.remove(&k); } } @@ -353,22 +453,27 @@ mod tests { fn addr(n: u8) -> IpAddr { IpAddr::from([198, 51, 100, n]) } + /// An attempt from an address the account does not know. + fn pair(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> { + t.acquire(account, ip, false, BudgetState::default(), now) + .map(|_| ()) + } #[test] fn a_pair_follows_the_schedule_and_other_addresses_stay_free() { let t = LoginThrottle::default(); for _ in 0..5 { - assert!(t.acquire("k", addr(1), 1000).is_ok()); + assert!(pair(&t, "k", addr(1), 1000).is_ok()); } - assert_eq!(t.acquire("k", addr(1), 1000), Err(30)); + assert_eq!(pair(&t, "k", addr(1), 1000), Err(30)); assert_eq!( - t.acquire("k", addr(1), 1010), + pair(&t, "k", addr(1), 1010), Err(20), "refusal adds nothing" ); - assert!(t.acquire("k", addr(2), 1000).is_ok()); - assert!(t.acquire("other", addr(1), 1000).is_ok()); - assert!(t.acquire("k", addr(1), 1030).is_ok()); - assert_eq!(t.acquire("k", addr(1), 1030), Err(60)); + assert!(pair(&t, "k", addr(2), 1000).is_ok()); + assert!(pair(&t, "other", addr(1), 1000).is_ok()); + assert!(pair(&t, "k", addr(1), 1030).is_ok()); + assert_eq!(pair(&t, "k", addr(1), 1030), Err(60)); } #[test] fn counts_decay_with_time() { @@ -378,66 +483,146 @@ mod tests { assert_eq!(decayed(0, 5, u64::MAX), (0, u64::MAX)); let t = LoginThrottle::default(); for _ in 0..5 { - t.acquire("k", addr(1), 1000).unwrap(); + pair(&t, "k", addr(1), 1000).unwrap(); } // Two windows later three failures remain: the next one is the fourth, // which carries no delay. let later = 1000 + 2 * DECAY_SECS; - assert!(t.acquire("k", addr(1), later).is_ok()); - assert!(t.acquire("k", addr(1), later).is_ok(), "fifth is evaluated"); - assert_eq!(t.acquire("k", addr(1), later), Err(30)); + assert!(pair(&t, "k", addr(1), later).is_ok()); + assert!(pair(&t, "k", addr(1), later).is_ok(), "fifth is evaluated"); + assert_eq!(pair(&t, "k", addr(1), later), Err(30)); } - /// Spends the account-wide budget from many addresses. - fn over_limit(t: &LoginThrottle, now: u64) { - for i in 0..ACCOUNT_WIDE_LIMIT { - let ip = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i)); - t.acquire("k", ip, now).unwrap(); + /// Fails `n` times, each from its own address. + fn spend(t: &LoginThrottle, account: &str, n: u32, first: u32, now: u64) -> u32 { + let mut through = 0; + for i in 0..n { + let ip = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + first + i)); + if pair(t, account, ip, now).is_ok() { + through += 1; + t.failed(account, now); + } } + through } #[test] - fn past_the_account_limit_an_address_waits_a_bounded_time() { + fn the_budget_is_a_cap_that_fades_one_per_slot() { let t = LoginThrottle::default(); - over_limit(&t, 1000); - // The fresh address waits once, whatever others do meanwhile. - assert_eq!(t.acquire("k", addr(1), 1000), Err(OVER_LIMIT_WAIT_SECS)); - assert_eq!(t.acquire("k", addr(1), 1059), Err(1)); - for i in 0..50u8 { - let _ = t.acquire("k", addr(100 + i), 1059); - } - assert!(t.acquire("k", addr(1), 1060).is_ok()); - // Having used its turn, it backs off without free failures. - assert_eq!(t.acquire("k", addr(1), 1060), Err(60)); - assert!(t.acquire("k", addr(1), 1120).is_ok()); - assert_eq!(t.acquire("k", addr(1), 1120), Err(120)); - } - #[test] - fn a_right_password_clears_the_address_but_not_the_attack() { - let t = LoginThrottle::default(); - over_limit(&t, 1000); - let _ = t.acquire("k", addr(1), 1000); - t.acquire("k", addr(1), 1060).unwrap(); - t.right_password("k", addr(1)); - assert!(t.acquire("k", addr(1), 1060).is_ok(), "no second wait"); - t.right_password("k", addr(1)); - assert_eq!(t.acquire("k", addr(2), 1060), Err(OVER_LIMIT_WAIT_SECS)); - } - #[test] - fn the_account_count_cannot_grow_without_end() { - let t = LoginThrottle::default(); - for i in 0..1000u32 { - let _ = t.acquire("k", IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i)), 1000); - } - let later = 1000 + DECAY_SECS * u64::from(ACCOUNT_WIDE_MAX); - assert!( - t.acquire("k", addr(1), later).is_ok(), - "the attack has aged out" + assert_eq!(spend(&t, "k", 150, 0, 1000), 100); + assert_eq!( + pair(&t, "k", addr(1), 1000), + Err(BUDGET_DECAY_SECS), + "seconds until the next slot" ); + assert_eq!( + pair(&t, "k", addr(1), 1000 + 800), + Err(BUDGET_DECAY_SECS - 800) + ); + assert_eq!(spend(&t, "k", 5, 200, 1000 + BUDGET_DECAY_SECS), 1); + } + #[test] + fn a_known_address_skips_the_budget_but_not_the_pair() { + let t = LoginThrottle::default(); + spend(&t, "k", 100, 0, 1000); + let known = |now| t.acquire("k", addr(1), true, BudgetState::default(), now); + for _ in 0..5 { + assert_eq!(known(1000), Ok(false)); + } + assert_eq!(known(1000), Err(30)); + } + #[test] + fn a_right_password_refunds_only_its_own_reservation() { + let t = LoginThrottle::default(); + spend(&t, "k", 100, 0, 1000); + assert!(pair(&t, "k", addr(1), 1000).is_err()); + t.right_password("k", addr(2), false); + assert!(pair(&t, "k", addr(1), 1000).is_err()); + t.right_password("k", addr(2), true); + assert!(pair(&t, "k", addr(1), 1000).is_ok()); + } + #[test] + fn a_new_generation_starts_the_account_over() { + let t = LoginThrottle::default(); + spend(&t, "k", 100, 0, 1000); + for _ in 0..5 { + let _ = t.acquire("k", addr(1), true, BudgetState::default(), 1000); + } + let reset = BudgetState { + generation: 1, + ..Default::default() + }; + assert_eq!(t.acquire("k", addr(1), false, reset, 1000), Ok(true)); + // Pairs too, even for an account seen only from a known address. + let t = LoginThrottle::default(); + for _ in 0..5 { + t.acquire("k", addr(1), true, BudgetState::default(), 1000) + .unwrap(); + } + assert_eq!(t.acquire("k", addr(1), true, reset, 1000), Ok(false)); + } + #[test] + fn a_stored_budget_is_where_an_unmet_account_starts() { + let t = LoginThrottle::default(); + let stored = BudgetState { + failures: 100, + last: 1000, + ..Default::default() + }; + assert!(t.acquire("k", addr(1), false, stored, 1000).is_err()); + assert_eq!(t.tracked().1, 0, "a refusal keeps nothing"); + } + #[test] + fn eviction_takes_the_faded_then_the_least_counted() { + let t = LoginThrottle::with_capacity(1000, 3); + spend(&t, "faded", 1, 0, 1000); + spend(&t, "busy", 50, 10, 1000 + BUDGET_DECAY_SECS); + spend(&t, "small", 2, 100, 1000 + BUDGET_DECAY_SECS); + // Newer than all of them, and each new name pushes out the last. + let now = 1001 + BUDGET_DECAY_SECS; + for i in 0..50 { + spend(&t, &format!("junk{i}"), 1, 200 + i, now); + } + assert_eq!(spend(&t, "busy", 60, 300, now), 50); + } + #[test] + fn a_flood_does_not_free_a_locked_pair() { + let t = LoginThrottle::with_capacity(4, 1000); + for _ in 0..5 { + pair(&t, "k", addr(1), 1000).unwrap(); + } + for i in 0..50u8 { + let _ = pair(&t, &format!("j{i}"), addr(100 + i), 1001); + } + assert!(pair(&t, "k", addr(1), 1001).is_err()); + } + #[test] + fn a_failure_asks_for_a_write_per_minute_and_at_the_crossing() { + let t = LoginThrottle::default(); + let note = |now| { + pair(&t, "k", addr(9), now).ok(); + t.failed("k", now) + }; + assert!(note(1000).write.is_some()); + assert!(note(1000).write.is_none()); + assert!(note(1000 + BUDGET_WRITE_SECS).write.is_some()); + spend(&t, "x", 99, 0, 1000); + pair(&t, "x", addr(8), 1000).unwrap(); + let crossing = t.failed("x", 1000); + assert_eq!(crossing.write.map(|s| s.failures), Some(100)); + assert!(crossing.audit); + } + #[test] + fn a_48_is_one_address_and_a_mapped_v4_is_the_v4() { + let key = |s: &str| address_key(s.parse().unwrap()); + assert_eq!(key("2001:db8:1:2::1"), key("2001:db8:1:ffff:1::9")); + assert_ne!(key("2001:db8:1::1"), key("2001:db8:2::1")); + assert_eq!(key("::ffff:203.0.113.9"), key("203.0.113.9")); + assert_ne!(key("203.0.113.9"), key("203.0.113.8")); } #[test] fn tables_stay_bounded() { let t = LoginThrottle::with_capacity(3, 3); for i in 0..20u8 { - let _ = t.acquire(&format!("k{i}"), addr(i), u64::from(i)); + let _ = pair(&t, &format!("k{i}"), addr(i), u64::from(i)); } let (pairs, accounts) = t.tracked(); assert!(pairs <= 3 && accounts <= 3);