Skip to main content

session_guard/
risk.rs

1//! Scores the current request against a session's baseline.
2
3use chrono::{DateTime, TimeDelta, Utc};
4
5use crate::{
6    checks::{Check, Checks, Decision, Thresholds},
7    fingerprint::{Baseline, Fingerprint, anonymity_change, os_compatible},
8};
9
10/// The checks that fired for a request and their summed weight.
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub struct Assessment {
14    /// Sum of the weights of `signals`.
15    pub score: u32,
16    /// Enabled checks that fired, in [`Check::ALL`] order.
17    pub signals: Vec<Check>,
18}
19
20impl Assessment {
21    /// Maps the score onto a decision.
22    pub fn decision(&self, thresholds: &Thresholds) -> Decision {
23        thresholds.decide(self.score)
24    }
25
26    /// Adds a signal the fingerprint comparison cannot see, if `checks` enables it, keeping
27    /// [`Check::ALL`] order.
28    pub(crate) fn add(&mut self, check: Check, checks: &Checks) {
29        if let Some(weight) = checks.weight_of(check)
30            && !self.signals.contains(&check)
31        {
32            let at = self.signals.partition_point(|c| *c < check);
33            self.signals.insert(at, check);
34            self.score = self.score.saturating_add(weight);
35        }
36    }
37}
38
39/// Compares `current` against `baseline`.
40///
41/// A value the baseline knows but the request lacks counts as a change: stripping headers
42/// never lowers the score. Values the baseline never had are not compared. The one exception:
43/// on the baseline's network prefix with the same browser and OS, missing client hints and a
44/// missing Accept-Language are not scored, since some request types never send them.
45pub fn assess(
46    baseline: &Baseline,
47    current: &Fingerprint,
48    now: DateTime<Utc>,
49    ping_pong_window: TimeDelta,
50    checks: &Checks,
51) -> Assessment {
52    let known = &baseline.fingerprint;
53    let mut fired = Vec::with_capacity(4);
54    // Same network prefix and the same browser and OS: headers that some request types never
55    // send (client hints on WebSocket upgrades or EventSource, Accept-Language on bare fetches)
56    // are not news. Changed values still count, and a replayed token is caught by rotation.
57    let known_net = baseline.known_prefix(&current.ip_prefix);
58    let same_client = !current.ip_prefix.is_empty()
59        && known_net == Some(current.ip_prefix.as_str())
60        && known.browser.is_some()
61        && known.browser == current.browser
62        && known.os.is_some()
63        && known.os == current.os;
64
65    if let (Some(a), Some(b)) = (&known.os, &current.os)
66        && !os_compatible(a, b)
67    {
68        fired.push(Check::OsChanged);
69    }
70
71    if let (Some(a), Some(b)) = (&known.browser, &current.browser) {
72        if a != b {
73            fired.push(Check::BrowserChanged);
74        } else if let (Some(a), Some(b)) = (known.browser_major, current.browser_major)
75            && b < a
76        {
77            fired.push(Check::BrowserDowngraded);
78        }
79    }
80
81    if lost(known.browser.as_ref(), current.browser.as_ref()) || lost(known.os.as_ref(), current.os.as_ref()) {
82        fired.push(Check::UserAgentMissing);
83    }
84
85    if let (Some(a), Some(b)) = (&known.ch_platform, &current.ch_platform)
86        && !os_compatible(a, b)
87    {
88        fired.push(Check::PlatformHintChanged);
89    }
90
91    if !same_client
92        && (lost(known.ch_platform.as_ref(), current.ch_platform.as_ref())
93            || lost(known.ch_mobile.as_ref(), current.ch_mobile.as_ref()))
94    {
95        fired.push(Check::ClientHintsMissing);
96    }
97
98    if matches!((known.ch_mobile, current.ch_mobile), (Some(a), Some(b)) if a != b) {
99        fired.push(Check::MobileHintChanged);
100    }
101
102    if let (Some(platform), Some(os)) = (&current.ch_platform, &current.os)
103        && !os_compatible(platform, os)
104    {
105        fired.push(Check::InconsistentHints);
106    }
107
108    // Each address family is compared with its own known network: a dual-stack client
109    // alternating between them has not moved. The first request from a family is a move.
110    let moved = match known_net {
111        Some(net) => net != current.ip_prefix,
112        None => known.ip_prefix != current.ip_prefix,
113    };
114    if moved {
115        if differs(known.country.as_ref(), current.country.as_ref()) {
116            fired.push(Check::CountryChanged);
117        } else if differs(known.asn.as_ref(), current.asn.as_ref()) {
118            fired.push(Check::AsnChanged);
119        } else {
120            fired.push(Check::IpPrefixChanged);
121        }
122
123        let returned =
124            known_net.is_some() && baseline.previous_ip_prefix.as_deref() == Some(current.ip_prefix.as_str());
125        let recent = baseline
126            .ip_changed_at
127            .is_some_and(|at| now.signed_duration_since(at) <= ping_pong_window);
128        if returned && recent {
129            fired.push(Check::IpPingPong);
130        }
131
132        // Returning to the previous network is no news: the client was trusted there.
133        if !returned
134            && let (Some(was), Some(now)) = (known.anonymity, current.anonymity)
135            && let Some(check) = anonymity_change(was, now)
136        {
137            fired.push(check);
138        }
139    }
140
141    let version_changed = matches!((known.browser_major, current.browser_major), (Some(a), Some(b)) if a != b);
142    if !version_changed && differs(known.tls.as_ref(), current.tls.as_ref()) {
143        fired.push(Check::TlsChanged);
144    }
145
146    let language_dropped = current.accept_language.is_none();
147    if differs(known.accept_language.as_ref(), current.accept_language.as_ref()) && !(same_client && language_dropped) {
148        fired.push(Check::AcceptLanguageChanged);
149    }
150
151    let mut signals = Vec::with_capacity(fired.len());
152    let mut score = 0u32;
153    for check in Check::ALL {
154        if fired.contains(&check)
155            && let Some(weight) = checks.weight_of(check)
156        {
157            signals.push(check);
158            score = score.saturating_add(weight);
159        }
160    }
161    Assessment { score, signals }
162}
163
164/// Known and now different, or known and now missing.
165fn differs<T: PartialEq>(known: Option<&T>, current: Option<&T>) -> bool {
166    match (known, current) {
167        (Some(a), Some(b)) => a != b,
168        (Some(_), None) => true,
169        (None, _) => false,
170    }
171}
172
173fn lost<T>(known: Option<&T>, current: Option<&T>) -> bool {
174    known.is_some() && current.is_none()
175}
176
177#[cfg(test)]
178mod tests {
179    use proptest::prelude::*;
180
181    use super::*;
182    use crate::intel::Anonymity;
183
184    fn chrome_on_windows() -> Fingerprint {
185        Fingerprint {
186            ip_prefix: "203.0.113.0/24".to_owned(),
187            country: Some("BE".to_owned()),
188            asn: Some(5432),
189            browser: Some("Chrome".to_owned()),
190            browser_major: Some(141),
191            os: Some("Windows".to_owned()),
192            ch_platform: Some("Windows".to_owned()),
193            ch_mobile: Some(false),
194            accept_language: Some("nl-be,nl,en".to_owned()),
195            tls: Some("t13d1516h2_8daaf6152771_02713d6af862".to_owned()),
196            anonymity: Some(Anonymity::Direct),
197        }
198    }
199
200    fn via(anonymity: Anonymity) -> Fingerprint {
201        let mut fp = chrome_on_windows();
202        fp.ip_prefix = "198.51.100.0/24".to_owned();
203        fp.asn = Some(9009);
204        fp.anonymity = Some(anonymity);
205        fp
206    }
207
208    fn assess_now(baseline: &Baseline, current: &Fingerprint) -> Assessment {
209        assess(baseline, current, Utc::now(), TimeDelta::minutes(5), &Checks::default())
210    }
211
212    fn decide(current: &Fingerprint) -> (Decision, Vec<Check>) {
213        let a = assess_now(&Baseline::new(chrome_on_windows()), current);
214        (a.decision(&Thresholds::default()), a.signals)
215    }
216
217    #[test]
218    fn added_signals_keep_check_order_and_respect_weights() {
219        let mut current = chrome_on_windows();
220        current.ip_prefix = "198.51.100.0/24".to_owned();
221        current.asn = Some(6848);
222        current.accept_language = Some("en".to_owned());
223        let mut a = assess_now(&Baseline::new(chrome_on_windows()), &current);
224        a.add(Check::OrphanedToken, &Checks::default());
225        assert_eq!(
226            a.signals,
227            vec![Check::OrphanedToken, Check::AsnChanged, Check::AcceptLanguageChanged]
228        );
229        assert_eq!(a.score, 25 + 20 + 15);
230
231        let mut a = Assessment::default();
232        a.add(Check::OrphanedToken, &Checks::none());
233        assert_eq!(a, Assessment::default());
234    }
235
236    #[test]
237    fn identical_request_is_allowed() {
238        assert_eq!(decide(&chrome_on_windows()), (Decision::Allow, vec![]));
239    }
240
241    // Legitimate users: none of these may step up or revoke.
242
243    #[test]
244    fn network_switch_within_same_provider_is_allowed() {
245        let mut current = chrome_on_windows();
246        current.ip_prefix = "203.0.200.0/24".to_owned();
247        assert_eq!(decide(&current), (Decision::Allow, vec![Check::IpPrefixChanged]));
248    }
249
250    #[test]
251    fn wifi_to_mobile_data_is_allowed() {
252        let mut current = chrome_on_windows();
253        current.ip_prefix = "198.51.100.0/24".to_owned();
254        current.asn = Some(6848);
255        assert_eq!(decide(&current), (Decision::Allow, vec![Check::AsnChanged]));
256    }
257
258    #[test]
259    fn browser_update_is_allowed_even_though_tls_changes() {
260        let mut current = chrome_on_windows();
261        current.browser_major = Some(142);
262        current.tls = Some("t13d1517h2_8daaf6152771_b0da82dd1658".to_owned());
263        assert_eq!(decide(&current), (Decision::Allow, vec![]));
264    }
265
266    #[test]
267    fn language_tweak_is_allowed() {
268        let mut current = chrome_on_windows();
269        current.accept_language = Some("en".to_owned());
270        assert_eq!(decide(&current).0, Decision::Allow);
271    }
272
273    #[test]
274    fn android_desktop_mode_toggle_steps_up_not_revokes() {
275        let mut fp = chrome_on_windows();
276        fp.os = Some("Android".to_owned());
277        fp.ch_platform = Some("Android".to_owned());
278        fp.ch_mobile = Some(true);
279        let mut current = fp.clone();
280        current.os = Some("Linux".to_owned());
281        current.ch_mobile = Some(false);
282        let a = assess_now(&Baseline::new(fp), &current);
283        assert_eq!(a.signals, vec![Check::MobileHintChanged]);
284        assert_eq!(a.decision(&Thresholds::default()), Decision::StepUp);
285    }
286
287    #[test]
288    fn travel_abroad_steps_up_not_revokes() {
289        let mut current = chrome_on_windows();
290        current.ip_prefix = "192.0.2.0/24".to_owned();
291        current.country = Some("FR".to_owned());
292        current.asn = Some(3215);
293        assert_eq!(decide(&current), (Decision::StepUp, vec![Check::CountryChanged]));
294    }
295
296    #[test]
297    fn baseline_without_hints_ignores_hints() {
298        let mut firefox = chrome_on_windows();
299        firefox.browser = Some("Firefox".to_owned());
300        firefox.ch_platform = None;
301        firefox.ch_mobile = None;
302        let a = assess_now(&Baseline::new(firefox.clone()), &firefox);
303        assert_eq!(a.score, 0);
304    }
305
306    // Theft.
307
308    #[test]
309    fn different_operating_system_is_revoked() {
310        let mut current = chrome_on_windows();
311        current.os = Some("macOS".to_owned());
312        current.ch_platform = Some("macOS".to_owned());
313        assert_eq!(decide(&current).0, Decision::Revoke);
314    }
315
316    #[test]
317    fn different_browser_is_revoked() {
318        let mut current = chrome_on_windows();
319        current.browser = Some("Firefox".to_owned());
320        current.ch_platform = None;
321        current.ch_mobile = None;
322        assert_eq!(decide(&current).0, Decision::Revoke);
323    }
324
325    #[test]
326    fn empty_user_agent_cannot_bypass_checks() {
327        let mut current = chrome_on_windows();
328        current.browser = None;
329        current.browser_major = None;
330        current.os = None;
331        current.ch_platform = None;
332        current.ch_mobile = None;
333        let (decision, signals) = decide(&current);
334        assert!(signals.contains(&Check::UserAgentMissing));
335        assert!(signals.contains(&Check::ClientHintsMissing));
336        assert_eq!(decision, Decision::Revoke);
337    }
338
339    #[test]
340    fn dropping_only_the_mobile_hint_is_noticed() {
341        let mut current = chrome_on_windows();
342        current.ip_prefix = "198.51.100.0/24".to_owned();
343        current.ch_mobile = None;
344        assert_eq!(
345            decide(&current).1,
346            vec![Check::ClientHintsMissing, Check::IpPrefixChanged]
347        );
348    }
349
350    #[test]
351    fn missing_soft_headers_on_the_same_network_are_not_scored() {
352        let mut current = chrome_on_windows();
353        current.ch_platform = None;
354        current.ch_mobile = None;
355        current.accept_language = None;
356        assert_eq!(decide(&current).1, Vec::<Check>::new());
357    }
358
359    #[test]
360    fn stripping_soft_headers_never_lowers_the_score() {
361        let mut current = chrome_on_windows();
362        current.ip_prefix = "198.51.100.0/24".to_owned();
363        current.accept_language = None;
364        current.tls = None;
365        assert_eq!(
366            decide(&current).1,
367            vec![Check::TlsChanged, Check::AcceptLanguageChanged, Check::IpPrefixChanged]
368        );
369
370        let mut current = chrome_on_windows();
371        current.ip_prefix = "198.51.100.0/24".to_owned();
372        current.country = None;
373        assert_eq!(decide(&current).1, vec![Check::CountryChanged]);
374    }
375
376    #[test]
377    fn copied_user_agent_from_script_in_same_country_is_revoked() {
378        let mut current = chrome_on_windows();
379        current.ip_prefix = "198.51.100.0/24".to_owned();
380        current.asn = Some(9999);
381        current.ch_platform = None;
382        current.ch_mobile = None;
383        current.tls = Some("t13d311200_e8f1e7e78f70_d41ae481755e".to_owned());
384        current.accept_language = None;
385        assert_eq!(decide(&current).0, Decision::Revoke);
386    }
387
388    #[test]
389    fn spoofed_ua_contradicting_client_hints_is_flagged() {
390        let mut current = chrome_on_windows();
391        current.ch_platform = Some("Linux".to_owned());
392        let (decision, signals) = decide(&current);
393        assert_eq!(signals, vec![Check::PlatformHintChanged, Check::InconsistentHints]);
394        assert_eq!(decision, Decision::Revoke);
395    }
396
397    #[test]
398    fn alternating_between_two_networks_adds_ping_pong() {
399        let now = Utc::now();
400        let mut baseline = Baseline::new(chrome_on_windows());
401        let mut elsewhere = chrome_on_windows();
402        elsewhere.ip_prefix = "198.51.100.0/24".to_owned();
403        elsewhere.asn = Some(9999);
404        baseline.absorb(&elsewhere, now, &Checks::default());
405
406        let back = chrome_on_windows();
407        let soon = assess(
408            &baseline,
409            &back,
410            now + TimeDelta::seconds(20),
411            TimeDelta::minutes(5),
412            &Checks::default(),
413        );
414        assert_eq!(soon.signals, vec![Check::IpPingPong, Check::AsnChanged]);
415        // Bouncing between two ASNs within minutes looks like two parties sharing one cookie.
416        assert_eq!(soon.decision(&Thresholds::default()), Decision::StepUp);
417
418        let later = assess(
419            &baseline,
420            &back,
421            now + TimeDelta::minutes(10),
422            TimeDelta::minutes(5),
423            &Checks::default(),
424        );
425        assert_eq!(later.signals, vec![Check::AsnChanged]);
426    }
427
428    #[test]
429    fn switching_on_a_vpn_steps_up() {
430        for anonymizer in [Anonymity::Vpn, Anonymity::HostingProvider, Anonymity::ResidentialProxy] {
431            assert_eq!(
432                decide(&via(anonymizer)),
433                (Decision::StepUp, vec![Check::AnonymizerEntered, Check::AsnChanged]),
434                "{anonymizer:?}"
435            );
436        }
437        let mut abroad = via(Anonymity::Vpn);
438        abroad.country = Some("NL".to_owned());
439        assert_eq!(
440            decide(&abroad),
441            (Decision::StepUp, vec![Check::CountryChanged, Check::AnonymizerEntered])
442        );
443    }
444
445    #[test]
446    fn tor_steps_up_and_tor_abroad_revokes() {
447        for anonymizer in [Anonymity::TorExitNode, Anonymity::PublicProxy] {
448            assert_eq!(
449                decide(&via(anonymizer)),
450                (Decision::StepUp, vec![Check::TorOrProxyEntered, Check::AsnChanged]),
451                "{anonymizer:?}"
452            );
453        }
454        let mut abroad = via(Anonymity::TorExitNode);
455        abroad.country = Some("DE".to_owned());
456        assert_eq!(
457            decide(&abroad),
458            (Decision::Revoke, vec![Check::TorOrProxyEntered, Check::CountryChanged])
459        );
460    }
461
462    #[test]
463    fn anonymity_only_scores_moves_onto_a_worse_network() {
464        let assess_from = |was: Option<Anonymity>, now: Option<Anonymity>| {
465            let mut known = via(Anonymity::Direct);
466            known.anonymity = was;
467            let mut current = chrome_on_windows();
468            current.anonymity = now;
469            assess_now(&Baseline::new(known), &current).signals
470        };
471        let vpn = Some(Anonymity::Vpn);
472        let tor = Some(Anonymity::TorExitNode);
473        let direct = Some(Anonymity::Direct);
474        assert_eq!(assess_from(vpn, direct), vec![Check::AsnChanged], "leaving a VPN");
475        assert_eq!(
476            assess_from(vpn, Some(Anonymity::HostingProvider)),
477            vec![Check::AsnChanged]
478        );
479        assert_eq!(assess_from(tor, vpn), vec![Check::AsnChanged], "Tor to VPN");
480        assert_eq!(assess_from(tor, Some(Anonymity::PublicProxy)), vec![Check::AsnChanged]);
481        assert_eq!(assess_from(vpn, tor), vec![Check::TorOrProxyEntered, Check::AsnChanged]);
482        assert_eq!(assess_from(None, tor), vec![Check::AsnChanged], "unknown baseline");
483        assert_eq!(assess_from(direct, None), vec![Check::AsnChanged], "lookup failed");
484    }
485
486    #[test]
487    fn anonymity_needs_a_network_move() {
488        let mut current = chrome_on_windows();
489        current.anonymity = Some(Anonymity::Vpn);
490        assert_eq!(decide(&current), (Decision::Allow, vec![]));
491    }
492
493    #[test]
494    fn toggling_a_vpn_back_on_does_not_revoke() {
495        let now = Utc::now();
496        let mut baseline = Baseline::new(chrome_on_windows());
497        baseline.absorb(&via(Anonymity::Vpn), now, &Checks::default());
498        baseline.absorb(&chrome_on_windows(), now + TimeDelta::seconds(10), &Checks::default());
499
500        let a = assess(
501            &baseline,
502            &via(Anonymity::Vpn),
503            now + TimeDelta::seconds(20),
504            TimeDelta::minutes(5),
505            &Checks::default(),
506        );
507        // The client was already trusted on this VPN: only the bounce counts.
508        assert_eq!(a.signals, vec![Check::IpPingPong, Check::AsnChanged]);
509        assert_eq!(a.decision(&Thresholds::default()), Decision::StepUp);
510    }
511
512    #[test]
513    fn downgrade_is_flagged() {
514        let mut current = chrome_on_windows();
515        current.browser_major = Some(120);
516        assert_eq!(decide(&current), (Decision::StepUp, vec![Check::BrowserDowngraded]));
517    }
518
519    #[test]
520    fn disabled_checks_and_custom_weights() {
521        let mut current = chrome_on_windows();
522        current.os = Some("macOS".to_owned());
523        let checks = Checks::default()
524            .disable(Check::OsChanged)
525            .weight(Check::InconsistentHints, 5);
526        let a = assess(
527            &Baseline::new(chrome_on_windows()),
528            &current,
529            Utc::now(),
530            TimeDelta::minutes(5),
531            &checks,
532        );
533        assert_eq!(a.signals, vec![Check::InconsistentHints]);
534        assert_eq!(a.score, 5);
535        let none = assess(
536            &Baseline::new(chrome_on_windows()),
537            &current,
538            Utc::now(),
539            TimeDelta::minutes(5),
540            &Checks::none(),
541        );
542        assert_eq!(none, Assessment::default());
543    }
544
545    /// Changes legitimate users make routinely, one at a time.
546    fn routine_change() -> impl Strategy<Value = (u8, u32)> {
547        (0u8..9, any::<u32>())
548    }
549
550    fn apply_routine(fp: &mut Fingerprint, kind: u8, n: u32) {
551        match kind {
552            0 => fp.ip_prefix = format!("198.51.{}.0/24", n % 256),
553            1 => {
554                fp.ip_prefix = format!("100.64.{}.0/24", n % 256);
555                fp.asn = Some(n);
556            }
557            2 => {
558                fp.ip_prefix = format!("192.0.{}.0/24", n % 256);
559                fp.country = Some(["FR", "DE", "US", "JP"][(n % 4) as usize].to_owned());
560                fp.asn = Some(n);
561            }
562            3 => {
563                fp.browser_major = fp.browser_major.map(|m| m + 1 + n % 5);
564                fp.tls = Some(format!("tls-{n}"));
565            }
566            4 => fp.accept_language = Some(["en", "fr,en", "de-de,de"][(n % 3) as usize].to_owned()),
567            5 => fp.tls = Some(format!("tls-{n}")),
568            6 => fp.ch_mobile = fp.ch_mobile.map(|m| !m),
569            7 => {
570                fp.ip_prefix = format!("185.{}.0.0/24", n % 256);
571                fp.country = Some(["BE", "NL", "CH", "US"][(n % 4) as usize].to_owned());
572                fp.asn = Some(n);
573                fp.anonymity = Some(Anonymity::Vpn);
574            }
575            _ => fp.os = Some("Linux".to_owned()),
576        }
577    }
578
579    proptest! {
580        #[test]
581        fn no_single_routine_change_revokes(
582            (kind, n) in routine_change(),
583            android in any::<bool>(),
584            previous in any::<bool>(),
585            secs in 0i64..600,
586        ) {
587            let mut fp = chrome_on_windows();
588            if android {
589                fp.os = Some("Android".into());
590                fp.ch_platform = Some("Android".into());
591                fp.ch_mobile = Some(true);
592            }
593            if !android && kind == 8 {
594                // Linux is only a routine change for Android devices.
595                return Ok(());
596            }
597            let now = Utc::now();
598            let mut baseline = Baseline::new(fp.clone());
599            let mut current = fp.clone();
600            apply_routine(&mut current, kind, n);
601            if previous {
602                baseline.previous_ip_prefix = Some(current.ip_prefix.clone());
603                baseline.ip_changed_at = Some(now - TimeDelta::seconds(secs));
604            }
605            let a = assess(&baseline, &current, now, TimeDelta::minutes(5), &Checks::default());
606            prop_assert_ne!(a.decision(&Thresholds::default()), Decision::Revoke, "{:?}", a);
607        }
608
609        #[test]
610        fn score_is_sum_of_signal_weights(
611            os in proptest::option::of("[A-Za-z]{1,8}"),
612            browser in proptest::option::of("[A-Za-z]{1,8}"),
613            major in proptest::option::of(0u32..300),
614            platform in proptest::option::of("[A-Za-z]{1,8}"),
615            mobile in proptest::option::of(any::<bool>()),
616            lang in proptest::option::of("[a-z]{2}"),
617        ) {
618            let current = Fingerprint {
619                os, browser, browser_major: major, ch_platform: platform, ch_mobile: mobile,
620                accept_language: lang, ..chrome_on_windows()
621            };
622            let a = assess(&Baseline::new(chrome_on_windows()), &current, Utc::now(), TimeDelta::minutes(5), &Checks::default());
623            let sum: u32 = a.signals.iter().map(|c| c.default_weight()).sum();
624            prop_assert_eq!(a.score, sum);
625        }
626    }
627}