//! Brute-force protection for sign-in, by client, so one attacker can't lock the owner out. //! //! Each client (an IPv4 address, or an IPv6 /64, which one machine usually controls whole) gets //! [`FREE_FAILURES`] failed attempts; each one after that locks that client out for longer, //! from a minute up to [`LONGEST_LOCK`]. A client's failures are forgotten after //! [`FORGET_AFTER`] without one, so an old attack never turns a later typo into a long lock. //! //! On top of that, every client together may fail at most [`GLOBAL_PER_HOUR`] times an hour. //! That caps how fast a distributed attack can guess. One client, held back by its own lock, //! can never reach it alone. Browsers that have signed in before carry a trusted-device token //! (see `gitv_web::auth::Credentials::device_token`) and aren't held to this cap, so many //! addresses together can't lock the owner out; their own per-client lock still applies. //! //! Every method takes the current time, so the rules can be tested without waiting. use std::collections::{HashMap, VecDeque}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::time::{Duration, Instant}; use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts; use axum::http::{Extensions, HeaderMap}; /// Failed attempts a client may make before it is locked out. pub const FREE_FAILURES: u32 = 5; /// The longest a client's lock lasts; it starts at a minute and doubles with each failure. pub const LONGEST_LOCK: Duration = Duration::from_secs(15 * 60); /// How long without a failure before a client's count starts again. pub const FORGET_AFTER: Duration = Duration::from_secs(60 * 60); /// Failures allowed per hour from every client together. pub const GLOBAL_PER_HOUR: usize = 60; /// Clients remembered at once. Past this, the one quiet longest is forgotten first. const MAX_CLIENTS: usize = 4096; const HOUR: Duration = Duration::from_secs(60 * 60); /// Who is signing in, as far as throttling is concerned: their address, or their IPv6 /64. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Client(IpAddr); impl Client { pub fn new(address: IpAddr) -> Client { Client(match address { IpAddr::V6(v6) => match v6.to_ipv4_mapped() { Some(v4) => IpAddr::V4(v4), None => { let prefix = u128::from(v6) & !((1u128 << 64) - 1); IpAddr::V6(Ipv6Addr::from(prefix)) } }, v4 => v4, }) } /// The client a request came from. gitv-web listens on loopback behind Caddy, which puts /// the real client's address last in `X-Forwarded-For`; that header is believed only from /// a loopback peer, since anyone else could write anything there. Without connection /// details (as in unit tests) every request is one unknown client. pub fn of(headers: &HeaderMap, extensions: &Extensions) -> Client { let peer = extensions.get::>().map(|ConnectInfo(addr)| addr.ip()); let forwarded = || { let header = headers.get_all("x-forwarded-for").iter().next_back()?.to_str().ok()?; header.rsplit(',').next()?.trim().parse::().ok() }; let address = match peer { Some(peer) if peer.is_loopback() => forwarded().unwrap_or(peer), Some(peer) => peer, None => IpAddr::V4(Ipv4Addr::UNSPECIFIED), }; Client::new(address) } } /// The address, or the /64 for IPv6, as the logs show it. impl std::fmt::Display for Client { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.0 { IpAddr::V4(v4) => write!(f, "{v4}"), IpAddr::V6(v6) => write!(f, "{v6}/64"), } } } impl FromRequestParts for Client { type Rejection = std::convert::Infallible; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { Ok(Client::of(&parts.headers, &parts.extensions)) } } /// One client's record. #[derive(Default)] struct Record { failures: u32, last_failure: Option, locked_until: Option, } impl Record { fn locked_for(&self, now: Instant) -> Option { self.locked_until.and_then(|until| until.checked_duration_since(now)).filter(|d| !d.is_zero()) } fn forgotten(&self, now: Instant) -> bool { self.locked_for(now).is_none() && self.last_failure.is_none_or(|t| now.duration_since(t) >= FORGET_AFTER) } fn fail(&mut self, now: Instant) { if self.forgotten(now) { self.failures = 0; } self.failures += 1; self.last_failure = Some(now); if let Some(over) = self.failures.checked_sub(FREE_FAILURES + 1) { let lock = Duration::from_secs(60).saturating_mul(1 << over.min(10)).min(LONGEST_LOCK); self.locked_until = Some(now + lock); } } } #[derive(Default)] pub struct Throttle { clients: HashMap, /// When the failures of the last hour happened, oldest first, at most [`GLOBAL_PER_HOUR`]. recent: VecDeque, } impl Throttle { /// How long `client` must wait before trying again, if at all. A `trusted` browser (one that /// has signed in before) waits only for its own lock, never the global cap. pub fn locked_for(&self, client: Client, now: Instant, trusted: bool) -> Option { let own = self.clients.get(&client).and_then(|r| r.locked_for(now)); let global = (!trusted && self.recent.len() >= GLOBAL_PER_HOUR) .then(|| self.recent.front().and_then(|first| (*first + HOUR).checked_duration_since(now))) .flatten() .filter(|d| !d.is_zero()); own.max(global) } /// Count a failed attempt by `client`. pub fn fail(&mut self, client: Client, now: Instant) { while self.recent.front().is_some_and(|t| now.duration_since(*t) >= HOUR) { self.recent.pop_front(); } if self.recent.len() >= GLOBAL_PER_HOUR { self.recent.pop_front(); } self.recent.push_back(now); self.clients.retain(|_, record| !record.forgotten(now)); if self.clients.len() >= MAX_CLIENTS && !self.clients.contains_key(&client) { let quietest = self.clients.iter().min_by_key(|(_, r)| r.last_failure).map(|(c, _)| *c); if let Some(quietest) = quietest { self.clients.remove(&quietest); } } self.clients.entry(client).or_default().fail(now); } /// `client` got everything right: its own record is cleared. Other clients' are not, and /// neither is the global count, which other clients' failures still make up. pub fn succeed(&mut self, client: Client) { self.clients.remove(&client); } #[cfg(test)] pub fn failures(&self, client: Client) -> u32 { self.clients.get(&client).map_or(0, |r| r.failures) } } #[cfg(test)] mod tests { use super::*; fn ip(text: &str) -> Client { Client::new(text.parse().unwrap()) } #[test] fn a_client_is_locked_after_its_free_failures_and_longer_each_time() { let (mut throttle, now, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7")); (0..FREE_FAILURES).for_each(|_| throttle.fail(a, now)); assert_eq!(throttle.locked_for(a, now, false), None); throttle.fail(a, now); assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(60))); throttle.fail(a, now); assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(120))); (0..20).for_each(|_| throttle.fail(a, now)); assert_eq!(throttle.locked_for(a, now, false), Some(LONGEST_LOCK)); } #[test] fn one_clients_lock_leaves_the_others_alone() { let (mut throttle, now) = (Throttle::default(), Instant::now()); (0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now)); assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some()); assert_eq!(throttle.locked_for(ip("198.51.100.1"), now, false), None, "the owner elsewhere isn't locked"); } #[test] fn failures_are_forgotten_after_a_quiet_hour() { let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7")); (0..12).for_each(|_| throttle.fail(a, start)); // Long after the lock ran out and an hour after the last failure, one typo is free. let later = start + LONGEST_LOCK + FORGET_AFTER; throttle.fail(a, later); assert_eq!(throttle.locked_for(a, later, false), None); assert_eq!(throttle.failures(a), 1); } #[test] fn failures_inside_the_hour_still_count() { let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7")); (0..=FREE_FAILURES).for_each(|_| throttle.fail(a, start)); // The minute's lock is over, but the next failure comes well inside the hour. let later = start + Duration::from_secs(120); assert_eq!(throttle.locked_for(a, later, false), None); throttle.fail(a, later); assert_eq!(throttle.locked_for(a, later, false), Some(Duration::from_secs(120))); } #[test] fn success_clears_only_that_client() { let (mut throttle, now) = (Throttle::default(), Instant::now()); (0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now)); (0..3).for_each(|_| throttle.fail(ip("198.51.100.1"), now)); throttle.succeed(ip("198.51.100.1")); assert_eq!(throttle.failures(ip("198.51.100.1")), 0); assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some(), "the attacker stays locked"); } #[test] fn many_clients_together_are_held_to_the_hourly_rate() { let (mut throttle, start) = (Throttle::default(), Instant::now()); let owner = ip("198.51.100.1"); // Each attacker address stays within its own free failures. for i in 0..GLOBAL_PER_HOUR { let at = start + Duration::from_secs(i as u64); throttle.fail(Client::new(IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i as u32))), at); } let now = start + Duration::from_secs(GLOBAL_PER_HOUR as u64); let wait = throttle.locked_for(owner, now, false).expect("the hourly budget is spent"); assert!(wait <= HOUR && wait > HOUR - Duration::from_secs(61), "{wait:?}"); assert_eq!(throttle.locked_for(owner, now, true), None, "a browser that signed in before isn't held"); // As the oldest failures age out of the hour, attempts are allowed again. assert_eq!(throttle.locked_for(owner, start + HOUR, false), None); } #[test] fn a_trusted_browser_is_still_held_by_its_own_lock() { let (mut throttle, now, typist) = (Throttle::default(), Instant::now(), ip("198.51.100.2")); (0..=FREE_FAILURES).for_each(|_| throttle.fail(typist, now)); assert!(throttle.locked_for(typist, now, true).is_some()); } #[test] fn ipv6_clients_are_grouped_by_their_64_and_mapped_ipv4_is_ipv4() { assert_eq!(ip("2001:db8:1:2:aaaa::1"), ip("2001:db8:1:2:ffff::9")); assert_ne!(ip("2001:db8:1:2::1"), ip("2001:db8:1:3::1")); assert_eq!(ip("::ffff:203.0.113.7"), ip("203.0.113.7")); } #[test] fn clients_show_as_their_address_or_64() { assert_eq!(ip("203.0.113.7").to_string(), "203.0.113.7"); assert_eq!(ip("2001:db8:1:2:aaaa::1").to_string(), "2001:db8:1:2::/64"); } #[test] fn forwarded_addresses_are_believed_only_from_loopback() { let parts = |peer: &str, forwarded: Option<&str>| { let mut request = axum::http::Request::builder(); if let Some(value) = forwarded { request = request.header("x-forwarded-for", value); } let (mut parts, ()) = request.body(()).unwrap().into_parts(); parts.extensions.insert(ConnectInfo(peer.parse::().unwrap())); parts }; let of = |peer, forwarded| { let parts = parts(peer, forwarded); Client::of(&parts.headers, &parts.extensions) }; assert_eq!(of("127.0.0.1:5000", Some("203.0.113.7")), ip("203.0.113.7"), "Caddy's word is taken"); assert_eq!(of("127.0.0.1:5000", Some("1.2.3.4, 203.0.113.7")), ip("203.0.113.7"), "the last hop is Caddy's"); assert_eq!(of("127.0.0.1:5000", Some("not an address")), ip("127.0.0.1")); assert_eq!(of("127.0.0.1:5000", None), ip("127.0.0.1")); assert_eq!(of("[::1]:5000", Some("2001:db8::1")), ip("2001:db8::1")); assert_eq!(of("192.0.2.5:5000", Some("203.0.113.7")), ip("192.0.2.5"), "nobody else's is"); } }