1//! Helper functionality used by the rest of `tor-guardmgr`.
23use rand::Rng;
4use std::time::{Duration, SystemTime};
5use tor_basic_utils::RngExt as _;
67/// 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 {
16let offset = rng.gen_range_infallible(..=max);
17let 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.
22round_time(random, 10)
23}
2425/// 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 {
37let (early, elapsed) = if when < SystemTime::UNIX_EPOCH {
38 (
39true,
40 SystemTime::UNIX_EPOCH
41 .duration_since(when)
42 .expect("logic_error"),
43 )
44 } else {
45 (
46false,
47 when.duration_since(SystemTime::UNIX_EPOCH)
48 .expect("logic error"),
49 )
50 };
5152let secs_elapsed = elapsed.as_secs();
53let secs_rounded = secs_elapsed - (secs_elapsed % u64::from(d));
54let dur_rounded = Duration::from_secs(secs_rounded);
5556if early {
57 SystemTime::UNIX_EPOCH - dur_rounded
58 } else {
59 SystemTime::UNIX_EPOCH + dur_rounded
60 }
61}
6263#[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 @@ -->
78use super::*;
79use tor_basic_utils::test_rng::testing_rng;
8081#[test]
82fn test_randomize_time() {
83let now = SystemTime::now();
84let one_hour = humantime::parse_duration("1hr").unwrap();
85let ten_sec = humantime::parse_duration("10s").unwrap();
86let mut rng = testing_rng();
8788for _ in 0..1000 {
89let t = randomize_time(&mut rng, now, one_hour);
90assert!(t >= now - one_hour - ten_sec);
91assert!(t <= now);
92 }
9394let close_to_epoch = humantime::parse_rfc3339("1970-01-01T00:30:00Z").unwrap();
95for _ in 0..1000 {
96let t = randomize_time(&mut rng, close_to_epoch, one_hour);
97assert!(t >= SystemTime::UNIX_EPOCH);
98assert!(t <= close_to_epoch);
99let d = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
100assert_eq!(d.subsec_nanos(), 0);
101assert_eq!(d.as_secs() % 10, 0);
102 }
103 }
104}