ring/
constant_time.rs

1// Copyright 2015-2016 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15//! Constant-time operations.
16
17use crate::{c, error};
18
19/// Returns `Ok(())` if `a == b` and `Err(error::Unspecified)` otherwise.
20/// The comparison of `a` and `b` is done in constant time with respect to the
21/// contents of each, but NOT in constant time with respect to the lengths of
22/// `a` and `b`.
23pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
24    if a.len() != b.len() {
25        return Err(error::Unspecified);
26    }
27    let result = unsafe { CRYPTO_memcmp(a.as_ptr(), b.as_ptr(), a.len()) };
28    match result {
29        0 => Ok(()),
30        _ => Err(error::Unspecified),
31    }
32}
33
34prefixed_extern! {
35    fn CRYPTO_memcmp(a: *const u8, b: *const u8, len: c::size_t) -> c::int;
36}
37
38pub(crate) fn xor<const N: usize>(mut a: [u8; N], b: [u8; N]) -> [u8; N] {
39    // `xor_assign_at_start()`, but avoiding relying on the compiler to
40    // optimize the slice iterators.
41    a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a ^= *b);
42    a
43}
44
45/// XORs the first N bytes of `b` into `a`, where N is
46/// `core::cmp::min(a.len(), b.len())`.
47#[inline(always)]
48pub(crate) fn xor_assign_at_start<'a>(
49    a: impl IntoIterator<Item = &'a mut u8>,
50    b: impl IntoIterator<Item = &'a u8>,
51) {
52    a.into_iter().zip(b).for_each(|(a, b)| *a ^= *b);
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58    use crate::limb::LimbMask;
59    use crate::{bssl, error, rand};
60
61    #[test]
62    fn test_constant_time() -> Result<(), error::Unspecified> {
63        prefixed_extern! {
64            fn bssl_constant_time_test_main() -> bssl::Result;
65        }
66        Result::from(unsafe { bssl_constant_time_test_main() })
67    }
68
69    #[test]
70    fn constant_time_conditional_memcpy() -> Result<(), error::Unspecified> {
71        let rng = rand::SystemRandom::new();
72        for _ in 0..100 {
73            let mut out = rand::generate::<[u8; 256]>(&rng)?.expose();
74            let input = rand::generate::<[u8; 256]>(&rng)?.expose();
75
76            // Mask to 16 bits to make zero more likely than it would otherwise be.
77            let b = (rand::generate::<[u8; 1]>(&rng)?.expose()[0] & 0x0f) == 0;
78
79            let ref_in = input;
80            let ref_out = if b { input } else { out };
81
82            prefixed_extern! {
83                fn bssl_constant_time_test_conditional_memcpy(dst: &mut [u8; 256], src: &[u8; 256], b: LimbMask);
84            }
85            unsafe {
86                bssl_constant_time_test_conditional_memcpy(
87                    &mut out,
88                    &input,
89                    if b { LimbMask::True } else { LimbMask::False },
90                )
91            }
92            assert_eq!(ref_in, input);
93            assert_eq!(ref_out, out);
94        }
95
96        Ok(())
97    }
98
99    #[test]
100    fn constant_time_conditional_memxor() -> Result<(), error::Unspecified> {
101        let rng = rand::SystemRandom::new();
102        for _ in 0..256 {
103            let mut out = rand::generate::<[u8; 256]>(&rng)?.expose();
104            let input = rand::generate::<[u8; 256]>(&rng)?.expose();
105
106            // Mask to 16 bits to make zero more likely than it would otherwise be.
107            let b = (rand::generate::<[u8; 1]>(&rng)?.expose()[0] & 0x0f) != 0;
108
109            let ref_in = input;
110            let ref_out = if b { xor(out, ref_in) } else { out };
111
112            prefixed_extern! {
113                fn bssl_constant_time_test_conditional_memxor(dst: &mut [u8; 256], src: &[u8; 256], b: LimbMask);
114            }
115            unsafe {
116                bssl_constant_time_test_conditional_memxor(
117                    &mut out,
118                    &input,
119                    if b { LimbMask::True } else { LimbMask::False },
120                );
121            }
122
123            assert_eq!(ref_in, input);
124            assert_eq!(ref_out, out);
125        }
126
127        Ok(())
128    }
129}