Skip to main content

session_guard/
risk.rs

1//! Scores the current request against a session's baseline.
2
3use time::OffsetDateTime;
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: OffsetDateTime,
49    ping_pong_window: time::Duration,
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.ip_changed_at.is_some_and(|at| now - at <= ping_pong_window);
126        if returned && recent {
127            fired.push(Check::IpPingPong);
128        }
129
130        // Returning to the previous network is no news: the client was trusted there.
131        if !returned
132            && let (Some(was), Some(now)) = (known.anonymity, current.anonymity)
133            && let Some(check) = anonymity_change(was, now)
134        {
135            fired.push(check);
136        }
137    }
138
139    let version_changed = matches!((known.browser_major, current.browser_major), (Some(a), Some(b)) if a != b);
140    if !version_changed && differs(known.tls.as_ref(), current.tls.as_ref()) {
141        fired.push(Check::TlsChanged);
142    }
143
144    let language_dropped = current.accept_language.is_none();
145    if differs(known.accept_language.as_ref(), current.accept_language.as_ref()) && !(same_client && language_dropped) {
146        fired.push(Check::AcceptLanguageChanged);
147    }
148
149    let mut signals = Vec::with_capacity(fired.len());
150    let mut score = 0u32;
151    for check in Check::ALL {
152        if fired.contains(&check)
153            && let Some(weight) = checks.weight_of(check)
154        {
155            signals.push(check);
156            score = score.saturating_add(weight);
157        }
158    }
159    Assessment { score, signals }
160}
161
162/// Known and now different, or known and now missing.
163fn differs<T: PartialEq>(known: Option<&T>, current: Option<&T>) -> bool {
164    match (known, current) {
165        (Some(a), Some(b)) => a != b,
166        (Some(_), None) => true,
167        (None, _) => false,
168    }
169}
170
171fn lost<T>(known: Option<&T>, current: Option<&T>) -> bool {
172    known.is_some() && current.is_none()
173}
174
175#[cfg(test)]
176mod tests {
177    use proptest::prelude::*;
178
179    use super::*;
180    use crate::intel::Anonymity;
181
182    fn chrome_on_windows() -> Fingerprint {
183        Fingerprint {
184            ip_prefix: "203.0.113.0/24".to_owned(),
185            country: Some("BE".to_owned()),
186            asn: Some(5432),
187            browser: Some("Chrome".to_owned()),
188            browser_major: Some(141),
189            os: Some("Windows".to_owned()),
190            ch_platform: Some("Windows".to_owned()),
191            ch_mobile: Some(false),
192            accept_language: Some("nl-be,nl,en".to_owned()),
193            tls: Some("t13d1516h2_8daaf6152771_02713d6af862".to_owned()),
194            anonymity: Some(Anonymity::Direct),
195        }
196    }
197
198    fn via(anonymity: Anonymity) -> Fingerprint {
199        let mut fp = chrome_on_windows();
200        fp.ip_prefix = "198.51.100.0/24".to_owned();
201        fp.asn = Some(9009);
202        fp.anonymity = Some(anonymity);
203        fp
204    }
205
206    fn assess_now(baseline: &Baseline, current: &Fingerprint) -> Assessment {
207        assess(
208            baseline,
209            current,
210            OffsetDateTime::now_utc(),
211            time::Duration::minutes(5),
212            &Checks::default(),
213        )
214    }
215
216    fn decide(current: &Fingerprint) -> (Decision, Vec<Check>) {
217        let a = assess_now(&Baseline::new(chrome_on_windows()), current);
218        (a.decision(&Thresholds::default()), a.signals)
219    }
220
221    #[test]
222    fn added_signals_keep_check_order_and_respect_weights() {
223        let mut current = chrome_on_windows();
224        current.ip_prefix = "198.51.100.0/24".to_owned();
225        current.asn = Some(6848);
226        current.accept_language = Some("en".to_owned());
227        let mut a = assess_now(&Baseline::new(chrome_on_windows()), &current);
228        a.add(Check::OrphanedToken, &Checks::default());
229        assert_eq!(
230            a.signals,
231            vec![Check::OrphanedToken, Check::AsnChanged, Check::AcceptLanguageChanged]
232        );
233        assert_eq!(a.score, 25 + 20 + 15);
234
235        let mut a = Assessment::default();
236        a.add(Check::OrphanedToken, &Checks::none());
237        assert_eq!(a, Assessment::default());
238    }
239
240    #[test]
241    fn identical_request_is_allowed() {
242        assert_eq!(decide(&chrome_on_windows()), (Decision::Allow, vec![]));
243    }
244
245    // Legitimate users: none of these may step up or revoke.
246
247    #[test]
248    fn network_switch_within_same_provider_is_allowed() {
249        let mut current = chrome_on_windows();
250        current.ip_prefix = "203.0.200.0/24".to_owned();
251        assert_eq!(decide(&current), (Decision::Allow, vec![Check::IpPrefixChanged]));
252    }
253
254    #[test]
255    fn wifi_to_mobile_data_is_allowed() {
256        let mut current = chrome_on_windows();
257        current.ip_prefix = "198.51.100.0/24".to_owned();
258        current.asn = Some(6848);
259        assert_eq!(decide(&current), (Decision::Allow, vec![Check::AsnChanged]));
260    }
261
262    #[test]
263    fn browser_update_is_allowed_even_though_tls_changes() {
264        let mut current = chrome_on_windows();
265        current.browser_major = Some(142);
266        current.tls = Some("t13d1517h2_8daaf6152771_b0da82dd1658".to_owned());
267        assert_eq!(decide(&current), (Decision::Allow, vec![]));
268    }
269
270    #[test]
271    fn language_tweak_is_allowed() {
272        let mut current = chrome_on_windows();
273        current.accept_language = Some("en".to_owned());
274        assert_eq!(decide(&current).0, Decision::Allow);
275    }
276
277    #[test]
278    fn android_desktop_mode_toggle_steps_up_not_revokes() {
279        let mut fp = chrome_on_windows();
280        fp.os = Some("Android".to_owned());
281        fp.ch_platform = Some("Android".to_owned());
282        fp.ch_mobile = Some(true);
283        let mut current = fp.clone();
284        current.os = Some("Linux".to_owned());
285        current.ch_mobile = Some(false);
286        let a = assess_now(&Baseline::new(fp), &current);
287        assert_eq!(a.signals, vec![Check::MobileHintChanged]);
288        assert_eq!(a.decision(&Thresholds::default()), Decision::StepUp);
289    }
290
291    #[test]
292    fn travel_abroad_steps_up_not_revokes() {
293        let mut current = chrome_on_windows();
294        current.ip_prefix = "192.0.2.0/24".to_owned();
295        current.country = Some("FR".to_owned());
296        current.asn = Some(3215);
297        assert_eq!(decide(&current), (Decision::StepUp, vec![Check::CountryChanged]));
298    }
299
300    #[test]
301    fn baseline_without_hints_ignores_hints() {
302        let mut firefox = chrome_on_windows();
303        firefox.browser = Some("Firefox".to_owned());
304        firefox.ch_platform = None;
305        firefox.ch_mobile = None;
306        let a = assess_now(&Baseline::new(firefox.clone()), &firefox);
307        assert_eq!(a.score, 0);
308    }
309
310    // Theft.
311
312    #[test]
313    fn different_operating_system_is_revoked() {
314        let mut current = chrome_on_windows();
315        current.os = Some("macOS".to_owned());
316        current.ch_platform = Some("macOS".to_owned());
317        assert_eq!(decide(&current).0, Decision::Revoke);
318    }
319
320    #[test]
321    fn different_browser_is_revoked() {
322        let mut current = chrome_on_windows();
323        current.browser = Some("Firefox".to_owned());
324        current.ch_platform = None;
325        current.ch_mobile = None;
326        assert_eq!(decide(&current).0, Decision::Revoke);
327    }
328
329    #[test]
330    fn empty_user_agent_cannot_bypass_checks() {
331        let mut current = chrome_on_windows();
332        current.browser = None;
333        current.browser_major = None;
334        current.os = None;
335        current.ch_platform = None;
336        current.ch_mobile = None;
337        let (decision, signals) = decide(&current);
338        assert!(signals.contains(&Check::UserAgentMissing));
339        assert!(signals.contains(&Check::ClientHintsMissing));
340        assert_eq!(decision, Decision::Revoke);
341    }
342
343    #[test]
344    fn dropping_only_the_mobile_hint_is_noticed() {
345        let mut current = chrome_on_windows();
346        current.ip_prefix = "198.51.100.0/24".to_owned();
347        current.ch_mobile = None;
348        assert_eq!(
349            decide(&current).1,
350            vec![Check::ClientHintsMissing, Check::IpPrefixChanged]
351        );
352    }
353
354    #[test]
355    fn missing_soft_headers_on_the_same_network_are_not_scored() {
356        let mut current = chrome_on_windows();
357        current.ch_platform = None;
358        current.ch_mobile = None;
359        current.accept_language = None;
360        assert_eq!(decide(&current).1, Vec::<Check>::new());
361    }
362
363    #[test]
364    fn stripping_soft_headers_never_lowers_the_score() {
365        let mut current = chrome_on_windows();
366        current.ip_prefix = "198.51.100.0/24".to_owned();
367        current.accept_language = None;
368        current.tls = None;
369        assert_eq!(
370            decide(&current).1,
371            vec![Check::TlsChanged, Check::AcceptLanguageChanged, Check::IpPrefixChanged]
372        );
373
374        let mut current = chrome_on_windows();
375        current.ip_prefix = "198.51.100.0/24".to_owned();
376        current.country = None;
377        assert_eq!(decide(&current).1, vec![Check::CountryChanged]);
378    }
379
380    #[test]
381    fn copied_user_agent_from_script_in_same_country_is_revoked() {
382        let mut current = chrome_on_windows();
383        current.ip_prefix = "198.51.100.0/24".to_owned();
384        current.asn = Some(9999);
385        current.ch_platform = None;
386        current.ch_mobile = None;
387        current.tls = Some("t13d311200_e8f1e7e78f70_d41ae481755e".to_owned());
388        current.accept_language = None;
389        assert_eq!(decide(&current).0, Decision::Revoke);
390    }
391
392    #[test]
393    fn spoofed_ua_contradicting_client_hints_is_flagged() {
394        let mut current = chrome_on_windows();
395        current.ch_platform = Some("Linux".to_owned());
396        let (decision, signals) = decide(&current);
397        assert_eq!(signals, vec![Check::PlatformHintChanged, Check::InconsistentHints]);
398        assert_eq!(decision, Decision::Revoke);
399    }
400
401    #[test]
402    fn alternating_between_two_networks_adds_ping_pong() {
403        let now = OffsetDateTime::now_utc();
404        let mut baseline = Baseline::new(chrome_on_windows());
405        let mut elsewhere = chrome_on_windows();
406        elsewhere.ip_prefix = "198.51.100.0/24".to_owned();
407        elsewhere.asn = Some(9999);
408        baseline.absorb(&elsewhere, now, &Checks::default());
409
410        let back = chrome_on_windows();
411        let soon = assess(
412            &baseline,
413            &back,
414            now + time::Duration::seconds(20),
415            time::Duration::minutes(5),
416            &Checks::default(),
417        );
418        assert_eq!(soon.signals, vec![Check::IpPingPong, Check::AsnChanged]);
419        // Bouncing between two ASNs within minutes looks like two parties sharing one cookie.
420        assert_eq!(soon.decision(&Thresholds::default()), Decision::StepUp);
421
422        let later = assess(
423            &baseline,
424            &back,
425            now + time::Duration::minutes(10),
426            time::Duration::minutes(5),
427            &Checks::default(),
428        );
429        assert_eq!(later.signals, vec![Check::AsnChanged]);
430    }
431
432    #[test]
433    fn switching_on_a_vpn_steps_up() {
434        for anonymizer in [Anonymity::Vpn, Anonymity::HostingProvider, Anonymity::ResidentialProxy] {
435            assert_eq!(
436                decide(&via(anonymizer)),
437                (Decision::StepUp, vec![Check::AnonymizerEntered, Check::AsnChanged]),
438                "{anonymizer:?}"
439            );
440        }
441        let mut abroad = via(Anonymity::Vpn);
442        abroad.country = Some("NL".to_owned());
443        assert_eq!(
444            decide(&abroad),
445            (Decision::StepUp, vec![Check::CountryChanged, Check::AnonymizerEntered])
446        );
447    }
448
449    #[test]
450    fn tor_steps_up_and_tor_abroad_revokes() {
451        for anonymizer in [Anonymity::TorExitNode, Anonymity::PublicProxy] {
452            assert_eq!(
453                decide(&via(anonymizer)),
454                (Decision::StepUp, vec![Check::TorOrProxyEntered, Check::AsnChanged]),
455                "{anonymizer:?}"
456            );
457        }
458        let mut abroad = via(Anonymity::TorExitNode);
459        abroad.country = Some("DE".to_owned());
460        assert_eq!(
461            decide(&abroad),
462            (Decision::Revoke, vec![Check::TorOrProxyEntered, Check::CountryChanged])
463        );
464    }
465
466    #[test]
467    fn anonymity_only_scores_moves_onto_a_worse_network() {
468        let assess_from = |was: Option<Anonymity>, now: Option<Anonymity>| {
469            let mut known = via(Anonymity::Direct);
470            known.anonymity = was;
471            let mut current = chrome_on_windows();
472            current.anonymity = now;
473            assess_now(&Baseline::new(known), &current).signals
474        };
475        let vpn = Some(Anonymity::Vpn);
476        let tor = Some(Anonymity::TorExitNode);
477        let direct = Some(Anonymity::Direct);
478        assert_eq!(assess_from(vpn, direct), vec![Check::AsnChanged], "leaving a VPN");
479        assert_eq!(
480            assess_from(vpn, Some(Anonymity::HostingProvider)),
481            vec![Check::AsnChanged]
482        );
483        assert_eq!(assess_from(tor, vpn), vec![Check::AsnChanged], "Tor to VPN");
484        assert_eq!(assess_from(tor, Some(Anonymity::PublicProxy)), vec![Check::AsnChanged]);
485        assert_eq!(assess_from(vpn, tor), vec![Check::TorOrProxyEntered, Check::AsnChanged]);
486        assert_eq!(assess_from(None, tor), vec![Check::AsnChanged], "unknown baseline");
487        assert_eq!(assess_from(direct, None), vec![Check::AsnChanged], "lookup failed");
488    }
489
490    #[test]
491    fn anonymity_needs_a_network_move() {
492        let mut current = chrome_on_windows();
493        current.anonymity = Some(Anonymity::Vpn);
494        assert_eq!(decide(&current), (Decision::Allow, vec![]));
495    }
496
497    #[test]
498    fn toggling_a_vpn_back_on_does_not_revoke() {
499        let now = OffsetDateTime::now_utc();
500        let mut baseline = Baseline::new(chrome_on_windows());
501        baseline.absorb(&via(Anonymity::Vpn), now, &Checks::default());
502        baseline.absorb(
503            &chrome_on_windows(),
504            now + time::Duration::seconds(10),
505            &Checks::default(),
506        );
507
508        let a = assess(
509            &baseline,
510            &via(Anonymity::Vpn),
511            now + time::Duration::seconds(20),
512            time::Duration::minutes(5),
513            &Checks::default(),
514        );
515        // The client was already trusted on this VPN: only the bounce counts.
516        assert_eq!(a.signals, vec![Check::IpPingPong, Check::AsnChanged]);
517        assert_eq!(a.decision(&Thresholds::default()), Decision::StepUp);
518    }
519
520    #[test]
521    fn downgrade_is_flagged() {
522        let mut current = chrome_on_windows();
523        current.browser_major = Some(120);
524        assert_eq!(decide(&current), (Decision::StepUp, vec![Check::BrowserDowngraded]));
525    }
526
527    #[test]
528    fn disabled_checks_and_custom_weights() {
529        let mut current = chrome_on_windows();
530        current.os = Some("macOS".to_owned());
531        let checks = Checks::default()
532            .disable(Check::OsChanged)
533            .weight(Check::InconsistentHints, 5);
534        let a = assess(
535            &Baseline::new(chrome_on_windows()),
536            &current,
537            OffsetDateTime::now_utc(),
538            time::Duration::minutes(5),
539            &checks,
540        );
541        assert_eq!(a.signals, vec![Check::InconsistentHints]);
542        assert_eq!(a.score, 5);
543        let none = assess(
544            &Baseline::new(chrome_on_windows()),
545            &current,
546            OffsetDateTime::now_utc(),
547            time::Duration::minutes(5),
548            &Checks::none(),
549        );
550        assert_eq!(none, Assessment::default());
551    }
552
553    /// Changes legitimate users make routinely, one at a time.
554    fn routine_change() -> impl Strategy<Value = (u8, u32)> {
555        (0u8..9, any::<u32>())
556    }
557
558    fn apply_routine(fp: &mut Fingerprint, kind: u8, n: u32) {
559        match kind {
560            0 => fp.ip_prefix = format!("198.51.{}.0/24", n % 256),
561            1 => {
562                fp.ip_prefix = format!("100.64.{}.0/24", n % 256);
563                fp.asn = Some(n);
564            }
565            2 => {
566                fp.ip_prefix = format!("192.0.{}.0/24", n % 256);
567                fp.country = Some(["FR", "DE", "US", "JP"][(n % 4) as usize].to_owned());
568                fp.asn = Some(n);
569            }
570            3 => {
571                fp.browser_major = fp.browser_major.map(|m| m + 1 + n % 5);
572                fp.tls = Some(format!("tls-{n}"));
573            }
574            4 => fp.accept_language = Some(["en", "fr,en", "de-de,de"][(n % 3) as usize].to_owned()),
575            5 => fp.tls = Some(format!("tls-{n}")),
576            6 => fp.ch_mobile = fp.ch_mobile.map(|m| !m),
577            7 => {
578                fp.ip_prefix = format!("185.{}.0.0/24", n % 256);
579                fp.country = Some(["BE", "NL", "CH", "US"][(n % 4) as usize].to_owned());
580                fp.asn = Some(n);
581                fp.anonymity = Some(Anonymity::Vpn);
582            }
583            _ => fp.os = Some("Linux".to_owned()),
584        }
585    }
586
587    proptest! {
588        #[test]
589        fn no_single_routine_change_revokes(
590            (kind, n) in routine_change(),
591            android in any::<bool>(),
592            previous in any::<bool>(),
593            secs in 0i64..600,
594        ) {
595            let mut fp = chrome_on_windows();
596            if android {
597                fp.os = Some("Android".into());
598                fp.ch_platform = Some("Android".into());
599                fp.ch_mobile = Some(true);
600            }
601            if !android && kind == 8 {
602                // Linux is only a routine change for Android devices.
603                return Ok(());
604            }
605            let now = OffsetDateTime::now_utc();
606            let mut baseline = Baseline::new(fp.clone());
607            let mut current = fp.clone();
608            apply_routine(&mut current, kind, n);
609            if previous {
610                baseline.previous_ip_prefix = Some(current.ip_prefix.clone());
611                baseline.ip_changed_at = Some(now - time::Duration::seconds(secs));
612            }
613            let a = assess(&baseline, &current, now, time::Duration::minutes(5), &Checks::default());
614            prop_assert_ne!(a.decision(&Thresholds::default()), Decision::Revoke, "{:?}", a);
615        }
616
617        #[test]
618        fn score_is_sum_of_signal_weights(
619            os in proptest::option::of("[A-Za-z]{1,8}"),
620            browser in proptest::option::of("[A-Za-z]{1,8}"),
621            major in proptest::option::of(0u32..300),
622            platform in proptest::option::of("[A-Za-z]{1,8}"),
623            mobile in proptest::option::of(any::<bool>()),
624            lang in proptest::option::of("[a-z]{2}"),
625        ) {
626            let current = Fingerprint {
627                os, browser, browser_major: major, ch_platform: platform, ch_mobile: mobile,
628                accept_language: lang, ..chrome_on_windows()
629            };
630            let a = assess(&Baseline::new(chrome_on_windows()), &current, OffsetDateTime::now_utc(), time::Duration::minutes(5), &Checks::default());
631            let sum: u32 = a.signals.iter().map(|c| c.default_weight()).sum();
632            prop_assert_eq!(a.score, sum);
633        }
634    }
635}