1//! Define helpers for working with types in constant time.
23use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
4use zeroize::Zeroize;
56#[cfg(feature = "memquota-memcost")]
7use {derive_deftly::Deftly, tor_memquota::derive_deftly_template_HasMemoryCost};
89/// 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)]
26pub struct CtByteArray<const N: usize>([u8; N]);
2728impl<const N: usize> ConstantTimeEq for CtByteArray<N> {
29fn ct_eq(&self, other: &Self) -> Choice {
30self.0.ct_eq(&other.0)
31 }
32}
3334impl<const N: usize> PartialEq for CtByteArray<N> {
35fn eq(&self, other: &Self) -> bool {
36self.ct_eq(other).into()
37 }
38}
39impl<const N: usize> Eq for CtByteArray<N> {}
4041impl<const N: usize> From<[u8; N]> for CtByteArray<N> {
42fn from(value: [u8; N]) -> Self {
43Self(value)
44 }
45}
4647impl<const N: usize> From<CtByteArray<N>> for [u8; N] {
48fn from(value: CtByteArray<N>) -> Self {
49 value.0
50}
51}
5253impl<const N: usize> Ord for CtByteArray<N> {
54fn cmp(&self, other: &Self) -> std::cmp::Ordering {
55// At every point, this value will be set to:
56 // 0 if a[i]==b[i] for all i considered so far.
57 // a[i] - b[i] for the lowest i that has a nonzero a[i] - b[i].
58let mut first_nonzero_difference = 0_i16;
5960for (a, b) in self.0.iter().zip(other.0.iter()) {
61let difference = i16::from(*a) - i16::from(*b);
6263// If it's already set to a nonzero value, this conditional
64 // assignment does nothing. Otherwise, it sets it to `difference`.
65 //
66 // The use of conditional_assign and ct_eq ensures that the compiler
67 // won't short-circuit our logic here and end the loop (or stop
68 // computing differences) on the first nonzero difference.
69first_nonzero_difference
70 .conditional_assign(&difference, first_nonzero_difference.ct_eq(&0));
71 }
7273// 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.
75first_nonzero_difference.cmp(&0)
76 }
77}
7879impl<const N: usize> PartialOrd for CtByteArray<N> {
80fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
81Some(self.cmp(other))
82 }
83}
8485impl<const N: usize> AsRef<[u8; N]> for CtByteArray<N> {
86fn as_ref(&self) -> &[u8; N] {
87&self.0
88}
89}
9091impl<const N: usize> AsMut<[u8; N]> for CtByteArray<N> {
92fn as_mut(&mut self) -> &mut [u8; N] {
93&mut self.0
94}
95}
9697/// 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.
112pub fn ct_lookup<T, F>(array: &[T], matches: F) -> Option<&T>
113where
114F: Fn(&T) -> Choice,
115{
116// ConditionallySelectable isn't implemented for usize, so we need
117 // to use u64.
118let mut idx: u64 = 0;
119let mut found: Choice = 0.into();
120121for (i, x) in array.iter().enumerate() {
122let equal = matches(x);
123 idx.conditional_assign(&(i as u64), equal);
124 found.conditional_assign(&equal, equal);
125 }
126127if found.into() {
128Some(&array[idx as usize])
129 } else {
130None
131}
132}
133134#[cfg(test)]
135mod 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 @@ -->
149150use super::*;
151use rand::Rng;
152use tor_basic_utils::test_rng;
153154#[allow(clippy::nonminimal_bool)]
155 #[test]
156fn test_comparisons() {
157let num = 200;
158let mut rng = test_rng::testing_rng();
159160let mut array: Vec<CtByteArray<32>> =
161 (0..num).map(|_| rng.random::<[u8; 32]>().into()).collect();
162 array.sort();
163164for i in 0..num {
165assert_eq!(array[i], array[i]);
166assert!(!(array[i] < array[i]));
167assert!(!(array[i] > array[i]));
168169for 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.
173assert!(array[i] < array[j]);
174assert_ne!(array[i], array[j]);
175assert!(array[j] > array[i]);
176assert_eq!(
177 array[i].cmp(&array[j]),
178 array[j].as_ref().cmp(array[i].as_ref()).reverse()
179 );
180 }
181 }
182 }
183184#[test]
185fn test_lookup() {
186use super::ct_lookup as lookup;
187use subtle::ConstantTimeEq;
188let items = vec![
189"One".to_string(),
190"word".to_string(),
191"of".to_string(),
192"every".to_string(),
193"length".to_string(),
194 ];
195let of_word = lookup(&items[..], |i| i.len().ct_eq(&2));
196let every_word = lookup(&items[..], |i| i.len().ct_eq(&5));
197let no_word = lookup(&items[..], |i| i.len().ct_eq(&99));
198assert_eq!(of_word.unwrap(), "of");
199assert_eq!(every_word.unwrap(), "every");
200assert_eq!(no_word, None);
201 }
202}