Skip to main content

universal_exports/
login_limit.rs

1//! How often a password or key may be tried at the login route.
2//!
3//! A secret is only as strong as the number of guesses allowed against it, whoever checks it.
4//! Before an authenticator is asked anything, a try is counted twice: against the address it
5//! came from and against the account name it is for. A try past either count is refused
6//! without being judged, the right secret along with the wrong ones, and the caller is told
7//! how long to wait.
8
9use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
10use std::num::NonZeroU32;
11use std::sync::atomic::{AtomicU32, Ordering};
12use std::time::Duration;
13
14use axum::http::{HeaderMap, HeaderName};
15use governor::clock::{Clock, DefaultClock};
16use governor::middleware::NoOpMiddleware;
17use governor::state::keyed::DashMapStateStore;
18use governor::{Quota, RateLimiter};
19
20/// How many password or key tries the login route allows, and where it finds the address a
21/// try came from. Every field has a default that is safe for a gateway on the public
22/// internet; raise a count for an office behind one address.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct LoginLimits {
25    /// Tries a minute from one address (an IPv6 address counts as its /64 network). Default 5.
26    pub per_address: NonZeroU32,
27    /// Tries in ten minutes for one account name, from anywhere. Default 10.
28    pub per_name: NonZeroU32,
29    /// A header the trusted reverse proxy sets to the client's address, such as
30    /// `x-forwarded-for` (the last entry is used) or `x-real-ip`. The gateway listens on
31    /// loopback behind that proxy, so without it every try comes from one address. Default none.
32    pub address_header: Option<HeaderName>,
33    /// The longest an account name is told apart by; longer names count as one. Default 64.
34    pub name_bytes: usize,
35    /// Every this many checks, the counts of addresses and names gone quiet are dropped, at
36    /// least 1. Default 256.
37    pub forget_every: u32,
38    /// How long a try from one address is counted. Default one minute.
39    pub address_window: Duration,
40    /// How long a try for one account name is counted. Default ten minutes.
41    pub name_window: Duration,
42    /// How long a sign-in that has passed its first step waits for the next. Default five
43    /// minutes.
44    pub pending_seconds: Duration,
45    /// Tries at the next step one waiting sign-in allows before it ends. Default 5.
46    pub pending_tries: u32,
47    /// How old a sign-in may be and still replace its person's second factor without a code from
48    /// it. Default five minutes.
49    pub enrol_fresh_seconds: Duration,
50    /// The most certificate pins one account may hold, and the most certificate-field entries.
51    /// Default 4.
52    pub max_pins: usize,
53}
54
55impl Default for LoginLimits {
56    fn default() -> Self {
57        let table = ai6::LoginTable::default();
58        Self {
59            per_address: NonZeroU32::new(5).unwrap_or(NonZeroU32::MIN),
60            per_name: NonZeroU32::new(10).unwrap_or(NonZeroU32::MIN),
61            address_header: None,
62            name_bytes: table.name_bytes.or_max(),
63            forget_every: u32::try_from(table.forget_every).unwrap_or(u32::MAX),
64            address_window: table.address_window.0,
65            name_window: table.name_window.0,
66            pending_seconds: table.pending_seconds.0,
67            pending_tries: u32::try_from(table.pending_tries).unwrap_or(u32::MAX),
68            enrol_fresh_seconds: table.enrol_fresh_seconds.0,
69            max_pins: usize::try_from(table.max_pins).unwrap_or(usize::MAX),
70        }
71    }
72}
73
74type Counted<K> = RateLimiter<K, DashMapStateStore<K>, DefaultClock, NoOpMiddleware>;
75
76/// The counts of tries kept by a gateway.
77pub(crate) struct LoginGuard {
78    clock: DefaultClock,
79    addresses: Counted<IpAddr>,
80    names: Counted<String>,
81    address_header: Option<HeaderName>,
82    checks: AtomicU32,
83    name_bytes: usize,
84    forget_every: u32,
85}
86
87impl LoginGuard {
88    pub(crate) fn new(limits: &LoginLimits) -> Self {
89        let clock = DefaultClock::default();
90        Self {
91            addresses: RateLimiter::dashmap_with_clock(
92                quota(limits.address_window, limits.per_address),
93                clock.clone(),
94            ),
95            names: RateLimiter::dashmap_with_clock(
96                quota(limits.name_window, limits.per_name),
97                clock.clone(),
98            ),
99            clock,
100            address_header: limits.address_header.clone(),
101            checks: AtomicU32::new(0),
102            name_bytes: limits.name_bytes,
103            forget_every: limits.forget_every.max(1),
104        }
105    }
106
107    /// What the proxy configured by `address_header` said: its last line, which is the proxy's
108    /// own (a client's lines come before it), and that line's rightmost entry.
109    fn forwarded(&self, headers: &HeaderMap) -> Option<IpAddr> {
110        let name = self.address_header.as_ref()?;
111        headers
112            .get_all(name)
113            .iter()
114            .next_back()
115            .and_then(|value| value.to_str().ok())
116            .and_then(|value| value.rsplit(',').next())
117            .and_then(|entry| parse_address(entry.trim()))
118    }
119
120    /// The address a request came from, for a sign-in policy: with a header configured only what
121    /// the proxy said in it, so a request that bypassed the proxy has none (never the peer's);
122    /// else the connection's. An IPv4-mapped IPv6 address is the IPv4 address.
123    pub(crate) fn address(
124        &self,
125        headers: &HeaderMap,
126        connection: Option<SocketAddr>,
127    ) -> Option<IpAddr> {
128        let found = if self.address_header.is_some() {
129            self.forwarded(headers)
130        } else {
131            connection.map(|address| address.ip())
132        };
133        found.map(unmapped)
134    }
135
136    /// What a request is counted against: the proxy's address, else the connection's, else a
137    /// single shared bucket for the unknown.
138    pub(crate) fn source(&self, headers: &HeaderMap, connection: Option<SocketAddr>) -> IpAddr {
139        self.forwarded(headers)
140            .or_else(|| connection.map(|address| address.ip()))
141            .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))
142    }
143
144    /// Counts a try from `source` for `name`. `Some(wait)` when it is one too many, and it is
145    /// then not to be judged.
146    pub(crate) fn tried(&self, source: IpAddr, name: &str) -> Option<Duration> {
147        if self.checks.fetch_add(1, Ordering::Relaxed) % self.forget_every == self.forget_every - 1
148        {
149            self.forget();
150        }
151        let now = self.clock.now();
152        if let Err(refused) = self.addresses.check_key(&network(source)) {
153            return Some(refused.wait_time_from(now));
154        }
155        // Counted only for a try the address was allowed, so an address held off cannot use
156        // up a name's tries.
157        let refused = self.names.check_key(&called(name, self.name_bytes)).err()?;
158        Some(refused.wait_time_from(now))
159    }
160
161    /// Counts a try for the account `name` alone, whatever address it came from: a try already
162    /// counted against its address. `Some(wait)` when it is one too many.
163    pub(crate) fn tried_name(&self, name: &str) -> Option<Duration> {
164        if self.checks.fetch_add(1, Ordering::Relaxed) % self.forget_every == self.forget_every - 1
165        {
166            self.forget();
167        }
168        let now = self.clock.now();
169        let refused = self.names.check_key(&called(name, self.name_bytes)).err()?;
170        Some(refused.wait_time_from(now))
171    }
172
173    /// Counts a try from `source` that names no account, so no account pays for it. `Some(wait)`
174    /// when it is one too many.
175    pub(crate) fn tried_address(&self, source: IpAddr) -> Option<Duration> {
176        if self.checks.fetch_add(1, Ordering::Relaxed) % self.forget_every == self.forget_every - 1
177        {
178            self.forget();
179        }
180        let now = self.clock.now();
181        let refused = self.addresses.check_key(&network(source)).err()?;
182        Some(refused.wait_time_from(now))
183    }
184
185    fn forget(&self) {
186        self.addresses.retain_recent();
187        self.addresses.shrink_to_fit();
188        self.names.retain_recent();
189        self.names.shrink_to_fit();
190    }
191}
192
193/// `tries` allowed in `window`, all of them at once or spread evenly.
194fn quota(window: Duration, tries: NonZeroU32) -> Quota {
195    Quota::with_period(window / tries.get())
196        .unwrap_or_else(|| Quota::per_minute(tries))
197        .allow_burst(tries)
198}
199
200/// An address as a header or a socket writes it, with or without a port.
201fn parse_address(text: &str) -> Option<IpAddr> {
202    text.parse::<IpAddr>()
203        .or_else(|_| text.parse::<SocketAddr>().map(|address| address.ip()))
204        .ok()
205}
206
207/// An IPv4-mapped IPv6 address as the IPv4 address it stands for.
208fn unmapped(address: IpAddr) -> IpAddr {
209    match address {
210        IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(address, IpAddr::V4),
211        v4 => v4,
212    }
213}
214
215/// What a try is counted against for an address: itself, or for IPv6 the /64 network it is in,
216/// since whoever has one address there has all of them.
217pub(crate) fn network(address: IpAddr) -> IpAddr {
218    match address {
219        IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
220            Some(v4) => IpAddr::V4(v4),
221            None => IpAddr::V6(Ipv6Addr::from(u128::from(v6) & !u128::from(u64::MAX))),
222        },
223        v4 => v4,
224    }
225}
226
227/// What a try is counted against for a name: the name as accounts are told apart, and no
228/// longer than is worth keeping.
229fn called(name: &str, name_bytes: usize) -> String {
230    let lowered = name.trim().to_lowercase();
231    let mut end = lowered.len().min(name_bytes);
232    while !lowered.is_char_boundary(end) {
233        end -= 1;
234    }
235    lowered[..end].to_owned()
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    fn limits(per_address: u32, per_name: u32) -> LoginLimits {
243        LoginLimits {
244            per_address: NonZeroU32::new(per_address).unwrap(),
245            per_name: NonZeroU32::new(per_name).unwrap(),
246            address_header: None,
247            ..LoginLimits::default()
248        }
249    }
250
251    fn address(text: &str) -> IpAddr {
252        text.parse().unwrap()
253    }
254
255    #[test]
256    fn the_defaults_allow_five_a_minute_per_address_and_ten_per_name() {
257        let defaults = LoginLimits::default();
258        assert_eq!(defaults.per_address.get(), 5);
259        assert_eq!(defaults.per_name.get(), 10);
260        assert!(defaults.address_header.is_none());
261    }
262
263    #[test]
264    fn an_address_is_refused_after_its_count_and_told_how_long_to_wait() {
265        let guard = LoginGuard::new(&limits(3, 100));
266        let source = address("192.0.2.1");
267        for attempt in 0..3 {
268            assert!(guard.tried(source, "alice").is_none(), "try {attempt}");
269        }
270        let wait = guard.tried(source, "alice").expect("the fourth is refused");
271        assert!(wait > Duration::ZERO && wait <= Duration::from_secs(60));
272        assert!(guard.tried(address("192.0.2.2"), "alice").is_none());
273    }
274
275    #[test]
276    fn a_name_is_refused_after_its_count_from_any_address() {
277        let guard = LoginGuard::new(&limits(100, 2));
278        assert!(guard.tried(address("192.0.2.1"), "Alice").is_none());
279        assert!(guard.tried(address("192.0.2.2"), " alice ").is_none());
280        assert!(guard.tried(address("192.0.2.3"), "ALICE").is_some());
281        assert!(guard.tried(address("192.0.2.3"), "bob").is_none());
282    }
283
284    #[test]
285    fn an_address_held_off_does_not_use_up_a_names_tries() {
286        let guard = LoginGuard::new(&limits(1, 2));
287        assert!(guard.tried(address("192.0.2.1"), "alice").is_none());
288        for _ in 0..10 {
289            assert!(guard.tried(address("192.0.2.1"), "alice").is_some());
290        }
291        assert!(guard.tried(address("192.0.2.9"), "alice").is_none());
292    }
293
294    #[test]
295    fn an_ipv6_address_counts_as_its_network() {
296        let guard = LoginGuard::new(&limits(1, 100));
297        assert!(guard.tried(address("2001:db8:1:2::1"), "a").is_none());
298        assert!(guard.tried(address("2001:db8:1:2:ffff::9"), "b").is_some());
299        assert!(guard.tried(address("2001:db8:1:3::1"), "c").is_none());
300        assert_eq!(network(address("::ffff:192.0.2.1")), address("192.0.2.1"));
301    }
302
303    #[test]
304    fn a_long_name_is_counted_by_its_first_bytes_without_splitting_a_character() {
305        let long = "é".repeat(100);
306        assert!(called(&long, 64).len() <= 64);
307        assert!(called(&long, 64).chars().all(|character| character == 'é'));
308        assert_eq!(
309            called(&long, 5).len(),
310            4,
311            "the name_bytes setting bounds it"
312        );
313    }
314
315    #[test]
316    fn the_source_is_the_proxy_header_then_the_connection_then_one_shared_bucket() {
317        let mut configured = limits(5, 10);
318        configured.address_header = Some(HeaderName::from_static("x-forwarded-for"));
319        let guard = LoginGuard::new(&configured);
320        let connection: SocketAddr = "127.0.0.1:5000".parse().unwrap();
321        let mut headers = HeaderMap::new();
322        assert_eq!(
323            guard.source(&headers, Some(connection)),
324            address("127.0.0.1")
325        );
326        assert_eq!(guard.source(&headers, None), address("0.0.0.0"));
327        // The trusted proxy appends the address it saw; what came before is the client's claim.
328        headers.insert(
329            "x-forwarded-for",
330            "203.0.113.50, 198.51.100.7".parse().unwrap(),
331        );
332        assert_eq!(
333            guard.source(&headers, Some(connection)),
334            address("198.51.100.7")
335        );
336        headers.insert("x-forwarded-for", "not an address".parse().unwrap());
337        assert_eq!(
338            guard.source(&headers, Some(connection)),
339            address("127.0.0.1")
340        );
341        // Without a configured header the claim is ignored.
342        let plain = LoginGuard::new(&limits(5, 10));
343        headers.insert("x-forwarded-for", "198.51.100.7".parse().unwrap());
344        assert_eq!(
345            plain.source(&headers, Some(connection)),
346            address("127.0.0.1")
347        );
348    }
349
350    #[test]
351    fn the_policy_reads_the_last_line_and_rightmost_entry_of_the_address_header() {
352        let guard = LoginGuard::new(&LoginLimits {
353            address_header: Some(HeaderName::from_static("x-forwarded-for")),
354            ..limits(5, 10)
355        });
356        let mut headers = HeaderMap::new();
357        // The client's own line comes first; the proxy's, last, is the one that counts.
358        headers.append("x-forwarded-for", "6.6.6.6".parse().unwrap());
359        headers.append("x-forwarded-for", "203.0.113.7, 10.1.2.3".parse().unwrap());
360        assert_eq!(guard.address(&headers, None), Some(address("10.1.2.3")));
361    }
362
363    #[test]
364    fn a_missing_or_unreadable_header_is_no_address_to_the_policy_whatever_the_peer() {
365        let guard = LoginGuard::new(&LoginLimits {
366            address_header: Some(HeaderName::from_static("x-forwarded-for")),
367            ..limits(5, 10)
368        });
369        let peer: SocketAddr = "127.0.0.1:5000".parse().unwrap();
370        let mut headers = HeaderMap::new();
371        assert_eq!(guard.address(&headers, Some(peer)), None);
372        headers.insert("x-forwarded-for", "not an address".parse().unwrap());
373        assert_eq!(guard.address(&headers, Some(peer)), None);
374        // Counting keeps its shared bucket for the peer.
375        assert_eq!(guard.source(&headers, Some(peer)), address("127.0.0.1"));
376        // With no header configured the peer is the address.
377        let plain = LoginGuard::new(&limits(5, 10));
378        assert_eq!(
379            plain.address(&headers, Some(peer)),
380            Some(address("127.0.0.1"))
381        );
382    }
383
384    #[test]
385    fn an_ipv4_mapped_address_is_the_ipv4_address_to_the_policy() {
386        let guard = LoginGuard::new(&LoginLimits {
387            address_header: Some(HeaderName::from_static("x-forwarded-for")),
388            ..limits(5, 10)
389        });
390        let mut headers = HeaderMap::new();
391        headers.insert("x-forwarded-for", "::ffff:10.1.2.3".parse().unwrap());
392        assert_eq!(guard.address(&headers, None), Some(address("10.1.2.3")));
393        let plain = LoginGuard::new(&limits(5, 10));
394        let peer: SocketAddr = "[::ffff:10.9.9.9]:5000".parse().unwrap();
395        assert_eq!(
396            plain.address(&HeaderMap::new(), Some(peer)),
397            Some(address("10.9.9.9"))
398        );
399    }
400}