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
+706 -180

No files matched your search

+18 -2
View File
@@ -80,6 +80,7 @@ fn failure_response(f: &AuthFailure) -> Response {
F::BootstrapInvalid => (StatusCode::UNAUTHORIZED, "invalid setup code"), F::BootstrapInvalid => (StatusCode::UNAUTHORIZED, "invalid setup code"),
F::LastAdmin => (StatusCode::CONFLICT, "the last administrator must remain"), F::LastAdmin => (StatusCode::CONFLICT, "the last administrator must remain"),
F::MfaMandatory => (StatusCode::CONFLICT, "MFA is mandatory for administrators"), F::MfaMandatory => (StatusCode::CONFLICT, "MFA is mandatory for administrators"),
F::MfaNotEnabled => (StatusCode::CONFLICT, "MFA is not enabled"),
F::EnrollmentNotStarted => (StatusCode::CONFLICT, "no enrollment in progress"), F::EnrollmentNotStarted => (StatusCode::CONFLICT, "no enrollment in progress"),
F::UsernameTaken => (StatusCode::CONFLICT, "username is already in use"), F::UsernameTaken => (StatusCode::CONFLICT, "username is already in use"),
F::UserNotFound | F::NotFound => (StatusCode::NOT_FOUND, "not found"), F::UserNotFound | F::NotFound => (StatusCode::NOT_FOUND, "not found"),
@@ -153,8 +154,19 @@ where
T: Send + 'static, T: Send + 'static,
F: FnOnce() -> Result<T, AcauaError> + Send + 'static, F: FnOnce() -> Result<T, AcauaError> + Send + 'static,
{ {
let _permit = state.argon2.acquire().await.map_err(|_| internal())?; // The permit moves into the closure: a dropped request cancels this future
blocking(f).await // but not the blocking task, whose Argon2 run must keep its slot to the end.
let permit = state
.argon2
.clone()
.acquire_owned()
.await
.map_err(|_| internal())?;
blocking(move || {
let _permit = permit;
f()
})
.await
} }
// ---- Credentials ---------------------------------------------------------- // ---- Credentials ----------------------------------------------------------
@@ -460,6 +472,8 @@ pub struct StateReply {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
role: Option<Role>, role: Option<Role>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
mfa_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
csrf: Option<String>, csrf: Option<String>,
} }
@@ -480,6 +494,7 @@ pub async fn auth_state(
Some((p, csrf)) => StateReply { Some((p, csrf)) => StateReply {
setup_required, setup_required,
authenticated: true, authenticated: true,
mfa_enabled: Some(auth.mfa_enabled(&p.user_id)?),
username: Some(p.username), username: Some(p.username),
role: Some(p.role), role: Some(p.role),
csrf: Some(csrf), csrf: Some(csrf),
@@ -489,6 +504,7 @@ pub async fn auth_state(
authenticated: false, authenticated: false,
username: None, username: None,
role: None, role: None,
mfa_enabled: None,
csrf: None, csrf: None,
}, },
})) }))
+7 -4
View File
@@ -46,8 +46,9 @@ enum Command {
#[derive(Subcommand)] #[derive(Subcommand)]
enum AuthAction { enum AuthAction {
/// Resets an administrator: removes MFA and sessions, prints a temporary /// Resets an account: removes MFA, sessions and tokens, prints a temporary
/// password once. The next login enrolls MFA again and changes the password. /// password once. The next login changes the password; an administrator
/// also enrolls MFA again.
Reset { Reset {
#[arg(long)] #[arg(long)]
username: String, username: String,
@@ -73,9 +74,11 @@ async fn run(cli: Cli) -> acaua_core::Result<()> {
} => { } => {
let key = web::secret_key_file(&|name| std::env::var(name).ok()); let key = web::secret_key_file(&|name| std::env::var(name).ok());
let auth = acaua_core::auth::AuthService::open(&data_dir, key.as_deref())?; let auth = acaua_core::auth::AuthService::open(&data_dir, key.as_deref())?;
let temp = auth.reset_admin(&username, auth_http::unix_now())?; let temp = auth.reset_account(&username, auth_http::unix_now())?;
println!("Senha temporária (exibida uma única vez): {temp}"); println!("Senha temporária (exibida uma única vez): {temp}");
println!("O próximo login exige novo cadastro de MFA e troca de senha."); println!(
"O próximo login exige troca de senha e, para administradores, novo cadastro de MFA."
);
Ok(()) Ok(())
} }
Command::Analyze { Command::Analyze {
+55
View File
@@ -75,6 +75,30 @@ impl Transport {
} }
} }
/// `local` means plain HTTP for this machine only. In a container the
/// daemon must listen on all interfaces to be published at all, so there
/// `ACAUA_PUBLISHED` decides (see `from_env`); elsewhere the bind does.
pub fn check_bind(&self, bind: &str, env: &impl Fn(&str) -> Option<String>) -> Result<()> {
if !matches!(self, Transport::Local) || env("ACAUA_RUNTIME").as_deref() == Some("container")
{
return Ok(());
}
let loopback = match bind.parse::<SocketAddr>() {
Ok(addr) => addr.ip().to_canonical().is_loopback(),
Err(_) => bind
.rsplit_once(':')
.is_some_and(|(host, _)| host.eq_ignore_ascii_case("localhost")),
};
if loopback {
return Ok(());
}
Err(AcauaError::InvalidInput(format!(
"ACAUA_TRANSPORT=local refuses --bind {bind}: the dashboard would be reachable \
over plain HTTP from the network. Bind to 127.0.0.1 or [::1], or set \
ACAUA_TRANSPORT to tls or proxy"
)))
}
/// Browsers should be pinned to HTTPS only when HTTPS is what they use. /// Browsers should be pinned to HTTPS only when HTTPS is what they use.
pub fn hsts(&self) -> bool { pub fn hsts(&self) -> bool {
!matches!(self, Transport::Local) !matches!(self, Transport::Local)
@@ -136,6 +160,37 @@ mod tests {
s.parse().unwrap() s.parse().unwrap()
} }
#[test]
fn local_mode_refuses_a_network_bind_outside_a_container() {
let bare = |_: &str| None;
let local = Transport::Local;
for ok in [
"127.0.0.1:8787",
"[::1]:8787",
"localhost:8787",
"127.9.9.9:1",
] {
assert!(local.check_bind(ok, &bare).is_ok(), "{ok}");
}
for bad in [
"0.0.0.0:8787",
"[::]:8787",
"192.0.2.1:8787",
"example.org:80",
"nonsense",
] {
let err = local.check_bind(bad, &bare).unwrap_err().to_string();
assert!(err.contains("--bind"), "{err}");
}
// In the image ACAUA_PUBLISHED is the control, not the bind.
let container = |n: &str| (n == "ACAUA_RUNTIME").then(|| "container".to_string());
assert!(local.check_bind("0.0.0.0:8787", &container).is_ok());
let other = |n: &str| (n == "ACAUA_RUNTIME").then(|| "host".to_string());
assert!(local.check_bind("0.0.0.0:8787", &other).is_err());
// Other modes protect the network themselves.
assert!(proxy().check_bind("0.0.0.0:8787", &bare).is_ok());
}
#[test] #[test]
fn forwarded_for_counts_only_from_a_trusted_proxy() { fn forwarded_for_counts_only_from_a_trusted_proxy() {
let forged = xff("203.0.113.9"); let forged = xff("203.0.113.9");
+31 -1
View File
@@ -10,7 +10,7 @@ use axum::body::Body;
use axum::extract::Request; use axum::extract::Request;
use axum::extract::{DefaultBodyLimit, Query, State}; use axum::extract::{DefaultBodyLimit, Query, State};
use axum::http::{header, HeaderValue, Method, StatusCode, Uri}; use axum::http::{header, HeaderValue, Method, StatusCode, Uri};
use axum::middleware::{from_fn_with_state, Next}; use axum::middleware::{from_fn, from_fn_with_state, Next};
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, patch, post, MethodRouter}; use axum::routing::{delete, get, patch, post, MethodRouter};
use axum::{Json, Router}; use axum::{Json, Router};
@@ -238,6 +238,7 @@ pub fn build_app(state: AppState) -> Router {
.layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES)) .layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES))
.layer(from_fn_with_state(state.clone(), require_auth)) .layer(from_fn_with_state(state.clone(), require_auth))
.layer(from_fn_with_state(state.clone(), hsts)) .layer(from_fn_with_state(state.clone(), hsts))
.layer(from_fn(security_headers))
.with_state(state) .with_state(state)
.layer(CompressionLayer::new()) .layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http()) .layer(TraceLayer::new_for_http())
@@ -256,6 +257,34 @@ async fn hsts(State(state): State<AppState>, req: Request, next: Next) -> Respon
response response
} }
/// `style-src 'unsafe-inline'` is the narrowest that works: the report carries
/// its stylesheet inline and Paged.js adds `<style>` elements while it paginates.
/// Scripts stay same-origin only. `data:` images are the report's embedded logo
/// and the MFA QR code.
pub(crate) const CSP: &str = "default-src 'none'; script-src 'self'; \
style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; \
connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";
/// On every response, refusals included.
async fn security_headers(req: Request, next: Next) -> Response {
let mut response = next.run(req).await;
let headers = response.headers_mut();
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(CSP),
);
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
response
}
#[derive(Serialize)] #[derive(Serialize)]
struct Health { struct Health {
status: &'static str, status: &'static str,
@@ -418,6 +447,7 @@ pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
// Decide the exposure before touching the data directory or printing a // Decide the exposure before touching the data directory or printing a
// setup code: a refusal must leave nothing behind. // setup code: a refusal must leave nothing behind.
let transport = Transport::from_env(&|name| std::env::var(name).ok())?; let transport = Transport::from_env(&|name| std::env::var(name).ok())?;
transport.check_bind(bind, &|name| std::env::var(name).ok())?;
let _ = tracing_subscriber::fmt().try_init(); let _ = tracing_subscriber::fmt().try_init();
std::fs::create_dir_all(&data_dir)?; std::fs::create_dir_all(&data_dir)?;
let auth = Arc::new(AuthService::open( let auth = Arc::new(AuthService::open(
+38 -2
View File
@@ -770,11 +770,12 @@ async fn enrolling_or_disabling_from_a_session_needs_recent_reauth() {
.mutate(&cookie, Method::POST, start, nothing.clone()) .mutate(&cookie, Method::POST, start, nothing.clone())
.await; .await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert_eq!(r.status, StatusCode::OK, "{}", r.body);
// Past the reauth check; this analyst never activated MFA.
assert_eq!( assert_eq!(
h.mutate(&cookie, Method::POST, disable, nothing) h.mutate(&cookie, Method::POST, disable, nothing)
.await .await
.status, .status,
StatusCode::OK StatusCode::CONFLICT
); );
} }
@@ -816,7 +817,7 @@ async fn confirm_from_a_session_ends_it_and_clears_the_cookie() {
#[tokio::test] #[tokio::test]
async fn required_password_change_opens_the_session_through_the_public_route() { async fn required_password_change_opens_the_session_through_the_public_route() {
let h = harness(Transport::Local); let h = harness(Transport::Local);
let temp = h.auth.reset_admin("root", now()).unwrap(); let temp = h.auth.reset_account("root", now()).unwrap();
let login = send( let login = send(
&h.app, &h.app,
post_json( post_json(
@@ -1144,3 +1145,38 @@ fn secret_key_file_comes_from_the_environment() {
Some(PathBuf::from("/run/secrets/acaua_key")) Some(PathBuf::from("/run/secrets/acaua_key"))
); );
} }
#[tokio::test]
async fn every_response_carries_the_security_headers() {
let h = harness(Transport::Local);
for path in ["/login.html", "/api/health", "/api/alerts", "/nope"] {
let r = send(&h.app, empty(Method::GET, path)).await;
let get = |name: header::HeaderName| r.headers.get(name).unwrap().to_str().unwrap();
let csp = get(header::CONTENT_SECURITY_POLICY);
assert!(csp.contains("frame-ancestors 'none'"), "{path}");
assert!(csp.contains("script-src 'self'"), "{path}");
assert!(!csp.contains("script-src 'self' 'unsafe"), "{path}");
assert_eq!(get(header::X_FRAME_OPTIONS), "DENY", "{path}");
assert_eq!(get(header::X_CONTENT_TYPE_OPTIONS), "nosniff", "{path}");
assert_eq!(get(header::REFERRER_POLICY), "no-referrer", "{path}");
}
}
#[tokio::test]
async fn auth_state_tells_whether_mfa_is_on() {
let h = harness(Transport::Local);
let anon = send(&h.app, empty(Method::GET, "/api/auth/state")).await;
assert!(anon.json().get("mfa_enabled").is_none());
let state = |c: &str| {
request(Method::GET, "/api/auth/state")
.header(header::COOKIE, c)
.body(Body::empty())
.unwrap()
};
let cookie = h.analyst_cookie().await;
let off = send(&h.app, state(&cookie)).await;
assert_eq!(off.json()["mfa_enabled"], serde_json::json!(false));
let cookie = h.admin_cookie().await;
let on = send(&h.app, state(&cookie)).await;
assert_eq!(on.json()["mfa_enabled"], serde_json::json!(true));
}
+71 -59
View File
@@ -11,7 +11,7 @@ use super::credentials::{
totp_uri_and_qr, validate_password, verify_password, verify_totp, totp_uri_and_qr, validate_password, verify_password, verify_totp,
}; };
use super::store::{AuthState, AuthStore, Bootstrap, Role, Scope, Session, User}; 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 super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets};
use crate::error::{AcauaError, AuthFailure, Result}; use crate::error::{AcauaError, AuthFailure, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -111,7 +111,7 @@ pub struct AuthService {
pub(super) secrets: Secrets, pub(super) secrets: Secrets,
pub(super) audit: AuditLog, pub(super) audit: AuditLog,
pub(super) ips: IpLimiter, pub(super) ips: IpLimiter,
unknown: UnknownAccounts, logins: LoginThrottle,
#[cfg_attr(not(test), allow(dead_code))] #[cfg_attr(not(test), allow(dead_code))]
pub(super) auth_dir: PathBuf, 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()) 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) { 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); 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)) 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 { fn bootstrap_valid(st: &AuthState, code_hash: &str, now: u64) -> bool {
!has_admin(st) !has_admin(st)
&& st.bootstrap.as_ref().is_some_and(|b| { && st.bootstrap.as_ref().is_some_and(|b| {
@@ -273,7 +297,7 @@ impl AuthService {
secrets, secrets,
audit: AuditLog::open(&auth_dir), audit: AuditLog::open(&auth_dir),
ips: IpLimiter::default(), ips: IpLimiter::default(),
unknown: UnknownAccounts::default(), logins: LoginThrottle::default(),
auth_dir, auth_dir,
}) })
} }
@@ -414,61 +438,44 @@ impl AuthService {
} }
/// First factor. Unknown user and wrong password are indistinguishable: /// 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> { pub fn login(&self, username: &str, password: &str, ip: IpAddr, now: u64) -> Result<LoginStep> {
enum Gate { struct Known {
NoAdmin,
Unknown,
Locked(u64),
Known {
id: String, id: String,
name: String, name: String,
hash: String, hash: String,
},
} }
self.ips.acquire(ip, now).map_err(throttled)?; self.ips.acquire(ip, now).map_err(throttled)?;
let key = username_key(username); let key = username_key(username);
let gate = self.store.update(|st| { let found = self.store.read(|st| {
if !has_admin(st) { has_admin(st).then(|| {
return Ok(Gate::NoAdmin); st.users
} .iter()
let Some(u) = st
.users
.iter_mut()
.find(|u| username_key(&u.username) == key) .find(|u| username_key(&u.username) == key)
else { .map(|u| Known {
return Ok(Gate::Unknown);
};
Ok(match reserve_attempt(u, now) {
Err(left) => Gate::Locked(left),
Ok(()) => Gate::Known {
id: u.id.clone(), id: u.id.clone(),
name: u.username.clone(), name: u.username.clone(),
hash: u.password_hash.clone(), hash: u.password_hash.clone(),
}, })
}) })
})?; })?;
let (id, name, hash) = match gate { let Some(found) = found else {
Gate::NoAdmin => {
self.ips.release(ip); self.ips.release(ip);
return Err(AuthFailure::SetupRequired.into()); return Err(AuthFailure::SetupRequired.into());
} };
Gate::Locked(left) => { // The hash keeps a password typed into the wrong field out of memory.
self.ips.release(ip); let throttle_key = hash_token(&key);
return Err(throttled(left)); if let Err(left) = self.logins.acquire(&throttle_key, ip, now) {
}
Gate::Unknown => {
if let Err(left) = self.unknown.acquire(&hash_token(&key), now) {
self.ips.release(ip); self.ips.release(ip);
return Err(throttled(left)); return Err(throttled(left));
} }
let Some(Known { id, name, hash }) = found else {
verify_password(None, password); verify_password(None, password);
// The typed name stays out of the log: it may be a password // The typed name stays out of the log: it may be a password
// entered in the wrong field. // entered in the wrong field.
self.log("login", None, Some(ip), false, Some("invalid credentials"))?; self.log("login", None, Some(ip), false, Some("invalid credentials"))?;
return Err(invalid()); return Err(invalid());
}
Gate::Known { id, name, hash } => (id, name, hash),
}; };
if !verify_password(Some(&hash), password) { if !verify_password(Some(&hash), password) {
self.log( self.log(
@@ -485,7 +492,6 @@ impl AuthService {
let Some(u) = user_mut(st, &id).filter(|u| u.password_hash == hash) else { let Some(u) = user_mut(st, &id).filter(|u| u.password_hash == hash) else {
return Ok(None); return Ok(None);
}; };
refund_attempt(u);
let epoch = u.auth_epoch; let epoch = u.auth_epoch;
let step = if u.totp_sealed.is_some() { 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, now)?)
@@ -514,6 +520,7 @@ impl AuthService {
return Err(invalid()); return Err(invalid());
}; };
self.ips.release(ip); self.ips.release(ip);
self.logins.right_password(&throttle_key, ip);
let detail = match step { let detail = match step {
LoginStep::Session(_) => "session", LoginStep::Session(_) => "session",
LoginStep::MfaRequired(_) => "mfa required", LoginStep::MfaRequired(_) => "mfa required",
@@ -714,6 +721,15 @@ impl AuthService {
Ok(texts) 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. /// Every account, without credentials. Authorization is the caller's.
pub fn list_users(&self) -> Result<Vec<UserView>> { pub fn list_users(&self) -> Result<Vec<UserView>> {
self.store.read(|st| { self.store.read(|st| {
@@ -891,16 +907,12 @@ impl AuthService {
return Err(invalid()); return Err(invalid());
} }
self.change_password(&claims.user_id, current, new, None, now)?; self.change_password(&claims.user_id, current, new, None, now)?;
self.store.update(|st| { self.store
let u = user_mut(st, &claims.user_id).ok_or_else(invalid)?; .update(|st| finish_required_change(st, &claims.user_id, claims.epoch, now))
if u.must_change_password {
return Err(invalid());
}
complete_login(st, &claims.user_id, 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( pub fn disable_mfa(
&self, &self,
actor: &str, actor: &str,
@@ -913,6 +925,9 @@ impl AuthService {
if u.role == Role::Admin { if u.role == Role::Admin {
return Err(AuthFailure::MfaMandatory.into()); return Err(AuthFailure::MfaMandatory.into());
} }
if u.totp_sealed.is_none() {
return Err(AuthFailure::MfaNotEnabled.into());
}
let name = u.username.clone(); let name = u.username.clone();
u.totp_sealed = None; u.totp_sealed = None;
u.totp_pending_sealed = None; u.totp_pending_sealed = None;
@@ -922,15 +937,18 @@ impl AuthService {
drop_admin_tokens(st, user_id); drop_admin_tokens(st, user_id);
Ok(name) Ok(name)
}); });
if !matches!(result, Err(AcauaError::Auth(AuthFailure::MfaNotEnabled))) {
self.log_admin_result("mfa.disable", actor, &result)?; self.log_admin_result("mfa.disable", actor, &result)?;
}
result.map(|_| ()) result.map(|_| ())
} }
/// Local recovery for an administrator who lost access: removes MFA and /// Local recovery for anyone who lost access: removes MFA, sessions and
/// sessions, clears the throttle, and returns a temporary password that /// tokens, clears the user-bound throttle, and returns a temporary password
/// is shown once. The next login must enroll again and change the password /// that is shown once. The next login must change the password before any
/// before any ordinary session. /// ordinary session; an administrator must enroll MFA again first. Login
pub fn reset_admin(&self, username: &str, _now: u64) -> Result<String> { /// 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 key = username_key(username);
let temp = random_token(TEMP_PASSWORD_BYTES); let temp = random_token(TEMP_PASSWORD_BYTES);
let password_hash = hash_password(&temp)?; let password_hash = hash_password(&temp)?;
@@ -938,7 +956,7 @@ impl AuthService {
let Some(u) = st let Some(u) = st
.users .users
.iter_mut() .iter_mut()
.find(|u| u.role == Role::Admin && username_key(&u.username) == key) .find(|u| username_key(&u.username) == key)
else { else {
return Ok(None); return Ok(None);
}; };
@@ -957,16 +975,10 @@ impl AuthService {
Ok(Some(name)) Ok(Some(name))
})?; })?;
let Some(name) = target else { 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()); return Err(AuthFailure::UserNotFound.into());
}; };
self.log( self.log("auth.reset", Some(&name), None, true, Some("local command"))?;
"admin.reset",
Some(&name),
None,
true,
Some("local command"),
)?;
Ok(temp) 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, AuthFailure::InvalidCredentials);
assert_eq!(unknown, bad); assert_eq!(unknown, bad);
assert_eq!(unknown.to_string(), bad.to_string()); assert_eq!(unknown.to_string(), bad.to_string());
// The throttle must not tell them apart either. // The throttle must not tell them apart either, per address or past the
for _ in 0..4 { // account-wide limit.
let _ = s.login("ghost", PW, "192.0.2.2".parse().unwrap(), T0); let spent: IpAddr = "192.0.2.2".parse().unwrap();
let _ = s.login("ana", WRONG, "192.0.2.2".parse().unwrap(), T0); 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 unknown = failure(s.login("ghost", PW, spent, T0));
let bad = failure(s.login("ana", WRONG, "192.0.2.3".parse().unwrap(), T0)); let bad = failure(s.login("ana", WRONG, spent, T0));
assert_eq!( assert_eq!(
unknown, unknown,
AuthFailure::Throttled { AuthFailure::Throttled {
@@ -393,25 +395,37 @@ fn same_error_for_unknown_user_and_bad_password() {
} }
); );
assert_eq!(unknown, bad); 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] #[test]
fn account_throttle_delay_grows_capped() { fn login_delay_grows_per_address() {
let (_d, s) = svc(); let (_d, s) = svc();
admin(&s); admin(&s);
let id = analyst(&s, "ana"); let id = analyst(&s, "ana");
let mut now = T0; let mut now = T0;
for _ in 0..4 { for _ in 0..5 {
assert_eq!( assert_eq!(
failure(s.login("ana", WRONG, ip(), now)), failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials AuthFailure::InvalidCredentials
); );
} }
assert_eq!( // Locked: even the right password is not evaluated from this address.
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
// Locked: even the right password is not evaluated.
assert_eq!( assert_eq!(
failure(s.login("ana", PW, ip(), now)), failure(s.login("ana", PW, ip(), now)),
AuthFailure::Throttled { AuthFailure::Throttled {
@@ -429,40 +443,204 @@ fn account_throttle_delay_grows_capped() {
retry_after_secs: 60 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; now += 61;
assert_eq!( session_of(s.login("ana", PW, ip(), now).unwrap());
failure(s2.login("ana", WRONG, ip(), now)), // None of it touched the user-bound counter.
AuthFailure::InvalidCredentials let (f, l) = s
);
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
.store .store
.read(|st| { .read(|st| {
let u = st.users.iter().find(|u| u.id == id).unwrap(); let u = st.users.iter().find(|u| u.id == id).unwrap();
(u.failed_attempts, u.locked_until) (u.failed_attempts, u.locked_until)
}) })
.unwrap(); .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] #[test]
@@ -505,7 +683,7 @@ fn bad_codes_count_towards_the_account_throttle() {
} }
#[test] #[test]
fn concurrent_guesses_cannot_outrun_the_account_throttle() { fn concurrent_guesses_cannot_outrun_the_address_throttle() {
let (_d, s) = svc(); let (_d, s) = svc();
admin(&s); admin(&s);
analyst(&s, "ana"); analyst(&s, "ana");
@@ -514,8 +692,8 @@ fn concurrent_guesses_cannot_outrun_the_account_throttle() {
.map(|i| { .map(|i| {
let s = &s; let s = &s;
sc.spawn(move || { sc.spawn(move || {
let addr = IpAddr::from([192, 0, 2, 100 + i]); let _ = i;
s.login("ana", WRONG, addr, T0) s.login("ana", WRONG, ip(), T0)
}) })
}) })
.collect(); .collect();
@@ -677,7 +855,7 @@ fn reset_admin_is_audited_and_forces_enrollment() {
let (_d, s) = svc(); let (_d, s) = svc();
let root = admin(&s); let root = admin(&s);
session_of_any(&s, &root); 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_eq!(sessions(&s, &root), 0);
assert!(temp.len() >= 24); assert!(temp.len() >= 24);
assert_eq!( assert_eq!(
@@ -689,15 +867,13 @@ fn reset_admin_is_audited_and_forces_enrollment() {
LoginStep::MfaEnrollRequired(_) LoginStep::MfaEnrollRequired(_)
)); ));
assert_eq!( assert_eq!(
failure(s.reset_admin("ghost", T0)), failure(s.reset_account("ghost", T0)),
AuthFailure::UserNotFound AuthFailure::UserNotFound
); );
analyst(&s, "ana");
assert_eq!(failure(s.reset_admin("ana", T0)), AuthFailure::UserNotFound);
let log = s.audit_tail(100).unwrap(); let log = s.audit_tail(100).unwrap();
assert!(log assert!(log
.iter() .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(); let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap();
assert!(!raw.contains(&temp)); 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); 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) { fn reset_and_enroll(s: &AuthService) -> (String, String) {
let id = admin(s); 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); enroll(s, &id, T0 + 200);
(id, temp) (id, temp)
} }
@@ -890,7 +1066,7 @@ fn flag_also_blocks_password_only_login() {
s.create_user("root", "second", PW, Role::Admin, T0) s.create_user("root", "second", PW, Role::Admin, T0)
.unwrap(); .unwrap();
let second = uid(&s, "second"); 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(); s.set_role("root", &second, Role::Analyst, T0).unwrap();
let t = change_ticket(s.login("second", &temp, ip(), T0).unwrap()); let t = change_ticket(s.login("second", &temp, ip(), T0).unwrap());
assert_eq!(sessions(&s, &second), 0); assert_eq!(sessions(&s, &second), 0);
+16 -5
View File
@@ -37,14 +37,18 @@ pub struct User {
pub totp_last_step: Option<u64>, pub totp_last_step: Option<u64>,
/// SHA-256 hex of each unused recovery code. /// SHA-256 hex of each unused recovery code.
pub recovery_hashes: Vec<String>, 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, 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, pub locked_until: u64,
/// Changes when the password changes and at each completed login, which /// Changes when the password changes and at each completed login, which
/// voids the pending MFA tokens issued before it. /// voids the pending MFA tokens issued before it.
pub auth_epoch: u64, 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, 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) if e.kind() == std::io::ErrorKind::NotFound => return Ok(AuthState::default()),
Err(e) => return Err(e.into()), Err(e) => return Err(e.into()),
}; };
let state: AuthState = serde_json::from_slice(&raw) let state: AuthState = serde_json::from_slice(&raw).map_err(|e| {
.map_err(|e| AcauaError::Auth(AuthFailure::StateCorrupt(e.to_string())))?; // 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 { if state.version == 0 || state.version > STATE_VERSION {
return Err(AuthFailure::StateVersionUnsupported(state.version).into()); return Err(AuthFailure::StateVersionUnsupported(state.version).into());
} }
+241 -56
View File
@@ -1,6 +1,11 @@
//! Attempt limits: the per-account delay schedule, the in-memory IP limiter //! Attempt limits: the delay schedule, the in-memory IP limiter and the
//! and the in-memory stand-in that makes unknown usernames throttle exactly //! in-memory login throttle.
//! like real accounts. //!
//! 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::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv6Addr}; 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. /// The failure count at which the delay starts.
const ACCOUNT_FREE_FAILURES: u32 = 5; const ACCOUNT_FREE_FAILURES: u32 = 5;
const ACCOUNT_DELAY_BASE_SECS: u64 = 30; 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 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 /// Delay after `failures` failures: none before the 5th, then 30 s doubling
/// up to 900 s. /// 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> { fn guard<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
// The tables stay valid whatever a panicking holder did. // The tables stay valid whatever a panicking holder did.
m.lock().unwrap_or_else(|e| e.into_inner()) m.lock().unwrap_or_else(|e| e.into_inner())
@@ -125,72 +158,151 @@ impl IpLimiter {
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, Default)]
struct UnknownEntry { struct PairEntry {
failures: u32, failures: u32,
last: u64,
locked_until: 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, last: u64,
} }
/// Failure schedule for usernames with no account. Without it, only real #[derive(Debug, Default)]
/// accounts would ever answer "throttled", which reveals who exists. Bounded struct LoginTables {
/// and in memory: an attacker must not be able to grow state on disk. 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)] #[derive(Debug)]
pub struct UnknownAccounts { pub struct LoginThrottle {
capacity: usize, pair_capacity: usize,
table: Mutex<HashMap<String, UnknownEntry>>, account_capacity: usize,
tables: Mutex<LoginTables>,
} }
impl Default for UnknownAccounts { impl Default for LoginThrottle {
fn default() -> Self { fn default() -> Self {
Self::with_capacity(UNKNOWN_TABLE_CAPACITY) Self::with_capacity(PAIR_TABLE_CAPACITY, ACCOUNT_TABLE_CAPACITY)
} }
} }
impl UnknownAccounts { impl LoginThrottle {
pub fn with_capacity(capacity: usize) -> Self { pub fn with_capacity(pair_capacity: usize, account_capacity: usize) -> Self {
Self { Self {
capacity, pair_capacity,
table: Mutex::new(HashMap::new()), account_capacity,
tables: Mutex::new(LoginTables::default()),
} }
} }
/// Same contract as a real account: `Err` with the remaining delay, or /// Counts the attempt as failed before Argon2 runs, so parallel guesses
/// the attempt is counted as a failure. /// cannot all pass. `right_password` undoes it. `Err` carries the seconds
pub fn acquire(&self, key: &str, now: u64) -> Result<(), u64> { /// to wait; a refused attempt never lengthens any delay.
let mut table = guard(&self.table); pub fn acquire(&self, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> {
if !table.contains_key(key) && table.len() >= self.capacity { let pair_key = (account.to_string(), ip_key(ip));
let stalest = table 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 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);
}
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, 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() .iter()
.min_by_key(|(_, e)| e.last) .min_by_key(|(_, e)| e.last)
.map(|(k, _)| k.clone()); .map(|(k, _)| k.clone());
if let Some(k) = stalest { if let Some(k) = stalest {
table.remove(&k); pairs.remove(&k);
} }
} }
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);
}
entry.failures = entry.failures.saturating_add(1);
entry.locked_until = lock_until(entry.failures, now);
Ok(())
}
#[cfg(test)] fn evict_account(accounts: &mut HashMap<String, AccountEntry>) {
fn tracked(&self) -> usize { let stalest = accounts
guard(&self.table).len() .iter()
.min_by_key(|(_, e)| e.last)
.map(|(k, _)| k.clone());
if let Some(k) = stalest {
accounts.remove(&k);
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::net::Ipv4Addr;
#[test] #[test]
fn delay_starts_at_fifth_failure_grows_and_caps() { fn delay_starts_at_fifth_failure_grows_and_caps() {
let seq: Vec<u64> = (0..=12).map(account_delay).collect(); let seq: Vec<u64> = (0..=12).map(account_delay).collect();
@@ -238,23 +350,96 @@ mod tests {
} }
assert!(l.tracked() <= 4); assert!(l.tracked() <= 4);
} }
#[test] fn addr(n: u8) -> IpAddr {
fn unknown_accounts_follow_the_account_schedule() { IpAddr::from([198, 51, 100, n])
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));
} }
#[test] #[test]
fn unknown_table_stays_bounded() { fn a_pair_follows_the_schedule_and_other_addresses_stay_free() {
let u = UnknownAccounts::with_capacity(3); let t = LoginThrottle::default();
for i in 0..20u64 { for _ in 0..5 {
u.acquire(&format!("k{i}"), i).unwrap(); 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), KeyInvalid(&'static str),
#[error("sealed value is malformed or failed authentication")] #[error("sealed value is malformed or failed authentication")]
SealInvalid, SealInvalid,
#[error("MFA is not enabled for this account")]
MfaNotEnabled,
#[error("auth state is corrupted: {0}")] #[error("auth state is corrupted: {0}")]
StateCorrupt(String), StateCorrupt(String),
#[error("auth state version {0} is not supported")] #[error("auth state version {0} is not supported")]