tor_guardmgr/
util.rs

1//! Helper functionality used by the rest of `tor-guardmgr`.
2
3use rand::Rng;
4use std::time::{Duration, SystemTime};
5use tor_basic_utils::RngExt as _;
6
7/// Return a random time within the range `when-max ..= when`.
8///
9/// Uses a uniform distribution; saturates at UNIX_EPOCH.  Rounds down to the
10/// nearest 10 seconds.
11///
12/// This kind of date randomization is used in our persistent state in
13/// an attempt to make some kinds of traffic analysis attacks a bit
14/// harder for an attacker who can read our state after the fact.
15pub(crate) fn randomize_time<R: Rng>(rng: &mut R, when: SystemTime, max: Duration) -> SystemTime {
16    let offset = rng.gen_range_infallible(..=max);
17    let random = when
18        .checked_sub(offset)
19        .unwrap_or(SystemTime::UNIX_EPOCH)
20        .max(SystemTime::UNIX_EPOCH);
21    // Round to the nearest 10-second increment.
22    round_time(random, 10)
23}
24
25/// Round `when` to a multiple of `d` seconds relative to epoch.
26///
27/// Rounds towards the epoch.
28///
29/// There's no reason to actually do this, since the times we use it
30/// on are randomized, but rounding times in this way avoids giving a
31/// false impression that we're storing hyper-accurate numbers.
32///
33/// # Panics
34///
35/// Panics if d == 0.
36fn round_time(when: SystemTime, d: u32) -> SystemTime {
37    let (early, elapsed) = if when < SystemTime::UNIX_EPOCH {
38        (
39            true,
40            SystemTime::UNIX_EPOCH
41                .duration_since(when)
42                .expect("logic_error"),
43        )
44    } else {
45        (
46            false,
47            when.duration_since(SystemTime::UNIX_EPOCH)
48                .expect("logic error"),
49        )
50    };
51
52    let secs_elapsed = elapsed.as_secs();
53    let secs_rounded = secs_elapsed - (secs_elapsed % u64::from(d));
54    let dur_rounded = Duration::from_secs(secs_rounded);
55
56    if early {
57        SystemTime::UNIX_EPOCH - dur_rounded
58    } else {
59        SystemTime::UNIX_EPOCH + dur_rounded
60    }
61}
62
63#[cfg(test)]
64mod test {
65    // @@ begin test lint list maintained by maint/add_warning @@
66    #![allow(clippy::bool_assert_comparison)]
67    #![allow(clippy::clone_on_copy)]
68    #![allow(clippy::dbg_macro)]
69    #![allow(clippy::mixed_attributes_style)]
70    #![allow(clippy::print_stderr)]
71    #![allow(clippy::print_stdout)]
72    #![allow(clippy::single_char_pattern)]
73    #![allow(clippy::unwrap_used)]
74    #![allow(clippy::unchecked_duration_subtraction)]
75    #![allow(clippy::useless_vec)]
76    #![allow(clippy::needless_pass_by_value)]
77    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
78    use super::*;
79    use tor_basic_utils::test_rng::testing_rng;
80
81    #[test]
82    fn test_randomize_time() {
83        let now = SystemTime::now();
84        let one_hour = humantime::parse_duration("1hr").unwrap();
85        let ten_sec = humantime::parse_duration("10s").unwrap();
86        let mut rng = testing_rng();
87
88        for _ in 0..1000 {
89            let t = randomize_time(&mut rng, now, one_hour);
90            assert!(t >= now - one_hour - ten_sec);
91            assert!(t <= now);
92        }
93
94        let close_to_epoch = humantime::parse_rfc3339("1970-01-01T00:30:00Z").unwrap();
95        for _ in 0..1000 {
96            let t = randomize_time(&mut rng, close_to_epoch, one_hour);
97            assert!(t >= SystemTime::UNIX_EPOCH);
98            assert!(t <= close_to_epoch);
99            let d = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
100            assert_eq!(d.subsec_nanos(), 0);
101            assert_eq!(d.as_secs() % 10, 0);
102        }
103    }
104}