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

            
3
use derive_deftly::{Deftly, define_derive_deftly};
4
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
5
use zeroize::Zeroize;
6

            
7
#[cfg(feature = "memquota-memcost")]
8
use tor_memquota_cost::derive_deftly_template_HasMemoryCost;
9

            
10
define_derive_deftly! {
11
    /// Derives [`subtle::ConstantTimeEq`] on structs for which all fields
12
    /// already implement it. Note that this does NOT work on fields which are
13
    /// arrays of type `T`, even if `T` implements [`subtle::ConstantTimeEq`].
14
    /// Arrays do not directly implement [`subtle::ConstantTimeEq`] and instead
15
    /// dereference to a slice, `[T]`, which does. See subtle!114 for a possible
16
    /// future resolution.
17
    export ConstantTimeEq for struct:
18

            
19
    impl<$tgens> ConstantTimeEq for $ttype
20
    where $twheres
21
          $( $ftype : ConstantTimeEq , )
22
    {
23
1514
        fn ct_eq(&self, other: &Self) -> subtle::Choice {
24
            match (self, other) {
25
                $(
26
                    (${vpat fprefix=self_}, ${vpat fprefix=other_}) => {
27
                        $(
28
                            $<self_ $fname>.ct_eq($<other_ $fname>) &
29
                        )
30
                        subtle::Choice::from(1)
31
                    },
32
                )
33
            }
34
        }
35
    }
36
}
37
define_derive_deftly! {
38
    /// Derives [`core::cmp::PartialEq`] on types which implement
39
    /// [`subtle::ConstantTimeEq`] by calling [`subtle::ConstantTimeEq::ct_eq`].
40
    export PartialEqFromCtEq:
41

            
42
    impl<$tgens> PartialEq for $ttype
43
    where $twheres
44
          $ttype : ConstantTimeEq
45
    {
46
38458
        fn eq(&self, other: &Self) -> bool {
47
            self.ct_eq(other).into()
48
        }
49
    }
50
}
51
pub(crate) use {derive_deftly_template_ConstantTimeEq, derive_deftly_template_PartialEqFromCtEq};
52

            
53
/// A byte array of length N for which comparisons are performed in constant
54
/// time.
55
///
56
/// # Limitations
57
///
58
/// It is possible to avoid constant time comparisons here, just by using the
59
/// `as_ref()` and `as_mut()` methods.  They should therefore be approached with
60
/// some caution.
61
///
62
/// (The decision to avoid implementing `Deref`/`DerefMut` is deliberate.)
63
#[allow(clippy::derived_hash_with_manual_eq)]
64
#[derive(Clone, Copy, Debug, Hash, Zeroize)]
65
#[cfg_attr(
66
    feature = "memquota-memcost",
67
    derive(Deftly),
68
    derive_deftly(HasMemoryCost)
69
)]
70
pub struct CtByteArray<const N: usize>([u8; N]);
71

            
72
impl<const N: usize> ConstantTimeEq for CtByteArray<N> {
73
431314410
    fn ct_eq(&self, other: &Self) -> Choice {
74
431314410
        self.0.ct_eq(&other.0)
75
431314410
    }
76
}
77

            
78
impl<const N: usize> PartialEq for CtByteArray<N> {
79
292678527
    fn eq(&self, other: &Self) -> bool {
80
292678527
        self.ct_eq(other).into()
81
292678527
    }
82
}
83
impl<const N: usize> Eq for CtByteArray<N> {}
84

            
85
impl<const N: usize> From<[u8; N]> for CtByteArray<N> {
86
10747560
    fn from(value: [u8; N]) -> Self {
87
10747560
        Self(value)
88
10747560
    }
89
}
90

            
91
impl<const N: usize> From<CtByteArray<N>> for [u8; N] {
92
17512
    fn from(value: CtByteArray<N>) -> Self {
93
17512
        value.0
94
17512
    }
95
}
96

            
97
impl<const N: usize> Ord for CtByteArray<N> {
98
3227086
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
99
        // At every point, this value will be set to:
100
        //       0 if a[i]==b[i] for all i considered so far.
101
        //       a[i] - b[i] for the lowest i that has a nonzero a[i] - b[i].
102
3227086
        let mut first_nonzero_difference = 0_i16;
103

            
104
76838072
        for (a, b) in self.0.iter().zip(other.0.iter()) {
105
76838072
            let difference = i16::from(*a) - i16::from(*b);
106
76838072

            
107
76838072
            // If it's already set to a nonzero value, this conditional
108
76838072
            // assignment does nothing. Otherwise, it sets it to `difference`.
109
76838072
            //
110
76838072
            // The use of conditional_assign and ct_eq ensures that the compiler
111
76838072
            // won't short-circuit our logic here and end the loop (or stop
112
76838072
            // computing differences) on the first nonzero difference.
113
76838072
            first_nonzero_difference
114
76838072
                .conditional_assign(&difference, first_nonzero_difference.ct_eq(&0));
115
76838072
        }
116

            
117
        // This comparison with zero is not itself constant-time, but that's
118
        // okay: we only want our Ord function not to leak the array values.
119
3227086
        first_nonzero_difference.cmp(&0)
120
3227086
    }
121
}
122

            
123
impl<const N: usize> PartialOrd for CtByteArray<N> {
124
2247774
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
125
2247774
        Some(self.cmp(other))
126
2247774
    }
127
}
128

            
129
impl<const N: usize> AsRef<[u8; N]> for CtByteArray<N> {
130
1673086
    fn as_ref(&self) -> &[u8; N] {
131
1673086
        &self.0
132
1673086
    }
133
}
134

            
135
impl<const N: usize> AsMut<[u8; N]> for CtByteArray<N> {
136
24161
    fn as_mut(&mut self) -> &mut [u8; N] {
137
24161
        &mut self.0
138
24161
    }
139
}
140

            
141
/// Try to find an item in a slice without leaking where and whether the
142
/// item was found.
143
///
144
/// If there is any item `x` in the `array` for which `matches(x)`
145
/// is true, this function will return a reference to one such
146
/// item.  (We don't specify which.)
147
///
148
/// Otherwise, this function returns none.
149
///
150
/// We evaluate `matches` on every item of the array, and try not to
151
/// leak by timing which element (if any) matched.  Note that if
152
/// `matches` itself has side channels, this function can't hide them.
153
///
154
/// Note that this doesn't necessarily do a constant-time comparison,
155
/// and that it is not constant-time for the found/not-found case.
156
186
pub fn ct_lookup<T, F>(array: &[T], matches: F) -> Option<&T>
157
186
where
158
186
    F: Fn(&T) -> Choice,
159
{
160
    // ConditionallySelectable isn't implemented for usize, so we need
161
    // to use u64.
162
186
    let mut idx: u64 = 0;
163
186
    let mut found: Choice = 0.into();
164

            
165
1710
    for (i, x) in array.iter().enumerate() {
166
1710
        let equal = matches(x);
167
1710
        idx.conditional_assign(&(i as u64), equal);
168
1710
        found.conditional_assign(&equal, equal);
169
1710
    }
170

            
171
186
    if found.into() {
172
182
        Some(&array[idx as usize])
173
    } else {
174
4
        None
175
    }
176
186
}
177

            
178
#[cfg(test)]
179
mod test {
180
    // @@ begin test lint list maintained by maint/add_warning @@
181
    #![allow(clippy::bool_assert_comparison)]
182
    #![allow(clippy::clone_on_copy)]
183
    #![allow(clippy::dbg_macro)]
184
    #![allow(clippy::mixed_attributes_style)]
185
    #![allow(clippy::print_stderr)]
186
    #![allow(clippy::print_stdout)]
187
    #![allow(clippy::single_char_pattern)]
188
    #![allow(clippy::unwrap_used)]
189
    #![allow(clippy::unchecked_time_subtraction)]
190
    #![allow(clippy::useless_vec)]
191
    #![allow(clippy::needless_pass_by_value)]
192
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
193

            
194
    use super::*;
195
    use rand::Rng;
196
    use tor_basic_utils::test_rng;
197

            
198
    #[allow(clippy::nonminimal_bool)]
199
    #[test]
200
    fn test_comparisons() {
201
        let num = 200;
202
        let mut rng = test_rng::testing_rng();
203

            
204
        let mut array: Vec<CtByteArray<32>> =
205
            (0..num).map(|_| rng.random::<[u8; 32]>().into()).collect();
206
        array.sort();
207

            
208
        for i in 0..num {
209
            assert_eq!(array[i], array[i]);
210
            assert!(!(array[i] < array[i]));
211
            assert!(!(array[i] > array[i]));
212

            
213
            for j in (i + 1)..num {
214
                // Note that this test will behave incorrectly if the rng
215
                // generates the same 256 value twice, but that's ridiculously
216
                // implausible.
217
                assert!(array[i] < array[j]);
218
                assert_ne!(array[i], array[j]);
219
                assert!(array[j] > array[i]);
220
                assert_eq!(
221
                    array[i].cmp(&array[j]),
222
                    array[j].as_ref().cmp(array[i].as_ref()).reverse()
223
                );
224
            }
225
        }
226
    }
227

            
228
    #[test]
229
    fn test_lookup() {
230
        use super::ct_lookup as lookup;
231
        use subtle::ConstantTimeEq;
232
        let items = vec![
233
            "One".to_string(),
234
            "word".to_string(),
235
            "of".to_string(),
236
            "every".to_string(),
237
            "length".to_string(),
238
        ];
239
        let of_word = lookup(&items[..], |i| i.len().ct_eq(&2));
240
        let every_word = lookup(&items[..], |i| i.len().ct_eq(&5));
241
        let no_word = lookup(&items[..], |i| i.len().ct_eq(&99));
242
        assert_eq!(of_word.unwrap(), "of");
243
        assert_eq!(every_word.unwrap(), "every");
244
        assert_eq!(no_word, None);
245
    }
246
}