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 <noreply@anthropic.com>
This commit is contained in:
1 parent
d48cf9d3f0
commit
b9137e0948
7 files changed
+1128
-206
No files matched your search
@@ -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<Known>,
|
||||
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(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
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<NewSession> {
|
||||
/// `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<NewSession> {
|
||||
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<NewSession> {
|
||||
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<PendingMfa> {
|
||||
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<LoginStep> {
|
||||
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<LoginAttempt> {
|
||||
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<LoginStep> {
|
||||
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<LoginStep> {
|
||||
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<String> {
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user