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
@@ -7,7 +7,8 @@
|
||||
|
||||
use crate::web::{access_of, is_public, is_public_asset, Access, AppState};
|
||||
use acaua_core::auth::{
|
||||
csrf_matches, csrf_token, NewSession, PendingMfa, Principal, Role, Scope, TotpEnrollment, Via,
|
||||
csrf_matches, csrf_token, AuthService, LoginAttempt, NewSession, PendingMfa, Principal, Role,
|
||||
Scope, TotpEnrollment, Via,
|
||||
};
|
||||
use acaua_core::{AcauaError, AuthFailure};
|
||||
use axum::extract::rejection::JsonRejection;
|
||||
@@ -20,6 +21,7 @@ use axum::{Extension, Json};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub const MAX_BODY_BYTES: usize = 64 * 1024;
|
||||
@@ -544,15 +546,46 @@ pub async fn login(
|
||||
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||
JsonBody(b): JsonBody<LoginBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let auth = state.auth.clone();
|
||||
let now = unix_now();
|
||||
// Whatever can be refused without Argon2 is, before the queue for a permit,
|
||||
// or a flood of hopeless attempts would stand in front of the owner.
|
||||
let auth = state.auth.clone();
|
||||
let username = b.username;
|
||||
let mut queued = blocking(move || {
|
||||
let attempt = auth.login_begin(&username, ip, now)?;
|
||||
Ok(QueuedLogin {
|
||||
auth,
|
||||
attempt: Some(attempt),
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
let password = b.password;
|
||||
let step = hashing(&state, move || {
|
||||
auth.login(&b.username, &b.password, ip, now)
|
||||
let attempt = queued
|
||||
.attempt
|
||||
.take()
|
||||
.ok_or(AuthFailure::InvalidCredentials)?;
|
||||
queued.auth.login_finish(attempt, &password, now)
|
||||
})
|
||||
.await?;
|
||||
Ok(step_reply(&state, &step))
|
||||
}
|
||||
|
||||
/// A login between its checks and its evaluation. A client that disconnects
|
||||
/// while queued made no guess, so what it reserved goes back.
|
||||
struct QueuedLogin {
|
||||
auth: Arc<AuthService>,
|
||||
attempt: Option<LoginAttempt>,
|
||||
}
|
||||
|
||||
impl Drop for QueuedLogin {
|
||||
fn drop(&mut self) {
|
||||
if let Some(attempt) = self.attempt.take() {
|
||||
self.auth.login_abandon(attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct MfaBody {
|
||||
pending: String,
|
||||
|
||||
@@ -86,6 +86,20 @@ fn fresh(transport: Transport) -> (tempfile::TempDir, Arc<AuthService>, Router)
|
||||
(dir, auth, build_app(state))
|
||||
}
|
||||
|
||||
fn fresh_with_state(
|
||||
transport: Transport,
|
||||
) -> (tempfile::TempDir, Arc<AuthService>, AppState, Router) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let auth = Arc::new(AuthService::open(dir.path(), None).unwrap());
|
||||
let state = AppState::new(
|
||||
Arc::new(Storage::open(dir.path()).unwrap()),
|
||||
auth.clone(),
|
||||
transport,
|
||||
);
|
||||
let app = build_app(state.clone());
|
||||
(dir, auth, state, app)
|
||||
}
|
||||
|
||||
/// Server with `root` (admin, MFA active) and analyst `ana` (no MFA).
|
||||
fn harness(transport: Transport) -> H {
|
||||
let (dir, auth, app) = fresh(transport);
|
||||
@@ -1180,3 +1194,90 @@ async fn auth_state_tells_whether_mfa_is_on() {
|
||||
let on = send(&h.app, state(&cookie)).await;
|
||||
assert_eq!(on.json()["mfa_enabled"], serde_json::json!(true));
|
||||
}
|
||||
|
||||
async fn login_from(app: &Router, peer: IpAddr, user: &str, pw: &str) -> Reply {
|
||||
let mut r = post_json(
|
||||
"/api/auth/login",
|
||||
serde_json::json!({"username": user, "password": pw}),
|
||||
);
|
||||
r.extensions_mut()
|
||||
.insert(axum::extract::ConnectInfo(SocketAddr::new(peer, 4000)));
|
||||
send(app, r).await
|
||||
}
|
||||
|
||||
fn v4_peer(i: u32) -> IpAddr {
|
||||
IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i))
|
||||
}
|
||||
|
||||
fn spend_budget(auth: &AuthService, user: &str, n: u32, t: u64) {
|
||||
for i in 0..n {
|
||||
let attempt = auth.login_begin(user, v4_peer(i), t).unwrap();
|
||||
let _ = auth.login_failed(attempt, t);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_login_takes_no_hashing_permit() {
|
||||
let (_d, auth, state, app) = fresh_with_state(Transport::Local);
|
||||
let code = auth.ensure_bootstrap(now()).unwrap().unwrap();
|
||||
auth.complete_bootstrap(&code, "root", PW, peer(), now())
|
||||
.unwrap();
|
||||
auth.create_user("root", "ana", PW, Role::Analyst, now())
|
||||
.unwrap();
|
||||
spend_budget(&auth, "ana", 100, now());
|
||||
let held = state
|
||||
.argon2
|
||||
.clone()
|
||||
.acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32)
|
||||
.await
|
||||
.unwrap();
|
||||
let refused = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
login_from(&app, v4_peer(500), "ana", PW),
|
||||
)
|
||||
.await
|
||||
.expect("a refusal must not wait for a permit");
|
||||
assert_eq!(refused.status, StatusCode::TOO_MANY_REQUESTS);
|
||||
assert!(refused.headers.contains_key(header::RETRY_AFTER));
|
||||
// An attempt that can still succeed does wait for one.
|
||||
let waits = tokio::time::timeout(
|
||||
std::time::Duration::from_millis(300),
|
||||
login_from(&app, v4_peer(501), "root", PW),
|
||||
)
|
||||
.await;
|
||||
assert!(waits.is_err());
|
||||
drop(held);
|
||||
// That cancelled attempt gave back what it held.
|
||||
assert_eq!(
|
||||
login_from(&app, v4_peer(501), "root", PW).await.status,
|
||||
StatusCode::OK
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parallel_requests_stop_at_the_cap() {
|
||||
let (_d, auth, _state, app) = fresh_with_state(Transport::Local);
|
||||
let code = auth.ensure_bootstrap(now()).unwrap().unwrap();
|
||||
auth.complete_bootstrap(&code, "root", PW, peer(), now())
|
||||
.unwrap();
|
||||
auth.create_user("root", "ana", PW, Role::Analyst, now())
|
||||
.unwrap();
|
||||
spend_budget(&auth, "ana", 96, now());
|
||||
let mut tasks = Vec::new();
|
||||
for i in 0..16 {
|
||||
let app = app.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
login_from(&app, v4_peer(1000 + i), "ana", PW2).await.status
|
||||
}));
|
||||
}
|
||||
let mut wrong = 0;
|
||||
let mut refused = 0;
|
||||
for t in tasks {
|
||||
match t.await.unwrap() {
|
||||
StatusCode::UNAUTHORIZED => wrong += 1,
|
||||
StatusCode::TOO_MANY_REQUESTS => refused += 1,
|
||||
other => panic!("{other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!((wrong, refused), (4, 12));
|
||||
}
|
||||
Reference in new issue
Block a user