fix(auth): close unauthenticated lockout and tighten the daemon's edges

Key login failures by username and client address with decay, plus a loose
per-username limit that delays every address by a bounded time. Refused
attempts write nothing. Unknown usernames share the code path. MFA and session
password checks keep a persistent user-bound count that needs a password or a
session to reach.

Also: local mode refuses a non-loopback bind outside a container; security
headers on every response; the Argon2 permit lives as long as the blocking
task; a required password change rechecks role, MFA and epoch; auth reset
works for any user; mfa_enabled in /api/auth/state; disabling MFA that is off
is refused with no side effects; StateCorrupt keeps only line and column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 21:03:27 -03:00
1 parent 3e4c4201e5
commit 348e61ca95
10 files changed
+725 -199

No files matched your search

+89 -77
View File
@@ -11,7 +11,7 @@ use super::credentials::{
totp_uri_and_qr, validate_password, verify_password, verify_totp,
};
use super::store::{AuthState, AuthStore, Bootstrap, Role, Scope, Session, User};
use super::throttle::{lock_until, IpLimiter, UnknownAccounts};
use super::throttle::{decayed, lock_until, IpLimiter, LoginThrottle};
use super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets};
use crate::error::{AcauaError, AuthFailure, Result};
use serde::{Deserialize, Serialize};
@@ -111,7 +111,7 @@ pub struct AuthService {
pub(super) secrets: Secrets,
pub(super) audit: AuditLog,
pub(super) ips: IpLimiter,
unknown: UnknownAccounts,
logins: LoginThrottle,
#[cfg_attr(not(test), allow(dead_code))]
pub(super) auth_dir: PathBuf,
}
@@ -173,8 +173,13 @@ pub(super) fn user_or_missing<'a>(st: &'a mut AuthState, id: &str) -> Result<&'a
user_mut(st, id).ok_or_else(|| AuthFailure::UserNotFound.into())
}
/// Counts against the user-bound throttle: MFA codes and the password checks
/// of a live session. Only someone past the password or inside a session can
/// reach it, so a stranger cannot use it against the owner.
pub(super) fn count_failure(u: &mut User, now: u64) {
u.failed_attempts = u.failed_attempts.saturating_add(1);
let (failures, last) = decayed(u.failed_attempts, u.failed_at, now);
u.failed_attempts = failures.saturating_add(1);
u.failed_at = if failures == 0 { now } else { last };
u.locked_until = lock_until(u.failed_attempts, now);
}
@@ -246,6 +251,25 @@ fn complete_login(st: &mut AuthState, user_id: &str, now: u64) -> Result<NewSess
Ok(issue_session(st, user_id, now))
}
/// Last step of a required password change. `change_password` moved the epoch
/// by exactly one; anything else means the account changed in between. An
/// administrator never gets a session without MFA, even if promoted meanwhile.
fn finish_required_change(
st: &mut AuthState,
user_id: &str,
ticket_epoch: u64,
now: u64,
) -> Result<NewSession> {
let u = user_mut(st, user_id).ok_or_else(invalid)?;
if u.must_change_password
|| u.auth_epoch != ticket_epoch.wrapping_add(1)
|| (u.role == Role::Admin && u.totp_sealed.is_none())
{
return Err(invalid());
}
complete_login(st, user_id, now)
}
fn bootstrap_valid(st: &AuthState, code_hash: &str, now: u64) -> bool {
!has_admin(st)
&& st.bootstrap.as_ref().is_some_and(|b| {
@@ -273,7 +297,7 @@ impl AuthService {
secrets,
audit: AuditLog::open(&auth_dir),
ips: IpLimiter::default(),
unknown: UnknownAccounts::default(),
logins: LoginThrottle::default(),
auth_dir,
})
}
@@ -414,61 +438,44 @@ impl AuthService {
}
/// First factor. Unknown user and wrong password are indistinguishable:
/// same error, same Argon2 cost, same store write, same throttle schedule.
/// same error, same Argon2 cost, same throttle schedule, and no store write
/// for either. A refused attempt writes nothing at all.
pub fn login(&self, username: &str, password: &str, ip: IpAddr, now: u64) -> Result<LoginStep> {
enum Gate {
NoAdmin,
Unknown,
Locked(u64),
Known {
id: String,
name: String,
hash: String,
},
struct Known {
id: String,
name: String,
hash: String,
}
self.ips.acquire(ip, now).map_err(throttled)?;
let key = username_key(username);
let gate = self.store.update(|st| {
if !has_admin(st) {
return Ok(Gate::NoAdmin);
}
let Some(u) = st
.users
.iter_mut()
.find(|u| username_key(&u.username) == key)
else {
return Ok(Gate::Unknown);
};
Ok(match reserve_attempt(u, now) {
Err(left) => Gate::Locked(left),
Ok(()) => Gate::Known {
id: u.id.clone(),
name: u.username.clone(),
hash: u.password_hash.clone(),
},
let found = self.store.read(|st| {
has_admin(st).then(|| {
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(),
})
})
})?;
let (id, name, hash) = match gate {
Gate::NoAdmin => {
self.ips.release(ip);
return Err(AuthFailure::SetupRequired.into());
}
Gate::Locked(left) => {
self.ips.release(ip);
return Err(throttled(left));
}
Gate::Unknown => {
if let Err(left) = self.unknown.acquire(&hash_token(&key), now) {
self.ips.release(ip);
return Err(throttled(left));
}
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());
}
Gate::Known { id, name, hash } => (id, name, hash),
let Some(found) = found else {
self.ips.release(ip);
return Err(AuthFailure::SetupRequired.into());
};
// 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());
};
if !verify_password(Some(&hash), password) {
self.log(
@@ -485,7 +492,6 @@ impl AuthService {
let Some(u) = user_mut(st, &id).filter(|u| u.password_hash == hash) else {
return Ok(None);
};
refund_attempt(u);
let epoch = u.auth_epoch;
let step = if u.totp_sealed.is_some() {
LoginStep::MfaRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?)
@@ -514,6 +520,7 @@ impl AuthService {
return Err(invalid());
};
self.ips.release(ip);
self.logins.right_password(&throttle_key, ip);
let detail = match step {
LoginStep::Session(_) => "session",
LoginStep::MfaRequired(_) => "mfa required",
@@ -714,6 +721,15 @@ impl AuthService {
Ok(texts)
}
/// Whether the account has an active second factor.
pub fn mfa_enabled(&self, user_id: &str) -> Result<bool> {
self.store.read(|st| {
st.users
.iter()
.any(|u| u.id == user_id && u.totp_sealed.is_some())
})
}
/// Every account, without credentials. Authorization is the caller's.
pub fn list_users(&self) -> Result<Vec<UserView>> {
self.store.read(|st| {
@@ -891,16 +907,12 @@ impl AuthService {
return Err(invalid());
}
self.change_password(&claims.user_id, current, new, None, now)?;
self.store.update(|st| {
let u = user_mut(st, &claims.user_id).ok_or_else(invalid)?;
if u.must_change_password {
return Err(invalid());
}
complete_login(st, &claims.user_id, now)
})
self.store
.update(|st| finish_required_change(st, &claims.user_id, claims.epoch, now))
}
/// Refused for administrators. Ends the other sessions.
/// Refused for administrators, and when MFA is already off, which changes
/// nothing and writes no audit line. Ends the other sessions.
pub fn disable_mfa(
&self,
actor: &str,
@@ -913,6 +925,9 @@ impl AuthService {
if u.role == Role::Admin {
return Err(AuthFailure::MfaMandatory.into());
}
if u.totp_sealed.is_none() {
return Err(AuthFailure::MfaNotEnabled.into());
}
let name = u.username.clone();
u.totp_sealed = None;
u.totp_pending_sealed = None;
@@ -922,15 +937,18 @@ impl AuthService {
drop_admin_tokens(st, user_id);
Ok(name)
});
self.log_admin_result("mfa.disable", actor, &result)?;
if !matches!(result, Err(AcauaError::Auth(AuthFailure::MfaNotEnabled))) {
self.log_admin_result("mfa.disable", actor, &result)?;
}
result.map(|_| ())
}
/// Local recovery for an administrator who lost access: removes MFA and
/// sessions, clears the throttle, and returns a temporary password that
/// is shown once. The next login must enroll again and change the password
/// before any ordinary session.
pub fn reset_admin(&self, username: &str, _now: u64) -> Result<String> {
/// 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.
pub fn reset_account(&self, username: &str, _now: u64) -> Result<String> {
let key = username_key(username);
let temp = random_token(TEMP_PASSWORD_BYTES);
let password_hash = hash_password(&temp)?;
@@ -938,7 +956,7 @@ impl AuthService {
let Some(u) = st
.users
.iter_mut()
.find(|u| u.role == Role::Admin && username_key(&u.username) == key)
.find(|u| username_key(&u.username) == key)
else {
return Ok(None);
};
@@ -957,16 +975,10 @@ impl AuthService {
Ok(Some(name))
})?;
let Some(name) = target else {
self.log("admin.reset", None, None, false, Some("no such admin"))?;
self.log("auth.reset", None, None, false, Some("no such user"))?;
return Err(AuthFailure::UserNotFound.into());
};
self.log(
"admin.reset",
Some(&name),
None,
true,
Some("local command"),
)?;
self.log("auth.reset", Some(&name), None, true, Some("local command"))?;
Ok(temp)
}
}
+227 -51
View File
@@ -379,13 +379,15 @@ fn same_error_for_unknown_user_and_bad_password() {
assert_eq!(unknown, AuthFailure::InvalidCredentials);
assert_eq!(unknown, bad);
assert_eq!(unknown.to_string(), bad.to_string());
// The throttle must not tell them apart either.
for _ in 0..4 {
let _ = s.login("ghost", PW, "192.0.2.2".parse().unwrap(), T0);
let _ = s.login("ana", WRONG, "192.0.2.2".parse().unwrap(), T0);
// The throttle must not tell them apart either, per address or past the
// account-wide limit.
let spent: IpAddr = "192.0.2.2".parse().unwrap();
for _ in 0..5 {
let _ = s.login("ghost", PW, spent, T0);
let _ = s.login("ana", WRONG, spent, T0);
}
let unknown = failure(s.login("ghost", PW, "192.0.2.3".parse().unwrap(), T0));
let bad = failure(s.login("ana", WRONG, "192.0.2.3".parse().unwrap(), T0));
let unknown = failure(s.login("ghost", PW, spent, T0));
let bad = failure(s.login("ana", WRONG, spent, T0));
assert_eq!(
unknown,
AuthFailure::Throttled {
@@ -393,25 +395,37 @@ fn same_error_for_unknown_user_and_bad_password() {
}
);
assert_eq!(unknown, bad);
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 fresh: IpAddr = "192.0.2.3".parse().unwrap();
let unknown = failure(s.login("ghost", PW, fresh, T0));
let bad = failure(s.login("ana", WRONG, fresh, T0));
assert_eq!(
unknown,
AuthFailure::Throttled {
retry_after_secs: 60
}
);
assert_eq!(unknown, bad);
}
#[test]
fn account_throttle_delay_grows_capped() {
fn login_delay_grows_per_address() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let mut now = T0;
for _ in 0..4 {
for _ in 0..5 {
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
}
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
// Locked: even the right password is not evaluated.
// Locked: even the right password is not evaluated from this address.
assert_eq!(
failure(s.login("ana", PW, ip(), now)),
AuthFailure::Throttled {
@@ -429,40 +443,204 @@ fn account_throttle_delay_grows_capped() {
retry_after_secs: 60
}
);
// Survives a restart and is capped.
s.store
.update(|st| {
st.users
.iter_mut()
.find(|u| u.id == id)
.unwrap()
.failed_attempts = 50;
Ok(())
})
.unwrap();
let dir = s.auth_dir.parent().unwrap().to_path_buf();
let s2 = AuthService::open(&dir, None).unwrap();
now += 61;
assert_eq!(
failure(s2.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s2.login("ana", PW, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 900
}
);
now += 901;
session_of(s2.login("ana", PW, ip(), now).unwrap());
let (f, l) = s2
session_of(s.login("ana", PW, ip(), now).unwrap());
// None of it touched the user-bound counter.
let (f, l) = s
.store
.read(|st| {
let u = st.users.iter().find(|u| u.id == id).unwrap();
(u.failed_attempts, u.locked_until)
})
.unwrap();
assert_eq!((f, l), (0, 0), "success clears the counter");
assert_eq!((f, l), (0, 0));
// A right password clears the address.
for _ in 0..4 {
let _ = s.login("ana", WRONG, ip(), now);
}
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn right_password_from_another_ip_still_gets_in_while_an_attacker_keeps_failing() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let attacker: IpAddr = "203.0.113.9".parse().unwrap();
let owner: IpAddr = "198.51.100.1".parse().unwrap();
let mut now = T0;
for _ in 0..6 {
let _ = s.login("ana", WRONG, attacker, now);
}
// The cadence of the proof of concept: a failure each time the lock lapses,
// for a day, with the owner trying a second later.
for _ in 0..96 {
now += 901;
assert_eq!(
failure(s.login("ana", WRONG, attacker, now)),
AuthFailure::InvalidCredentials
);
session_of(s.login("ana", PW, owner, now + 1).unwrap());
}
assert!(matches!(
failure(s.login("ana", PW, attacker, now + 1)),
AuthFailure::Throttled { .. }
));
}
#[test]
fn login_counts_decay_over_time() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
for _ in 0..5 {
let _ = s.login("ana", WRONG, ip(), T0);
}
// Long after, four failures are free again: the count was forgotten.
let later = T0 + 5 * 900;
for _ in 0..4 {
assert_eq!(
failure(s.login("ana", WRONG, ip(), later)),
AuthFailure::InvalidCredentials
);
}
session_of(s.login("ana", PW, ip(), later).unwrap());
}
#[test]
fn user_bound_failures_decay_over_time() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
for _ in 0..4 {
let _ = s.confirm_mfa(&p.token, "000000", T0 + 60);
}
let p = pending_of(s.login("ana", PW, ip(), T0 + 1920).unwrap());
let _ = s.confirm_mfa(&p.token, "000000", T0 + 1920);
let failures = s
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.failed_attempts
})
.unwrap();
assert_eq!(failures, 3, "two windows forgot two of four, then one more");
}
#[test]
fn wrong_passwords_and_refusals_write_no_state() {
let (_d, s) = svc();
admin(&s);
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();
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);
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]
fn a_stranger_cannot_trigger_the_user_bound_throttle() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let attacker: IpAddr = "203.0.113.9".parse().unwrap();
for _ in 0..8 {
let _ = s.login("ana", WRONG, attacker, T0 + 60);
}
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
let good = code_at_active(&s, &id, T0 + 60);
session_of(s.confirm_mfa(&p.token, &good, T0 + 60).unwrap());
}
#[test]
fn required_change_final_step_refuses_a_changed_account() {
let (_d, s) = svc();
let root = admin(&s);
let ana = analyst(&s, "ana");
let finish = |id: &str, epoch: u64| {
s.store
.update(|st| finish_required_change(st, id, epoch, T0))
};
// An administrator without MFA, as after a promotion in between.
let epoch = s
.store
.update(|st| {
let u = user_mut(st, &root).unwrap();
u.totp_sealed = None;
Ok(u.auth_epoch)
})
.unwrap();
assert_eq!(
failure(finish(&root, epoch.wrapping_sub(1))),
AuthFailure::InvalidCredentials
);
// The wrong epoch.
let epoch = s
.store
.read(|st| st.users.iter().find(|u| u.id == ana).unwrap().auth_epoch)
.unwrap();
assert_eq!(
failure(finish(&ana, epoch)),
AuthFailure::InvalidCredentials
);
// The expected epoch opens the session.
finish(&ana, epoch.wrapping_sub(1)).unwrap();
}
#[test]
fn an_analyst_who_lost_mfa_can_be_reset() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let temp = s.reset_account("ana", T0 + 100).unwrap();
assert!(!s.mfa_enabled(&id).unwrap());
let LoginStep::PasswordChangeRequired(ticket) = s.login("ana", &temp, ip(), T0 + 200).unwrap()
else {
panic!("expected the password step");
};
s.change_required_password(&ticket.token, &temp, PW2, T0 + 200)
.unwrap();
session_of(s.login("ana", PW2, ip(), T0 + 300).unwrap());
}
#[test]
fn disabling_mfa_that_is_off_changes_nothing() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let session = session_of(s.login("ana", PW, ip(), T0).unwrap());
let state = s.auth_dir.join(crate::auth::STATE_FILE);
let before = std::fs::read(&state).unwrap();
let lines = s.audit_tail(1000).unwrap().len();
assert_eq!(
failure(s.disable_mfa("ana", &id, Some(&session.token), T0)),
AuthFailure::MfaNotEnabled
);
assert_eq!(std::fs::read(&state).unwrap(), before);
assert_eq!(s.audit_tail(1000).unwrap().len(), lines);
assert_eq!(sessions(&s, &id), 1);
}
#[test]
@@ -505,7 +683,7 @@ fn bad_codes_count_towards_the_account_throttle() {
}
#[test]
fn concurrent_guesses_cannot_outrun_the_account_throttle() {
fn concurrent_guesses_cannot_outrun_the_address_throttle() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
@@ -514,8 +692,8 @@ fn concurrent_guesses_cannot_outrun_the_account_throttle() {
.map(|i| {
let s = &s;
sc.spawn(move || {
let addr = IpAddr::from([192, 0, 2, 100 + i]);
s.login("ana", WRONG, addr, T0)
let _ = i;
s.login("ana", WRONG, ip(), T0)
})
})
.collect();
@@ -677,7 +855,7 @@ fn reset_admin_is_audited_and_forces_enrollment() {
let (_d, s) = svc();
let root = admin(&s);
session_of_any(&s, &root);
let temp = s.reset_admin("root", T0 + 200).unwrap();
let temp = s.reset_account("root", T0 + 200).unwrap();
assert_eq!(sessions(&s, &root), 0);
assert!(temp.len() >= 24);
assert_eq!(
@@ -689,15 +867,13 @@ fn reset_admin_is_audited_and_forces_enrollment() {
LoginStep::MfaEnrollRequired(_)
));
assert_eq!(
failure(s.reset_admin("ghost", T0)),
failure(s.reset_account("ghost", T0)),
AuthFailure::UserNotFound
);
analyst(&s, "ana");
assert_eq!(failure(s.reset_admin("ana", T0)), AuthFailure::UserNotFound);
let log = s.audit_tail(100).unwrap();
assert!(log
.iter()
.any(|e| e.event.action == "admin.reset" && e.event.ok));
.any(|e| e.event.action == "auth.reset" && e.event.ok));
let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap();
assert!(!raw.contains(&temp));
}
@@ -795,10 +971,10 @@ fn open_fails_on_missing_key_without_touching_state() {
assert_eq!(std::fs::read(auth.join("state.json")).unwrap(), before);
}
/// Admin after `reset_admin`, enrolled again. Returns (id, temp password).
/// Admin after `reset_account`, enrolled again. Returns (id, temp password).
fn reset_and_enroll(s: &AuthService) -> (String, String) {
let id = admin(s);
let temp = s.reset_admin("root", T0 + 200).unwrap();
let temp = s.reset_account("root", T0 + 200).unwrap();
enroll(s, &id, T0 + 200);
(id, temp)
}
@@ -890,7 +1066,7 @@ fn flag_also_blocks_password_only_login() {
s.create_user("root", "second", PW, Role::Admin, T0)
.unwrap();
let second = uid(&s, "second");
let temp = s.reset_admin("second", T0).unwrap();
let temp = s.reset_account("second", T0).unwrap();
s.set_role("root", &second, Role::Analyst, T0).unwrap();
let t = change_ticket(s.login("second", &temp, ip(), T0).unwrap());
assert_eq!(sessions(&s, &second), 0);
+16 -5
View File
@@ -37,14 +37,18 @@ pub struct User {
pub totp_last_step: Option<u64>,
/// SHA-256 hex of each unused recovery code.
pub recovery_hashes: Vec<String>,
/// Failures since the last completed login; survives restarts.
/// MFA and session-password failures since the last completed login; one
/// is forgotten per 900 s. Wrong login passwords are not counted here: see
/// `throttle::LoginThrottle`.
pub failed_attempts: u32,
/// No attempt is evaluated before this instant.
/// Start of the current decay period of `failed_attempts`.
pub failed_at: u64,
/// No MFA code or session password is evaluated before this instant.
pub locked_until: u64,
/// Changes when the password changes and at each completed login, which
/// voids the pending MFA tokens issued before it.
pub auth_epoch: u64,
/// Set by `reset_admin`: no ordinary session until the password changes.
/// Set by `reset_account`: no ordinary session until the password changes.
pub must_change_password: bool,
}
@@ -201,8 +205,15 @@ impl AuthStore {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(AuthState::default()),
Err(e) => return Err(e.into()),
};
let state: AuthState = serde_json::from_slice(&raw)
.map_err(|e| AcauaError::Auth(AuthFailure::StateCorrupt(e.to_string())))?;
let state: AuthState = serde_json::from_slice(&raw).map_err(|e| {
// Serde's message can quote the file, which holds hashes and
// sealed secrets: the position is enough to find the damage.
AcauaError::Auth(AuthFailure::StateCorrupt(format!(
"invalid JSON at line {}, column {}",
e.line(),
e.column()
)))
})?;
if state.version == 0 || state.version > STATE_VERSION {
return Err(AuthFailure::StateVersionUnsupported(state.version).into());
}
+242 -57
View File
@@ -1,6 +1,11 @@
//! Attempt limits: the per-account delay schedule, the in-memory IP limiter
//! and the in-memory stand-in that makes unknown usernames throttle exactly
//! like real accounts.
//! 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.
use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv6Addr};
@@ -12,8 +17,18 @@ pub const ACCOUNT_DELAY_CAP_SECS: u64 = 900;
/// The failure count at which the delay starts.
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;
const IP_TABLE_CAPACITY: usize = 100_000;
const UNKNOWN_TABLE_CAPACITY: usize = 10_000;
const PAIR_TABLE_CAPACITY: usize = 100_000;
const ACCOUNT_TABLE_CAPACITY: usize = 10_000;
/// Delay after `failures` failures: none before the 5th, then 30 s doubling
/// up to 900 s.
@@ -36,6 +51,24 @@ 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;
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)
}
fn guard<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
// The tables stay valid whatever a panicking holder did.
m.lock().unwrap_or_else(|e| e.into_inner())
@@ -125,72 +158,151 @@ impl IpLimiter {
}
}
#[derive(Debug, Clone, Copy)]
struct UnknownEntry {
#[derive(Debug, Clone, Copy, Default)]
struct PairEntry {
failures: u32,
last: u64,
locked_until: u64,
/// Already waited out `OVER_LIMIT_WAIT_SECS` during this period over limit.
waited: bool,
}
#[derive(Debug, Clone, Copy, Default)]
struct AccountEntry {
failures: u32,
last: u64,
}
/// Failure schedule for usernames with no account. Without it, only real
/// accounts would ever answer "throttled", which reveals who exists. Bounded
/// and in memory: an attacker must not be able to grow state on disk.
#[derive(Debug, Default)]
struct LoginTables {
pairs: HashMap<(String, IpAddr), PairEntry>,
accounts: HashMap<String, AccountEntry>,
}
/// 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.
#[derive(Debug)]
pub struct UnknownAccounts {
capacity: usize,
table: Mutex<HashMap<String, UnknownEntry>>,
pub struct LoginThrottle {
pair_capacity: usize,
account_capacity: usize,
tables: Mutex<LoginTables>,
}
impl Default for UnknownAccounts {
impl Default for LoginThrottle {
fn default() -> Self {
Self::with_capacity(UNKNOWN_TABLE_CAPACITY)
Self::with_capacity(PAIR_TABLE_CAPACITY, ACCOUNT_TABLE_CAPACITY)
}
}
impl UnknownAccounts {
pub fn with_capacity(capacity: usize) -> Self {
impl LoginThrottle {
pub fn with_capacity(pair_capacity: usize, account_capacity: usize) -> Self {
Self {
capacity,
table: Mutex::new(HashMap::new()),
pair_capacity,
account_capacity,
tables: Mutex::new(LoginTables::default()),
}
}
/// Same contract as a real account: `Err` with the remaining delay, or
/// the attempt is counted as a failure.
pub fn acquire(&self, key: &str, now: u64) -> Result<(), u64> {
let mut table = guard(&self.table);
if !table.contains_key(key) && table.len() >= self.capacity {
let stalest = table
.iter()
.min_by_key(|(_, e)| e.last)
.map(|(k, _)| k.clone());
if let Some(k) = stalest {
table.remove(&k);
}
/// 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));
let mut guard = guard(&self.tables);
let t = &mut *guard;
let known_pair = t.pairs.get(&pair_key).copied();
if let Some(left) = known_pair
.map(|e| e.locked_until.saturating_sub(now))
.filter(|left| *left > 0)
{
return Err(left);
}
let entry = table.entry(key.to_string()).or_insert(UnknownEntry {
failures: 0,
locked_until: 0,
last: now,
});
entry.last = now;
if entry.locked_until > now {
return Err(entry.locked_until - now);
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;
if known_pair.is_none() && t.pairs.len() >= self.pair_capacity {
evict_pair(&mut t.pairs, now);
}
entry.failures = entry.failures.saturating_add(1);
entry.locked_until = lock_until(entry.failures, 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)
};
if !t.accounts.contains_key(account) && t.accounts.len() >= self.account_capacity {
evict_account(&mut t.accounts);
}
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(())
}
/// 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) {
let mut t = guard(&self.tables);
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), ip_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);
}
}
#[cfg(test)]
fn tracked(&self) -> usize {
guard(&self.table).len()
fn tracked(&self) -> (usize, usize) {
let t = guard(&self.tables);
(t.pairs.len(), t.accounts.len())
}
}
/// Drops what no longer matters, or else the entry idle the longest.
fn evict_pair(pairs: &mut HashMap<(String, IpAddr), PairEntry>, now: u64) {
pairs.retain(|_, e| e.locked_until > now || decayed(e.failures, e.last, now).0 > 0);
if pairs.is_empty() {
return;
}
let stalest = pairs
.iter()
.min_by_key(|(_, e)| e.last)
.map(|(k, _)| k.clone());
if let Some(k) = stalest {
pairs.remove(&k);
}
}
fn evict_account(accounts: &mut HashMap<String, AccountEntry>) {
let stalest = accounts
.iter()
.min_by_key(|(_, e)| e.last)
.map(|(k, _)| k.clone());
if let Some(k) = stalest {
accounts.remove(&k);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
#[test]
fn delay_starts_at_fifth_failure_grows_and_caps() {
let seq: Vec<u64> = (0..=12).map(account_delay).collect();
@@ -238,23 +350,96 @@ mod tests {
}
assert!(l.tracked() <= 4);
}
#[test]
fn unknown_accounts_follow_the_account_schedule() {
let u = UnknownAccounts::default();
for _ in 0..4 {
assert!(u.acquire("k", 1000).is_ok());
}
assert!(u.acquire("k", 1000).is_ok(), "fifth attempt is evaluated");
assert_eq!(u.acquire("k", 1000), Err(30));
assert!(u.acquire("k", 1030).is_ok());
assert_eq!(u.acquire("k", 1030), Err(60));
fn addr(n: u8) -> IpAddr {
IpAddr::from([198, 51, 100, n])
}
#[test]
fn unknown_table_stays_bounded() {
let u = UnknownAccounts::with_capacity(3);
for i in 0..20u64 {
u.acquire(&format!("k{i}"), i).unwrap();
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!(u.tracked() <= 3);
assert_eq!(t.acquire("k", addr(1), 1000), Err(30));
assert_eq!(
t.acquire("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));
}
#[test]
fn counts_decay_with_time() {
assert_eq!(decayed(3, 1000, 1000 + DECAY_SECS - 1), (3, 1000));
assert_eq!(decayed(3, 1000, 1000 + DECAY_SECS), (2, 1000 + DECAY_SECS));
assert_eq!(decayed(3, 1000, 1000 + 3 * DECAY_SECS).0, 0);
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();
}
// 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));
}
/// 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();
}
}
#[test]
fn past_the_account_limit_an_address_waits_a_bounded_time() {
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"
);
}
#[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 (pairs, accounts) = t.tracked();
assert!(pairs <= 3 && accounts <= 3);
}
}
+2
View File
@@ -34,6 +34,8 @@ pub enum AuthFailure {
KeyInvalid(&'static str),
#[error("sealed value is malformed or failed authentication")]
SealInvalid,
#[error("MFA is not enabled for this account")]
MfaNotEnabled,
#[error("auth state is corrupted: {0}")]
StateCorrupt(String),
#[error("auth state version {0} is not supported")]