ring/bb/
mod.rs

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