1
//! Helper functionality used by the rest of `tor-guardmgr`.
2

            
3
use rand::Rng;
4
use std::time::{Duration, SystemTime};
5

            
6
/// Return a random time within the range `when-max ..= when`.
7
///
8
/// Uses a uniform distribution; saturates at UNIX_EPOCH.  Rounds down to the
9
/// nearest 10 seconds.
10
///
11
/// This kind of date randomization is used in our persistent state in
12
/// an attempt to make some kinds of traffic analysis attacks a bit
13
/// harder for an attacker who can read our state after the fact.
14
3580
pub(crate) fn randomize_time<R: Rng>(rng: &mut R, when: SystemTime, max: Duration) -> SystemTime {
15
3580
    let offset = rng.gen_range(Duration::ZERO..max);
16
3580
    let random = when
17
3580
        .checked_sub(offset)
18
3580
        .unwrap_or(SystemTime::UNIX_EPOCH)
19
3580
        .max(SystemTime::UNIX_EPOCH);
20
3580
    // Round to the nearest 10-second increment.
21
3580
    round_time(random, 10)
22
3580
}
23

            
24
/// Round `when` to a multiple of `d` seconds relative to epoch.
25
///
26
/// Rounds towards the epoch.
27
///
28
/// There's no reason to actually do this, since the times we use it
29
/// on are randomized, but rounding times in this way avoids giving a
30
/// false impression that we're storing hyper-accurate numbers.
31
///
32
/// # Panics
33
///
34
/// Panics if d == 0.
35
3580
fn round_time(when: SystemTime, d: u32) -> SystemTime {
36
3580
    let (early, elapsed) = if when < SystemTime::UNIX_EPOCH {
37
        (
38
            true,
39
            SystemTime::UNIX_EPOCH
40
                .duration_since(when)
41
                .expect("logic_error"),
42
        )
43
    } else {
44
3580
        (
45
3580
            false,
46
3580
            when.duration_since(SystemTime::UNIX_EPOCH)
47
3580
                .expect("logic error"),
48
3580
        )
49
    };
50

            
51
3580
    let secs_elapsed = elapsed.as_secs();
52
3580
    let secs_rounded = secs_elapsed - (secs_elapsed % u64::from(d));
53
3580
    let dur_rounded = Duration::from_secs(secs_rounded);
54
3580

            
55
3580
    if early {
56
        SystemTime::UNIX_EPOCH - dur_rounded
57
    } else {
58
3580
        SystemTime::UNIX_EPOCH + dur_rounded
59
    }
60
3580
}
61

            
62
#[cfg(test)]
63
mod test {
64
    #![allow(clippy::unwrap_used)]
65
    use super::*;
66

            
67
    #[test]
68
    fn test_randomize_time() {
69
        let now = SystemTime::now();
70
        let one_hour = Duration::from_secs(3600);
71
        let ten_sec = Duration::from_secs(10);
72
        let mut rng = rand::thread_rng();
73

            
74
        for _ in 0..1000 {
75
            let t = randomize_time(&mut rng, now, one_hour);
76
            assert!(t >= now - one_hour - ten_sec);
77
            assert!(t <= now);
78
        }
79

            
80
        let close_to_epoch = SystemTime::UNIX_EPOCH + one_hour / 2;
81
        for _ in 0..1000 {
82
            let t = randomize_time(&mut rng, close_to_epoch, one_hour);
83
            assert!(t >= SystemTime::UNIX_EPOCH);
84
            assert!(t <= close_to_epoch);
85
            let d = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
86
            assert_eq!(d.subsec_nanos(), 0);
87
            assert_eq!(d.as_secs() % 10, 0);
88
        }
89
    }
90
}