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};
18use core::num::NonZeroUsize;
19
20mod boolmask;
21mod leaky;
22mod word;
23
24pub(crate) use self::{boolmask::BoolMask, leaky::LeakyWord, word::Word};
25
26/// Returns `Ok(())` if `a == b` and `Err(error::Unspecified)` otherwise.
27/// The comparison of `a` and `b` is done in constant time with respect to the
28/// contents of each, but NOT in constant time with respect to the lengths of
29/// `a` and `b`.
30pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
31 let len: usize = a.len(); // Arbitrary choice.
32 if b.len() != len {
33 return Err(error::Unspecified);
34 }
35 match NonZeroUsize::new(len) {
36 Some(len: NonZero) => {
37 let a: *const u8 = a.as_ptr();
38 let b: *const u8 = b.as_ptr();
39 // SAFETY: `a` and `b` are valid non-null non-dangling pointers to `len`
40 // bytes.
41 let result: i32 = unsafe { CRYPTO_memcmp(a, b, len) };
42 match result {
43 0 => Ok(()),
44 _ => Err(error::Unspecified),
45 }
46 }
47 None => Ok(()), // Empty slices are equal.
48 }
49}
50
51prefixed_extern! {
52 fn CRYPTO_memcmp(a: *const u8, b: *const u8, len: c::NonZero_size_t) -> c::int;
53}
54
55pub(crate) fn xor_16(a: [u8; 16], b: [u8; 16]) -> [u8; 16] {
56 let a: u128 = u128::from_ne_bytes(a);
57 let b: u128 = u128::from_ne_bytes(b);
58 let r: u128 = a ^ b;
59 r.to_ne_bytes()
60}
61
62#[inline(always)]
63pub(crate) fn xor_assign<'a>(a: impl IntoIterator<Item = &'a mut u8>, b: u8) {
64 a.into_iter().for_each(|a: &'a mut u8| *a ^= b);
65}
66
67/// XORs the first N bytes of `b` into `a`, where N is
68/// `core::cmp::min(a.len(), b.len())`.
69#[inline(always)]
70pub(crate) fn xor_assign_at_start<'a>(
71 a: impl IntoIterator<Item = &'a mut u8>,
72 b: impl IntoIterator<Item = &'a u8>,
73) {
74 a.into_iter().zip(b).for_each(|(a, b)| *a ^= *b);
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80 use crate::{bssl, rand};
81
82 fn leak_in_test(a: BoolMask) -> bool {
83 a.leak()
84 }
85
86 #[test]
87 fn test_constant_time() -> Result<(), error::Unspecified> {
88 prefixed_extern! {
89 fn bssl_constant_time_test_main() -> bssl::Result;
90 }
91 Result::from(unsafe { bssl_constant_time_test_main() })
92 }
93
94 #[test]
95 fn constant_time_conditional_memcpy() -> Result<(), error::Unspecified> {
96 let rng = rand::SystemRandom::new();
97 for _ in 0..100 {
98 let mut out = rand::generate::<[u8; 256]>(&rng)?.expose();
99 let input = rand::generate::<[u8; 256]>(&rng)?.expose();
100
101 // Mask to 16 bits to make zero more likely than it would otherwise be.
102 let b = (rand::generate::<[u8; 1]>(&rng)?.expose()[0] & 0x0f) == 0;
103
104 let ref_in = input;
105 let ref_out = if b { input } else { out };
106
107 prefixed_extern! {
108 fn bssl_constant_time_test_conditional_memcpy(dst: &mut [u8; 256], src: &[u8; 256], b: BoolMask);
109 }
110 unsafe {
111 bssl_constant_time_test_conditional_memcpy(
112 &mut out,
113 &input,
114 if b { BoolMask::TRUE } else { BoolMask::FALSE },
115 )
116 }
117 assert_eq!(ref_in, input);
118 assert_eq!(ref_out, out);
119 }
120
121 Ok(())
122 }
123
124 #[test]
125 fn constant_time_conditional_memxor() -> Result<(), error::Unspecified> {
126 let rng = rand::SystemRandom::new();
127 for _ in 0..256 {
128 let mut out = rand::generate::<[u8; 256]>(&rng)?.expose();
129 let input = rand::generate::<[u8; 256]>(&rng)?.expose();
130
131 // Mask to 16 bits to make zero more likely than it would otherwise be.
132 let b = (rand::generate::<[u8; 1]>(&rng)?.expose()[0] & 0x0f) != 0;
133
134 let ref_in = input;
135 let mut ref_out = out;
136 if b {
137 xor_assign_at_start(&mut ref_out, &ref_in)
138 };
139
140 prefixed_extern! {
141 fn bssl_constant_time_test_conditional_memxor(dst: &mut [u8; 256], src: &[u8; 256], b: BoolMask);
142 }
143 unsafe {
144 bssl_constant_time_test_conditional_memxor(
145 &mut out,
146 &input,
147 if b { BoolMask::TRUE } else { BoolMask::FALSE },
148 );
149 }
150
151 assert_eq!(ref_in, input);
152 assert_eq!(ref_out, out);
153 }
154
155 Ok(())
156 }
157
158 #[test]
159 fn test_bool_mask_bitwise_and_is_logical_and() {
160 assert!(leak_in_test(BoolMask::TRUE & BoolMask::TRUE));
161 assert!(!leak_in_test(BoolMask::TRUE & BoolMask::FALSE));
162 assert!(!leak_in_test(BoolMask::FALSE & BoolMask::TRUE));
163 assert!(!leak_in_test(BoolMask::FALSE & BoolMask::FALSE));
164 }
165}
166