1
//! Define helpers for working with types in constant time.
2

            
3
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
4
use zeroize::Zeroize;
5

            
6
#[cfg(feature = "memquota-memcost")]
7
use {derive_deftly::Deftly, tor_memquota::derive_deftly_template_HasMemoryCost};
8

            
9
/// A byte array of length N for which comparisons are performed in constant
10
/// time.
11
///
12
/// # Limitations
13
///
14
/// It is possible to avoid constant time comparisons here, just by using the
15
/// `as_ref()` and `as_mut()` methods.  They should therefore be approached with
16
/// some caution.
17
///
18
/// (The decision to avoid implementing `Deref`/`DerefMut` is deliberate.)
19
#[allow(clippy::derived_hash_with_manual_eq)]
20
#[derive(Clone, Copy, Debug, Hash, Zeroize, derive_more::Deref)]
21
#[cfg_attr(
22
    feature = "memquota-memcost",
23
    derive(Deftly),
24
    derive_deftly(HasMemoryCost)
25
)]
26
pub struct CtByteArray<const N: usize>([u8; N]);
27

            
28
impl<const N: usize> ConstantTimeEq for CtByteArray<N> {
29
272890992
    fn ct_eq(&self, other: &Self) -> Choice {
30
272890992
        self.0.ct_eq(&other.0)
31
272890992
    }
32
}
33

            
34
impl<const N: usize> PartialEq for CtByteArray<N> {
35
208970938
    fn eq(&self, other: &Self) -> bool {
36
208970938
        self.ct_eq(other).into()
37
208970938
    }
38
}
39
impl<const N: usize> Eq for CtByteArray<N> {}
40

            
41
impl<const N: usize> From<[u8; N]> for CtByteArray<N> {
42
5874792
    fn from(value: [u8; N]) -> Self {
43
5874792
        Self(value)
44
5874792
    }
45
}
46

            
47
impl<const N: usize> From<CtByteArray<N>> for [u8; N] {
48
13542
    fn from(value: CtByteArray<N>) -> Self {
49
13542
        value.0
50
13542
    }
51
}
52

            
53
impl<const N: usize> Ord for CtByteArray<N> {
54
2468900
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
55
2468900
        // At every point, this value will be set to:
56
2468900
        //       0 if a[i]==b[i] for all i considered so far.
57
2468900
        //       a[i] - b[i] for the lowest i that has a nonzero a[i] - b[i].
58
2468900
        let mut first_nonzero_difference = 0_i16;
59

            
60
54915220
        for (a, b) in self.0.iter().zip(other.0.iter()) {
61
54915220
            let difference = i16::from(*a) - i16::from(*b);
62
54915220

            
63
54915220
            // If it's already set to a nonzero value, this conditional
64
54915220
            // assignment does nothing. Otherwise, it sets it to `difference`.
65
54915220
            //
66
54915220
            // The use of conditional_assign and ct_eq ensures that the compiler
67
54915220
            // won't short-circuit our logic here and end the loop (or stop
68
54915220
            // computing differences) on the first nonzero difference.
69
54915220
            first_nonzero_difference
70
54915220
                .conditional_assign(&difference, first_nonzero_difference.ct_eq(&0));
71
54915220
        }
72

            
73
        // This comparison with zero is not itself constant-time, but that's
74
        // okay: we only want our Ord function not to leak the array values.
75
2468900
        first_nonzero_difference.cmp(&0)
76
2468900
    }
77
}
78

            
79
impl<const N: usize> PartialOrd for CtByteArray<N> {
80
2063824
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
81
2063824
        Some(self.cmp(other))
82
2063824
    }
83
}
84

            
85
impl<const N: usize> AsRef<[u8; N]> for CtByteArray<N> {
86
1289722
    fn as_ref(&self) -> &[u8; N] {
87
1289722
        &self.0
88
1289722
    }
89
}
90

            
91
impl<const N: usize> AsMut<[u8; N]> for CtByteArray<N> {
92
23201
    fn as_mut(&mut self) -> &mut [u8; N] {
93
23201
        &mut self.0
94
23201
    }
95
}
96

            
97
/// Try to find an item in a slice without leaking where and whether the
98
/// item was found.
99
///
100
/// If there is any item `x` in the `array` for which `matches(x)`
101
/// is true, this function will return a reference to one such
102
/// item.  (We don't specify which.)
103
///
104
/// Otherwise, this function returns none.
105
///
106
/// We evaluate `matches` on every item of the array, and try not to
107
/// leak by timing which element (if any) matched.  Note that if
108
/// `matches` itself has side channels, this function can't hide them.
109
///
110
/// Note that this doesn't necessarily do a constant-time comparison,
111
/// and that it is not constant-time for the found/not-found case.
112
162
pub fn ct_lookup<T, F>(array: &[T], matches: F) -> Option<&T>
113
162
where
114
162
    F: Fn(&T) -> Choice,
115
162
{
116
162
    // ConditionallySelectable isn't implemented for usize, so we need
117
162
    // to use u64.
118
162
    let mut idx: u64 = 0;
119
162
    let mut found: Choice = 0.into();
120

            
121
1626
    for (i, x) in array.iter().enumerate() {
122
1626
        let equal = matches(x);
123
1626
        idx.conditional_assign(&(i as u64), equal);
124
1626
        found.conditional_assign(&equal, equal);
125
1626
    }
126

            
127
162
    if found.into() {
128
158
        Some(&array[idx as usize])
129
    } else {
130
4
        None
131
    }
132
162
}
133

            
134
#[cfg(test)]
135
mod test {
136
    // @@ begin test lint list maintained by maint/add_warning @@
137
    #![allow(clippy::bool_assert_comparison)]
138
    #![allow(clippy::clone_on_copy)]
139
    #![allow(clippy::dbg_macro)]
140
    #![allow(clippy::mixed_attributes_style)]
141
    #![allow(clippy::print_stderr)]
142
    #![allow(clippy::print_stdout)]
143
    #![allow(clippy::single_char_pattern)]
144
    #![allow(clippy::unwrap_used)]
145
    #![allow(clippy::unchecked_duration_subtraction)]
146
    #![allow(clippy::useless_vec)]
147
    #![allow(clippy::needless_pass_by_value)]
148
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
149

            
150
    use super::*;
151
    use rand::Rng;
152
    use tor_basic_utils::test_rng;
153

            
154
    #[allow(clippy::nonminimal_bool)]
155
    #[test]
156
    fn test_comparisons() {
157
        let num = 200;
158
        let mut rng = test_rng::testing_rng();
159

            
160
        let mut array: Vec<CtByteArray<32>> =
161
            (0..num).map(|_| rng.random::<[u8; 32]>().into()).collect();
162
        array.sort();
163

            
164
        for i in 0..num {
165
            assert_eq!(array[i], array[i]);
166
            assert!(!(array[i] < array[i]));
167
            assert!(!(array[i] > array[i]));
168

            
169
            for j in (i + 1)..num {
170
                // Note that this test will behave incorrectly if the rng
171
                // generates the same 256 value twice, but that's ridiculously
172
                // implausible.
173
                assert!(array[i] < array[j]);
174
                assert_ne!(array[i], array[j]);
175
                assert!(array[j] > array[i]);
176
                assert_eq!(
177
                    array[i].cmp(&array[j]),
178
                    array[j].as_ref().cmp(array[i].as_ref()).reverse()
179
                );
180
            }
181
        }
182
    }
183

            
184
    #[test]
185
    fn test_lookup() {
186
        use super::ct_lookup as lookup;
187
        use subtle::ConstantTimeEq;
188
        let items = vec![
189
            "One".to_string(),
190
            "word".to_string(),
191
            "of".to_string(),
192
            "every".to_string(),
193
            "length".to_string(),
194
        ];
195
        let of_word = lookup(&items[..], |i| i.len().ct_eq(&2));
196
        let every_word = lookup(&items[..], |i| i.len().ct_eq(&5));
197
        let no_word = lookup(&items[..], |i| i.len().ct_eq(&99));
198
        assert_eq!(of_word.unwrap(), "of");
199
        assert_eq!(every_word.unwrap(), "every");
200
        assert_eq!(no_word, None);
201
    }
202
}