fix(auth): keep a queued login from passing the cap
A reservation could expire while its request queued, and the guess was then evaluated anyway. The wait for a hashing permit is now bounded to 30 s, and an attempt whose reservation is gone is refused at permit time. At the cap, each failure now reaches the disk, so a restart cannot reopen a slot. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4a48f2bd35
commit
9ef86ac425
5 files changed
+237
-66
No files matched your search
@@ -7,8 +7,8 @@
|
|||||||
|
|
||||||
use crate::web::{access_of, is_public, is_public_asset, Access, AppState};
|
use crate::web::{access_of, is_public, is_public_asset, Access, AppState};
|
||||||
use acaua_core::auth::{
|
use acaua_core::auth::{
|
||||||
csrf_matches, csrf_token, AuthService, LoginAttempt, NewSession, PendingMfa, Principal, Role,
|
csrf_matches, csrf_token, AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa,
|
||||||
Scope, TotpEnrollment, Via,
|
Principal, Role, Scope, TotpEnrollment, Via,
|
||||||
};
|
};
|
||||||
use acaua_core::{AcauaError, AuthFailure};
|
use acaua_core::{AcauaError, AuthFailure};
|
||||||
use axum::extract::rejection::JsonRejection;
|
use axum::extract::rejection::JsonRejection;
|
||||||
@@ -22,7 +22,7 @@ use serde::de::DeserializeOwned;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
pub const MAX_BODY_BYTES: usize = 64 * 1024;
|
pub const MAX_BODY_BYTES: usize = 64 * 1024;
|
||||||
pub const ARGON2_CONCURRENCY: usize = 8;
|
pub const ARGON2_CONCURRENCY: usize = 8;
|
||||||
@@ -32,6 +32,8 @@ const PENDING_HEADER: &str = "x-acaua-pending";
|
|||||||
const LOGIN_PAGE: &str = "/login.html";
|
const LOGIN_PAGE: &str = "/login.html";
|
||||||
const AUDIT_DEFAULT: usize = 200;
|
const AUDIT_DEFAULT: usize = 200;
|
||||||
const AUDIT_MAX: usize = 1000;
|
const AUDIT_MAX: usize = 1000;
|
||||||
|
/// The longest a login waits for a hashing permit.
|
||||||
|
const LOGIN_QUEUE_WAIT: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
/// A clock before 1970 fails closed: everything looks expired.
|
/// A clock before 1970 fails closed: everything looks expired.
|
||||||
pub fn unix_now() -> u64 {
|
pub fn unix_now() -> u64 {
|
||||||
@@ -551,7 +553,7 @@ pub async fn login(
|
|||||||
// or a flood of hopeless attempts would stand in front of the owner.
|
// or a flood of hopeless attempts would stand in front of the owner.
|
||||||
let auth = state.auth.clone();
|
let auth = state.auth.clone();
|
||||||
let username = b.username;
|
let username = b.username;
|
||||||
let mut queued = blocking(move || {
|
let queued = blocking(move || {
|
||||||
let attempt = auth.login_begin(&username, ip, now)?;
|
let attempt = auth.login_begin(&username, ip, now)?;
|
||||||
Ok(QueuedLogin {
|
Ok(QueuedLogin {
|
||||||
auth,
|
auth,
|
||||||
@@ -559,23 +561,46 @@ pub async fn login(
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
let password = b.password;
|
let step = finish_queued(&state, queued, b.password, LOGIN_QUEUE_WAIT).await?;
|
||||||
let step = hashing(&state, move || {
|
Ok(step_reply(&state, &step))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates a queued login once a permit is free. Past `wait` it is refused
|
||||||
|
/// like any other throttled attempt, and gives back what it reserved.
|
||||||
|
pub(crate) async fn finish_queued(
|
||||||
|
state: &AppState,
|
||||||
|
mut queued: QueuedLogin,
|
||||||
|
password: String,
|
||||||
|
wait: Duration,
|
||||||
|
) -> Result<LoginStep, ApiError> {
|
||||||
|
// Only the queue is timed: once the hash runs, it runs to its answer. Leaving
|
||||||
|
// here drops `queued`, which gives back what the attempt reserved.
|
||||||
|
let permit = match tokio::time::timeout(wait, state.argon2.clone().acquire_owned()).await {
|
||||||
|
Ok(permit) => permit.map_err(|_| internal())?,
|
||||||
|
Err(_) => {
|
||||||
|
return Err(AuthFailure::Throttled {
|
||||||
|
retry_after_secs: wait.as_secs().max(1),
|
||||||
|
}
|
||||||
|
.into())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
blocking(move || {
|
||||||
|
let _permit = permit;
|
||||||
let attempt = queued
|
let attempt = queued
|
||||||
.attempt
|
.attempt
|
||||||
.take()
|
.take()
|
||||||
.ok_or(AuthFailure::InvalidCredentials)?;
|
.ok_or(AuthFailure::InvalidCredentials)?;
|
||||||
queued.auth.login_finish(attempt, &password, now)
|
// The clock now, not at arrival: the queue took time.
|
||||||
|
queued.auth.login_finish(attempt, &password, unix_now())
|
||||||
})
|
})
|
||||||
.await?;
|
.await
|
||||||
Ok(step_reply(&state, &step))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A login between its checks and its evaluation. A client that disconnects
|
/// A login between its checks and its evaluation. A client that disconnects
|
||||||
/// while queued made no guess, so what it reserved goes back.
|
/// while queued made no guess, so what it reserved goes back.
|
||||||
struct QueuedLogin {
|
pub(crate) struct QueuedLogin {
|
||||||
auth: Arc<AuthService>,
|
pub(crate) auth: Arc<AuthService>,
|
||||||
attempt: Option<LoginAttempt>,
|
pub(crate) attempt: Option<LoginAttempt>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for QueuedLogin {
|
impl Drop for QueuedLogin {
|
||||||
|
|||||||
@@ -1281,3 +1281,50 @@ async fn parallel_requests_stop_at_the_cap() {
|
|||||||
}
|
}
|
||||||
assert_eq!((wrong, refused), (4, 12));
|
assert_eq!((wrong, refused), (4, 12));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_login_stuck_in_the_queue_is_refused_and_gives_back_its_reservation() {
|
||||||
|
let (_d, auth, state, _app) = fresh_with_state(Transport::Local);
|
||||||
|
let code = auth.ensure_bootstrap(now()).unwrap().unwrap();
|
||||||
|
auth.complete_bootstrap(&code, "root", PW, peer(), now())
|
||||||
|
.unwrap();
|
||||||
|
auth.create_user("root", "ana", PW, Role::Analyst, now())
|
||||||
|
.unwrap();
|
||||||
|
spend_budget(&auth, "ana", 99, now());
|
||||||
|
let queued = crate::auth_http::QueuedLogin {
|
||||||
|
auth: auth.clone(),
|
||||||
|
attempt: Some(auth.login_begin("ana", v4_peer(700), now()).unwrap()),
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
auth.login_begin("ana", v4_peer(701), now()).is_err(),
|
||||||
|
"full"
|
||||||
|
);
|
||||||
|
let held = state
|
||||||
|
.argon2
|
||||||
|
.clone()
|
||||||
|
.acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let done = tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(5),
|
||||||
|
crate::auth_http::finish_queued(
|
||||||
|
&state,
|
||||||
|
queued,
|
||||||
|
PW.to_string(),
|
||||||
|
std::time::Duration::from_millis(50),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("the wait is bounded");
|
||||||
|
let Err(error) = done else {
|
||||||
|
panic!("expected a refusal")
|
||||||
|
};
|
||||||
|
let reply = error.into_response();
|
||||||
|
assert_eq!(reply.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
assert!(reply.headers().contains_key(header::RETRY_AFTER));
|
||||||
|
drop(held);
|
||||||
|
assert!(
|
||||||
|
auth.login_begin("ana", v4_peer(702), now()).is_ok(),
|
||||||
|
"returned"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -34,6 +34,8 @@ const TEMP_PASSWORD_BYTES: usize = 24;
|
|||||||
/// A completed login makes its address known for this long.
|
/// A completed login makes its address known for this long.
|
||||||
const KNOWN_ADDRESS_SECS: u64 = 30 * 86_400;
|
const KNOWN_ADDRESS_SECS: u64 = 30 * 86_400;
|
||||||
const KNOWN_ADDRESS_MAX: usize = 10;
|
const KNOWN_ADDRESS_MAX: usize = 10;
|
||||||
|
/// Retry-After for an attempt that lost its place under the budget.
|
||||||
|
const RESERVATION_LOST_RETRY_SECS: u64 = 30;
|
||||||
|
|
||||||
/// A session just created. The token exists only here; the store has its hash.
|
/// A session just created. The token exists only here; the store has its hash.
|
||||||
pub struct NewSession {
|
pub struct NewSession {
|
||||||
@@ -118,8 +120,8 @@ pub struct LoginAttempt {
|
|||||||
ip: IpAddr,
|
ip: IpAddr,
|
||||||
/// Hash that makes `ip` known to this account once the login completes.
|
/// Hash that makes `ip` known to this account once the login completes.
|
||||||
address: String,
|
address: String,
|
||||||
/// The reservation was charged to the budget.
|
/// The attempt's place under the budget, if it was charged.
|
||||||
budgeted: bool,
|
reservation: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for LoginAttempt {
|
impl std::fmt::Debug for LoginAttempt {
|
||||||
@@ -586,8 +588,8 @@ impl AuthService {
|
|||||||
};
|
};
|
||||||
// The hash keeps a password typed into the wrong field out of memory.
|
// The hash keeps a password typed into the wrong field out of memory.
|
||||||
let throttle_key = hash_token(&key);
|
let throttle_key = hash_token(&key);
|
||||||
let budgeted = match self.logins.acquire(&throttle_key, ip, known, stored, now) {
|
let reservation = match self.logins.acquire(&throttle_key, ip, known, stored, now) {
|
||||||
Ok(budgeted) => budgeted,
|
Ok(reservation) => reservation,
|
||||||
Err(left) => {
|
Err(left) => {
|
||||||
self.ips.release(ip);
|
self.ips.release(ip);
|
||||||
return Err(throttled(left));
|
return Err(throttled(left));
|
||||||
@@ -598,7 +600,7 @@ impl AuthService {
|
|||||||
account,
|
account,
|
||||||
ip,
|
ip,
|
||||||
address,
|
address,
|
||||||
budgeted,
|
reservation,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -606,15 +608,14 @@ impl AuthService {
|
|||||||
pub fn login_abandon(&self, attempt: LoginAttempt) {
|
pub fn login_abandon(&self, attempt: LoginAttempt) {
|
||||||
self.ips.release(attempt.ip);
|
self.ips.release(attempt.ip);
|
||||||
self.logins
|
self.logins
|
||||||
.abandon(&attempt.throttle_key, attempt.ip, attempt.budgeted);
|
.abandon(&attempt.throttle_key, attempt.ip, attempt.reservation);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Records an evaluated failure and returns its refusal.
|
/// Records an evaluated failure and returns its refusal.
|
||||||
pub fn login_failed(&self, attempt: LoginAttempt, now: u64) -> Result<LoginStep> {
|
pub fn login_failed(&self, attempt: LoginAttempt, now: u64) -> Result<LoginStep> {
|
||||||
let note = if attempt.budgeted {
|
let note = match attempt.reservation {
|
||||||
self.logins.failed(&attempt.throttle_key, now)
|
Some(id) => self.logins.failed(&attempt.throttle_key, id, now),
|
||||||
} else {
|
None => Default::default(),
|
||||||
Default::default()
|
|
||||||
};
|
};
|
||||||
let id = attempt.account.as_ref().map(|k| k.id.as_str());
|
let id = attempt.account.as_ref().map(|k| k.id.as_str());
|
||||||
if let Some(state) = ¬e.write {
|
if let Some(state) = ¬e.write {
|
||||||
@@ -664,6 +665,14 @@ impl AuthService {
|
|||||||
password: &str,
|
password: &str,
|
||||||
now: u64,
|
now: u64,
|
||||||
) -> Result<LoginStep> {
|
) -> Result<LoginStep> {
|
||||||
|
// A reservation can be swept or evicted while its request waits. Its place
|
||||||
|
// may be taken by now, so evaluating this guess could pass the cap.
|
||||||
|
if let Some(id) = attempt.reservation {
|
||||||
|
if !self.logins.renew(&attempt.throttle_key, id, now) {
|
||||||
|
self.login_abandon(attempt);
|
||||||
|
return Err(throttled(RESERVATION_LOST_RETRY_SECS));
|
||||||
|
}
|
||||||
|
}
|
||||||
let Some(known) = &attempt.account else {
|
let Some(known) = &attempt.account else {
|
||||||
verify_password(None, password);
|
verify_password(None, password);
|
||||||
return self.login_failed(attempt, now);
|
return self.login_failed(attempt, now);
|
||||||
@@ -720,7 +729,7 @@ impl AuthService {
|
|||||||
};
|
};
|
||||||
self.ips.release(attempt.ip);
|
self.ips.release(attempt.ip);
|
||||||
self.logins
|
self.logins
|
||||||
.right_password(&attempt.throttle_key, attempt.ip, attempt.budgeted);
|
.right_password(&attempt.throttle_key, attempt.ip, attempt.reservation);
|
||||||
let detail = match step {
|
let detail = match step {
|
||||||
LoginStep::Session(_) => "session",
|
LoginStep::Session(_) => "session",
|
||||||
LoginStep::MfaRequired(_) => "mfa required",
|
LoginStep::MfaRequired(_) => "mfa required",
|
||||||
|
|||||||
@@ -1717,3 +1717,45 @@ fn mfa_changes_kill_stale_pending_tokens() {
|
|||||||
s.disable_mfa("ana", &id, None, None, T0 + 120).unwrap();
|
s.disable_mfa("ana", &id, None, None, T0 + 120).unwrap();
|
||||||
assert_ne!(user_of(&s, &id).auth_epoch, before);
|
assert_ne!(user_of(&s, &id).auth_epoch, before);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_expired_reservation_is_refused_and_the_cap_holds() {
|
||||||
|
let (_d, s) = svc();
|
||||||
|
admin(&s);
|
||||||
|
let id = analyst(&s, "ana");
|
||||||
|
let held: Vec<_> = (0..100u32)
|
||||||
|
.map(|i| s.login_begin("ana", v4(i), T0).unwrap())
|
||||||
|
.collect();
|
||||||
|
// The sweep takes them, and their places go to fresh failures.
|
||||||
|
let later = T0 + 3601;
|
||||||
|
assert_eq!(burn(&s, "ana", 100, 1000, later), 100);
|
||||||
|
let lines = s.audit_tail(100_000).unwrap().len();
|
||||||
|
for a in held {
|
||||||
|
assert!(matches!(
|
||||||
|
failure(s.login_finish(a, WRONG, later)),
|
||||||
|
AuthFailure::Throttled { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
assert_eq!(s.audit_tail(100_000).unwrap().len(), lines, "not evaluated");
|
||||||
|
assert_eq!(user_of(&s, &id).budget_times.len(), 100);
|
||||||
|
assert!(s.login_begin("ana", v4(5000), later).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failure_at_the_cap_survives_a_restart() {
|
||||||
|
let (d, s) = svc();
|
||||||
|
admin(&s);
|
||||||
|
let id = analyst(&s, "ana");
|
||||||
|
burn(&s, "ana", 1, 0, T0);
|
||||||
|
burn(&s, "ana", 1, 1, T0 + 10);
|
||||||
|
burn(&s, "ana", 98, 2, T0 + 1000);
|
||||||
|
// Two slots open ten seconds apart, inside one write interval.
|
||||||
|
assert_eq!(burn(&s, "ana", 1, 200, T0 + DAY), 1);
|
||||||
|
assert_eq!(burn(&s, "ana", 1, 201, T0 + DAY + 10), 1);
|
||||||
|
assert_eq!(
|
||||||
|
user_of(&s, &id).budget_times.iter().max(),
|
||||||
|
Some(&(T0 + DAY + 10))
|
||||||
|
);
|
||||||
|
let s = AuthService::open(d.path(), None).unwrap();
|
||||||
|
assert!(s.login_begin("ana", v4(300), T0 + DAY + 11).is_err());
|
||||||
|
}
|
||||||
@@ -25,7 +25,8 @@ pub const BUDGET_MAX_FAILURES: usize = 100;
|
|||||||
pub const BUDGET_WINDOW_SECS: u64 = 86_400;
|
pub const BUDGET_WINDOW_SECS: u64 = 86_400;
|
||||||
/// A budget is written to disk at most this often, bar crossing the cap.
|
/// A budget is written to disk at most this often, bar crossing the cap.
|
||||||
pub const BUDGET_WRITE_SECS: u64 = 60;
|
pub const BUDGET_WRITE_SECS: u64 = 60;
|
||||||
/// A reservation older than this lost its request, whatever happened to it.
|
/// Only a sweep for reservations whose request died unseen: an attempt whose
|
||||||
|
/// reservation is gone is refused, see `renew`.
|
||||||
const RESERVATION_SECS: u64 = 3600;
|
const RESERVATION_SECS: u64 = 3600;
|
||||||
const IP_TABLE_CAPACITY: usize = 100_000;
|
const IP_TABLE_CAPACITY: usize = 100_000;
|
||||||
const PAIR_TABLE_CAPACITY: usize = 100_000;
|
const PAIR_TABLE_CAPACITY: usize = 100_000;
|
||||||
@@ -186,11 +187,13 @@ pub struct BudgetState {
|
|||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
struct BudgetEntry {
|
struct BudgetEntry {
|
||||||
state: BudgetState,
|
state: BudgetState,
|
||||||
/// Instants of attempts between their checks and their evaluation. They
|
/// `(id, instant)` of attempts between their checks and their evaluation.
|
||||||
/// hold a place under the cap but are not failures yet.
|
/// They hold a place under the cap but are not failures yet.
|
||||||
reserved: Vec<u64>,
|
reserved: Vec<(u64, u64)>,
|
||||||
written_at: u64,
|
written_at: u64,
|
||||||
written_count: usize,
|
written_count: usize,
|
||||||
|
/// Newest failure the disk holds.
|
||||||
|
written_newest: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BudgetEntry {
|
impl BudgetEntry {
|
||||||
@@ -199,7 +202,7 @@ impl BudgetEntry {
|
|||||||
.times
|
.times
|
||||||
.retain(|t| now.saturating_sub(*t) < BUDGET_WINDOW_SECS);
|
.retain(|t| now.saturating_sub(*t) < BUDGET_WINDOW_SECS);
|
||||||
self.reserved
|
self.reserved
|
||||||
.retain(|t| now.saturating_sub(*t) < RESERVATION_SECS);
|
.retain(|(_, t)| now.saturating_sub(*t) < RESERVATION_SECS);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn weight(&self, now: u64) -> usize {
|
fn weight(&self, now: u64) -> usize {
|
||||||
@@ -231,6 +234,7 @@ pub struct FailureNote {
|
|||||||
struct LoginTables {
|
struct LoginTables {
|
||||||
pairs: HashMap<(String, IpAddr), PairEntry>,
|
pairs: HashMap<(String, IpAddr), PairEntry>,
|
||||||
budgets: HashMap<String, BudgetEntry>,
|
budgets: HashMap<String, BudgetEntry>,
|
||||||
|
next_reservation: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Failure counts for login attempts, known username or not. In memory and
|
/// Failure counts for login attempts, known username or not. In memory and
|
||||||
@@ -260,8 +264,8 @@ impl LoginThrottle {
|
|||||||
|
|
||||||
/// Reserves the attempt before Argon2 runs, in one step under one lock, so
|
/// Reserves the attempt before Argon2 runs, in one step under one lock, so
|
||||||
/// parallel guesses cannot pass the cap. `right_password` or `abandon` undoes
|
/// parallel guesses cannot pass the cap. `right_password` or `abandon` undoes
|
||||||
/// it; `failed` makes it a failure. `Ok` says whether the budget was charged;
|
/// it; `failed` makes it a failure. `Ok` holds the budget reservation, if one
|
||||||
/// `Err` carries the seconds to wait, and a refusal changes no count.
|
/// was taken; `Err` carries the seconds to wait, and a refusal changes no count.
|
||||||
pub fn acquire(
|
pub fn acquire(
|
||||||
&self,
|
&self,
|
||||||
account: &str,
|
account: &str,
|
||||||
@@ -269,7 +273,7 @@ impl LoginThrottle {
|
|||||||
known: bool,
|
known: bool,
|
||||||
stored: BudgetState,
|
stored: BudgetState,
|
||||||
now: u64,
|
now: u64,
|
||||||
) -> Result<bool, u64> {
|
) -> Result<Option<u64>, u64> {
|
||||||
let pair_key = (account.to_string(), address_key(ip));
|
let pair_key = (account.to_string(), address_key(ip));
|
||||||
let generation = stored.generation;
|
let generation = stored.generation;
|
||||||
let mut guard = guard(&self.tables);
|
let mut guard = guard(&self.tables);
|
||||||
@@ -295,9 +299,11 @@ impl LoginThrottle {
|
|||||||
}
|
}
|
||||||
let mut budget = t.budgets.get(account).cloned().unwrap_or_else(|| {
|
let mut budget = t.budgets.get(account).cloned().unwrap_or_else(|| {
|
||||||
let written_count = stored.times.len();
|
let written_count = stored.times.len();
|
||||||
|
let written_newest = stored.times.iter().max().copied().unwrap_or(0);
|
||||||
BudgetEntry {
|
BudgetEntry {
|
||||||
state: stored,
|
state: stored,
|
||||||
written_count,
|
written_count,
|
||||||
|
written_newest,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -317,27 +323,52 @@ impl LoginThrottle {
|
|||||||
pair.last = if pair_failures == 0 { now } else { pair_last };
|
pair.last = if pair_failures == 0 { now } else { pair_last };
|
||||||
pair.locked_until = lock_until(pair.failures, now);
|
pair.locked_until = lock_until(pair.failures, now);
|
||||||
|
|
||||||
if !known {
|
let reservation = (!known).then(|| {
|
||||||
budget.reserved.push(now);
|
t.next_reservation = t.next_reservation.wrapping_add(1);
|
||||||
}
|
budget.reserved.push((t.next_reservation, now));
|
||||||
|
t.next_reservation
|
||||||
|
});
|
||||||
if !t.budgets.contains_key(account) && t.budgets.len() >= self.budget_capacity {
|
if !t.budgets.contains_key(account) && t.budgets.len() >= self.budget_capacity {
|
||||||
evict_budget(&mut t.budgets, self.budget_capacity, now);
|
evict_budget(&mut t.budgets, self.budget_capacity, now);
|
||||||
}
|
}
|
||||||
t.budgets.insert(account.to_string(), budget);
|
t.budgets.insert(account.to_string(), budget);
|
||||||
Ok(!known)
|
Ok(reservation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called with a permit in hand, just before Argon2. `false`: the reservation
|
||||||
|
/// is gone, its place may belong to someone else, and the attempt must not be
|
||||||
|
/// evaluated. `true` restarts its clock, so it cannot expire during the hash.
|
||||||
|
pub fn renew(&self, account: &str, reservation: u64, now: u64) -> bool {
|
||||||
|
let mut t = guard(&self.tables);
|
||||||
|
let Some(e) = t.budgets.get_mut(account) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
e.prune(now);
|
||||||
|
match e.reserved.iter_mut().find(|(id, _)| *id == reservation) {
|
||||||
|
Some(held) => {
|
||||||
|
held.1 = now;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A reservation was evaluated and failed. Says what the caller must write
|
/// A reservation was evaluated and failed. Says what the caller must write
|
||||||
/// and audit, once the throttle's lock is gone.
|
/// and audit, once the throttle's lock is gone.
|
||||||
pub fn failed(&self, account: &str, now: u64) -> FailureNote {
|
pub fn failed(&self, account: &str, reservation: u64, now: u64) -> FailureNote {
|
||||||
let mut t = guard(&self.tables);
|
let mut t = guard(&self.tables);
|
||||||
let Some(e) = t.budgets.get_mut(account) else {
|
let Some(e) = t.budgets.get_mut(account) else {
|
||||||
return FailureNote::default();
|
return FailureNote::default();
|
||||||
};
|
};
|
||||||
e.reserved.pop();
|
let held = take_reservation(e, reservation);
|
||||||
e.prune(now);
|
e.prune(now);
|
||||||
|
// Without its reservation (evicted during the hash) it counts only if
|
||||||
|
// that keeps the cap.
|
||||||
|
if held || e.weight(now) < BUDGET_MAX_FAILURES {
|
||||||
e.state.times.push(now);
|
e.state.times.push(now);
|
||||||
|
}
|
||||||
let count = e.state.times.len();
|
let count = e.state.times.len();
|
||||||
|
let newest = e.state.times.iter().max().copied().unwrap_or(0);
|
||||||
let over = count >= BUDGET_MAX_FAILURES;
|
let over = count >= BUDGET_MAX_FAILURES;
|
||||||
let audit = over
|
let audit = over
|
||||||
&& (e.state.audited_at == 0
|
&& (e.state.audited_at == 0
|
||||||
@@ -346,11 +377,14 @@ impl LoginThrottle {
|
|||||||
e.state.audited_at = now;
|
e.state.audited_at = now;
|
||||||
}
|
}
|
||||||
let due = e.written_at == 0 || now.saturating_sub(e.written_at) >= BUDGET_WRITE_SECS;
|
let due = e.written_at == 0 || now.saturating_sub(e.written_at) >= BUDGET_WRITE_SECS;
|
||||||
// Once over the cap nothing is evaluated, so a later write would not come.
|
// At the cap no further failure may come to carry this one to disk, and
|
||||||
let crossing = over && e.written_count < BUDGET_MAX_FAILURES;
|
// the older instants on disk may have left the window by a restart, so
|
||||||
let write = (due || crossing || audit).then(|| {
|
// the disk must hold the newest one.
|
||||||
|
let at_cap = over && (e.written_count < BUDGET_MAX_FAILURES || e.written_newest < newest);
|
||||||
|
let write = (due || at_cap || audit).then(|| {
|
||||||
e.written_at = now;
|
e.written_at = now;
|
||||||
e.written_count = count;
|
e.written_count = count;
|
||||||
|
e.written_newest = newest;
|
||||||
e.state.clone()
|
e.state.clone()
|
||||||
});
|
});
|
||||||
FailureNote { write, audit }
|
FailureNote { write, audit }
|
||||||
@@ -359,19 +393,21 @@ impl LoginThrottle {
|
|||||||
/// The password was right: this address is clear, and the reservation goes
|
/// The password was right: this address is clear, and the reservation goes
|
||||||
/// back. Other failures stay, or each login by the owner would hand a
|
/// back. Other failures stay, or each login by the owner would hand a
|
||||||
/// distributed attacker a fresh budget.
|
/// distributed attacker a fresh budget.
|
||||||
pub fn right_password(&self, account: &str, ip: IpAddr, budgeted: bool) {
|
pub fn right_password(&self, account: &str, ip: IpAddr, reservation: Option<u64>) {
|
||||||
let mut t = guard(&self.tables);
|
let mut t = guard(&self.tables);
|
||||||
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
|
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
|
||||||
pair.failures = 0;
|
pair.failures = 0;
|
||||||
pair.locked_until = 0;
|
pair.locked_until = 0;
|
||||||
}
|
}
|
||||||
if budgeted {
|
if let Some(id) = reservation {
|
||||||
release_reservation(&mut t, account);
|
if let Some(e) = t.budgets.get_mut(account) {
|
||||||
|
take_reservation(e, id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The attempt was never evaluated: it gives back what it reserved.
|
/// The attempt was never evaluated: it gives back what it reserved.
|
||||||
pub fn abandon(&self, account: &str, ip: IpAddr, budgeted: bool) {
|
pub fn abandon(&self, account: &str, ip: IpAddr, reservation: Option<u64>) {
|
||||||
let mut t = guard(&self.tables);
|
let mut t = guard(&self.tables);
|
||||||
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
|
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
|
||||||
pair.failures = pair.failures.saturating_sub(1);
|
pair.failures = pair.failures.saturating_sub(1);
|
||||||
@@ -379,8 +415,10 @@ impl LoginThrottle {
|
|||||||
pair.locked_until = 0;
|
pair.locked_until = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if budgeted {
|
if let Some(id) = reservation {
|
||||||
release_reservation(&mut t, account);
|
if let Some(e) = t.budgets.get_mut(account) {
|
||||||
|
take_reservation(e, id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,10 +429,10 @@ impl LoginThrottle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn release_reservation(t: &mut LoginTables, account: &str) {
|
fn take_reservation(e: &mut BudgetEntry, id: u64) -> bool {
|
||||||
if let Some(e) = t.budgets.get_mut(account) {
|
let before = e.reserved.len();
|
||||||
e.reserved.pop();
|
e.reserved.retain(|(held, _)| *held != id);
|
||||||
}
|
e.reserved.len() != before
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drops what no longer matters; if that frees no room, the entry with the
|
/// Drops what no longer matters; if that frees no room, the entry with the
|
||||||
@@ -482,6 +520,10 @@ mod tests {
|
|||||||
fn addr(n: u8) -> IpAddr {
|
fn addr(n: u8) -> IpAddr {
|
||||||
IpAddr::from([198, 51, 100, n])
|
IpAddr::from([198, 51, 100, n])
|
||||||
}
|
}
|
||||||
|
fn reserve(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<u64, u64> {
|
||||||
|
t.acquire(account, ip, false, BudgetState::default(), now)
|
||||||
|
.map(|id| id.expect("an unknown address is charged"))
|
||||||
|
}
|
||||||
/// An attempt from an address the account does not know.
|
/// An attempt from an address the account does not know.
|
||||||
fn pair(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> {
|
fn pair(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> {
|
||||||
t.acquire(account, ip, false, BudgetState::default(), now)
|
t.acquire(account, ip, false, BudgetState::default(), now)
|
||||||
@@ -526,9 +568,9 @@ mod tests {
|
|||||||
let mut through = 0;
|
let mut through = 0;
|
||||||
for i in 0..n {
|
for i in 0..n {
|
||||||
let ip = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + first + i));
|
let ip = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + first + i));
|
||||||
if pair(t, account, ip, now).is_ok() {
|
if let Ok(id) = reserve(t, account, ip, now) {
|
||||||
through += 1;
|
through += 1;
|
||||||
t.failed(account, now);
|
t.failed(account, id, now);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
through
|
through
|
||||||
@@ -547,7 +589,10 @@ mod tests {
|
|||||||
fn a_known_address_skips_the_budget_but_not_the_pair() {
|
fn a_known_address_skips_the_budget_but_not_the_pair() {
|
||||||
let t = LoginThrottle::default();
|
let t = LoginThrottle::default();
|
||||||
spend(&t, "k", 100, 0, 1000);
|
spend(&t, "k", 100, 0, 1000);
|
||||||
let known = |now| t.acquire("k", addr(1), true, BudgetState::default(), now);
|
let known = |now| {
|
||||||
|
t.acquire("k", addr(1), true, BudgetState::default(), now)
|
||||||
|
.map(|id| id.is_some())
|
||||||
|
};
|
||||||
for _ in 0..5 {
|
for _ in 0..5 {
|
||||||
assert_eq!(known(1000), Ok(false));
|
assert_eq!(known(1000), Ok(false));
|
||||||
}
|
}
|
||||||
@@ -557,14 +602,14 @@ mod tests {
|
|||||||
fn a_right_password_returns_only_a_reservation() {
|
fn a_right_password_returns_only_a_reservation() {
|
||||||
let t = LoginThrottle::default();
|
let t = LoginThrottle::default();
|
||||||
spend(&t, "k", 99, 0, 1000);
|
spend(&t, "k", 99, 0, 1000);
|
||||||
pair(&t, "k", addr(2), 1000).unwrap();
|
let id = reserve(&t, "k", addr(2), 1000).unwrap();
|
||||||
assert!(pair(&t, "k", addr(1), 1000).is_err(), "reserved counts");
|
assert!(pair(&t, "k", addr(1), 1000).is_err(), "reserved counts");
|
||||||
t.right_password("k", addr(2), false);
|
t.right_password("k", addr(2), None);
|
||||||
assert!(pair(&t, "k", addr(1), 1000).is_err(), "not charged");
|
assert!(pair(&t, "k", addr(1), 1000).is_err(), "not charged");
|
||||||
t.right_password("k", addr(2), true);
|
t.right_password("k", addr(2), Some(id));
|
||||||
pair(&t, "k", addr(1), 1000).unwrap();
|
let id = reserve(&t, "k", addr(1), 1000).unwrap();
|
||||||
t.failed("k", 1000);
|
t.failed("k", id, 1000);
|
||||||
t.right_password("k", addr(1), true);
|
t.right_password("k", addr(1), Some(id));
|
||||||
assert!(pair(&t, "k", addr(3), 1000).is_err(), "failures stay");
|
assert!(pair(&t, "k", addr(3), 1000).is_err(), "failures stay");
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
@@ -605,7 +650,8 @@ mod tests {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
t.acquire("k", addr(1), false, reset.clone(), 1000),
|
t.acquire("k", addr(1), false, reset.clone(), 1000)
|
||||||
|
.map(|id| id.is_some()),
|
||||||
Ok(true)
|
Ok(true)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -621,7 +667,8 @@ mod tests {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
t.acquire("k", addr(1), false, reset.clone(), 1000),
|
t.acquire("k", addr(1), false, reset.clone(), 1000)
|
||||||
|
.map(|id| id.is_some()),
|
||||||
Ok(true)
|
Ok(true)
|
||||||
);
|
);
|
||||||
// Pairs too, even for an account seen only from a known address.
|
// Pairs too, even for an account seen only from a known address.
|
||||||
@@ -631,7 +678,8 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
t.acquire("k", addr(1), true, reset.clone(), 1000),
|
t.acquire("k", addr(1), true, reset.clone(), 1000)
|
||||||
|
.map(|id| id.is_some()),
|
||||||
Ok(false)
|
Ok(false)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -673,15 +721,15 @@ mod tests {
|
|||||||
fn a_failure_asks_for_a_write_per_minute_and_at_the_crossing() {
|
fn a_failure_asks_for_a_write_per_minute_and_at_the_crossing() {
|
||||||
let t = LoginThrottle::default();
|
let t = LoginThrottle::default();
|
||||||
let note = |now| {
|
let note = |now| {
|
||||||
pair(&t, "k", addr(9), now).ok();
|
let id = reserve(&t, "k", addr(9), now).unwrap();
|
||||||
t.failed("k", now)
|
t.failed("k", id, now)
|
||||||
};
|
};
|
||||||
assert!(note(1000).write.is_some());
|
assert!(note(1000).write.is_some());
|
||||||
assert!(note(1000).write.is_none());
|
assert!(note(1000).write.is_none());
|
||||||
assert!(note(1000 + BUDGET_WRITE_SECS).write.is_some());
|
assert!(note(1000 + BUDGET_WRITE_SECS).write.is_some());
|
||||||
spend(&t, "x", 99, 0, 1000);
|
spend(&t, "x", 99, 0, 1000);
|
||||||
pair(&t, "x", addr(8), 1000).unwrap();
|
let id = reserve(&t, "x", addr(8), 1000).unwrap();
|
||||||
let crossing = t.failed("x", 1000);
|
let crossing = t.failed("x", id, 1000);
|
||||||
assert_eq!(crossing.write.map(|s| s.times.len()), Some(100));
|
assert_eq!(crossing.write.map(|s| s.times.len()), Some(100));
|
||||||
assert!(crossing.audit);
|
assert!(crossing.audit);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user