| 1 |
//! Generic implementation of `constant_time_eq` and `constant_time_eq_n`. |
| 2 |
//! |
| 3 |
//! This implementation does SIMD in general-purpose registers instead of vector registers, and |
| 4 |
//! uses inline assembly only to hide the dependencies and comparisons from the optimizer, to |
| 5 |
//! prevent it from returning early when the accumulator becomes non-zero (found a difference) or |
| 6 |
//! all-ones (the accumulator can no longer change). |
| 7 |
//! |
| 8 |
//! This generic implementation is also used for suffixes smaller than one vector from the |
| 9 |
//! architecture-specific vector implementations. This is simpler and often faster than trying to |
| 10 |
//! load a partial vector register. |
| 11 |
|
| 12 |
use core::mem::size_of; |
| 13 |
use core::ops::BitXor; |
| 14 |
use core::ptr::read_unaligned; |
| 15 |
|
| 16 |
use crate::with_dit; |
| 17 |
|
| 18 |
/// The natural word type for this architecture. All bit patterns must be valid for this type. |
| 19 |
#[cfg(all( |
| 20 |
target_pointer_width = "64", |
| 21 |
any(not(target_arch = "riscv64"), target_feature = "unaligned-scalar-mem") |
| 22 |
))] |
| 23 |
pub(crate) type Word = u64; |
| 24 |
|
| 25 |
/// The natural word type for this architecture. All bit patterns must be valid for this type. |
| 26 |
#[cfg(all( |
| 27 |
target_pointer_width = "32", |
| 28 |
any(not(target_arch = "riscv32"), target_feature = "unaligned-scalar-mem") |
| 29 |
))] |
| 30 |
pub(crate) type Word = u32; |
| 31 |
|
| 32 |
/// The natural word type for this architecture. All bit patterns must be valid for this type. |
| 33 |
#[cfg(target_pointer_width = "16")] |
| 34 |
pub(crate) type Word = u16; |
| 35 |
|
| 36 |
/// The natural word type for this architecture. All bit patterns must be valid for this type. |
| 37 |
#[cfg(not(any( |
| 38 |
target_pointer_width = "64", |
| 39 |
target_pointer_width = "32", |
| 40 |
target_pointer_width = "16" |
| 41 |
)))] |
| 42 |
pub(crate) type Word = usize; |
| 43 |
|
| 44 |
// RISC-V without unaligned-scalar-mem generates worse code for unaligned word reads. |
| 45 |
/// The natural word type for this architecture. All bit patterns must be valid for this type. |
| 46 |
#[cfg(all( |
| 47 |
any(target_arch = "riscv64", target_arch = "riscv32"), |
| 48 |
not(target_feature = "unaligned-scalar-mem") |
| 49 |
))] |
| 50 |
pub(crate) type Word = u8; |
| 51 |
|
| 52 |
/// Hides a value from the optimizer. |
| 53 |
#[cfg(all( |
| 54 |
not(miri), |
| 55 |
any( |
| 56 |
target_arch = "x86", |
| 57 |
target_arch = "x86_64", |
| 58 |
target_arch = "arm", |
| 59 |
target_arch = "aarch64", |
| 60 |
target_arch = "arm64ec", |
| 61 |
target_arch = "riscv32", |
| 62 |
target_arch = "riscv64", |
| 63 |
target_arch = "loongarch64", |
| 64 |
target_arch = "s390x", |
| 65 |
) |
| 66 |
))] |
| 67 |
#[must_use] |
| 68 |
#[inline(always)] |
| 69 |
fn optimizer_hide(mut value: Word) -> Word { |
| 70 |
// SAFETY: the input value is passed unchanged to the output, the inline assembly does nothing. |
| 71 |
unsafe { |
| 72 |
core::arch::asm!("/* {0} */", inlateout(reg) value, options(pure, nomem, preserves_flags, nostack)); |
| 73 |
} |
| 74 |
value |
| 75 |
} |
| 76 |
|
| 77 |
/// Attempts to hide a value from the optimizer. |
| 78 |
#[cfg(any( |
| 79 |
miri, |
| 80 |
not(any( |
| 81 |
target_arch = "x86", |
| 82 |
target_arch = "x86_64", |
| 83 |
target_arch = "arm", |
| 84 |
target_arch = "aarch64", |
| 85 |
target_arch = "arm64ec", |
| 86 |
target_arch = "riscv32", |
| 87 |
target_arch = "riscv64", |
| 88 |
target_arch = "loongarch64", |
| 89 |
target_arch = "s390x", |
| 90 |
)) |
| 91 |
))] |
| 92 |
#[must_use] |
| 93 |
#[inline(never)] |
| 94 |
fn optimizer_hide(value: Word) -> Word { |
| 95 |
// The current implementation of black_box in the main codegen backends is similar to |
| 96 |
// { |
| 97 |
// let result = value; |
| 98 |
// asm!("", in(reg) &result); |
| 99 |
// result |
| 100 |
// } |
| 101 |
// which round-trips the value through the stack, instead of leaving it in a register. |
| 102 |
// Experimental codegen backends might implement black_box as a pure identity function, |
| 103 |
// without the expected optimization barrier, so it's less guaranteed than inline asm. |
| 104 |
// For that reason, we also use the #[inline(never)] hint, which makes it harder for an |
| 105 |
// optimizer to look inside this function. |
| 106 |
core::hint::black_box(value) |
| 107 |
} |
| 108 |
|
| 109 |
/// Equivalent to `read_unaligned` for byte slices. |
| 110 |
/// |
| 111 |
/// # Safety |
| 112 |
/// |
| 113 |
/// All bit patterns must be valid for type T. |
| 114 |
#[must_use] |
| 115 |
#[inline(always)] |
| 116 |
unsafe fn read_unaligned_from_slice<T>(src: &[u8]) -> T { |
| 117 |
assert_eq!(src.len(), size_of::<T>()); |
| 118 |
|
| 119 |
// SAFETY: the slice has enough bytes for type T |
| 120 |
// SAFETY: all bit patterns are valid for type T |
| 121 |
unsafe { read_unaligned(src.as_ptr().cast::<T>()) } |
| 122 |
} |
| 123 |
|
| 124 |
/// Generic implementation of `constant_time_eq` and `constant_time_eq_n`. |
| 125 |
#[must_use] |
| 126 |
#[inline(always)] |
| 127 |
pub(crate) fn constant_time_eq_impl(mut a: &[u8], mut b: &[u8], mut tmp: Word) -> bool { |
| 128 |
if a.len() != b.len() { |
| 129 |
return false; |
| 130 |
} |
| 131 |
|
| 132 |
// This statement does nothing, because a.len() == b.len() here, |
| 133 |
// but it makes the optimizer elide some useless bounds checks. |
| 134 |
b = &b[..a.len()]; |
| 135 |
|
| 136 |
// Early exit for the common case when called by the SIMD code. |
| 137 |
if a.is_empty() { |
| 138 |
return tmp == 0; |
| 139 |
} |
| 140 |
|
| 141 |
/// Reads and compares a single word from the input, adjusting the slices. |
| 142 |
/// Returns zero if both words are equal, non-zero if any byte is different. |
| 143 |
/// |
| 144 |
/// # Safety |
| 145 |
/// |
| 146 |
/// All bit patterns must be valid for type T. |
| 147 |
#[must_use] |
| 148 |
#[inline(always)] |
| 149 |
unsafe fn cmp_step<T: BitXor<Output = T>>(a: &mut &[u8], b: &mut &[u8]) -> T { |
| 150 |
// SAFETY: all bit patterns are valid for type T |
| 151 |
let tmpa = unsafe { read_unaligned_from_slice::<T>(&a[..size_of::<T>()]) }; |
| 152 |
// SAFETY: all bit patterns are valid for type T |
| 153 |
let tmpb = unsafe { read_unaligned_from_slice::<T>(&b[..size_of::<T>()]) }; |
| 154 |
|
| 155 |
*a = &a[size_of::<T>()..]; |
| 156 |
*b = &b[size_of::<T>()..]; |
| 157 |
|
| 158 |
tmpa ^ tmpb |
| 159 |
} |
| 160 |
|
| 161 |
// The optimizer is not allowed to assume anything about the value of tmp after each iteration, |
| 162 |
// which prevents it from terminating the loop early if the value becomes non-zero or all-ones. |
| 163 |
|
| 164 |
// Do most of the work using the natural word size; the other blocks clean up the leftovers. |
| 165 |
while a.len() >= size_of::<Word>() { |
| 166 |
// SAFETY: all bit patterns are valid for Word |
| 167 |
let cmp = optimizer_hide(unsafe { cmp_step::<Word>(&mut a, &mut b) }); |
| 168 |
tmp = optimizer_hide(tmp | cmp); |
| 169 |
} |
| 170 |
|
| 171 |
// These first two blocks would only be necessary for architectures with usize > 64 bits. |
| 172 |
// They are kept here for future-proofing, so that everything still works in that case. |
| 173 |
// The optimizer tracks the range of len and will not generate any code for these blocks. |
| 174 |
while a.len() >= size_of::<u128>() { |
| 175 |
// SAFETY: all bit patterns are valid for u128 |
| 176 |
let cmp = optimizer_hide(unsafe { cmp_step::<u128>(&mut a, &mut b) } as Word); |
| 177 |
tmp = optimizer_hide(tmp | cmp); |
| 178 |
} |
| 179 |
if a.len() >= size_of::<u64>() { |
| 180 |
// SAFETY: all bit patterns are valid for u64 |
| 181 |
let cmp = optimizer_hide(unsafe { cmp_step::<u64>(&mut a, &mut b) } as Word); |
| 182 |
tmp = optimizer_hide(tmp | cmp); |
| 183 |
} |
| 184 |
if a.len() >= size_of::<u32>() { |
| 185 |
// SAFETY: all bit patterns are valid for u32 |
| 186 |
let cmp = optimizer_hide(unsafe { cmp_step::<u32>(&mut a, &mut b) } as Word); |
| 187 |
tmp = optimizer_hide(tmp | cmp); |
| 188 |
} |
| 189 |
if a.len() >= size_of::<u16>() { |
| 190 |
// SAFETY: all bit patterns are valid for u16 |
| 191 |
let cmp = optimizer_hide(unsafe { cmp_step::<u16>(&mut a, &mut b) } as Word); |
| 192 |
tmp = optimizer_hide(tmp | cmp); |
| 193 |
} |
| 194 |
if a.len() >= size_of::<u8>() { |
| 195 |
// SAFETY: all bit patterns are valid for u8 |
| 196 |
let cmp = optimizer_hide(unsafe { cmp_step::<u8>(&mut a, &mut b) } as Word); |
| 197 |
tmp = optimizer_hide(tmp | cmp); |
| 198 |
} |
| 199 |
|
| 200 |
tmp == 0 |
| 201 |
} |
| 202 |
|
| 203 |
/// Compares two equal-sized byte strings in constant time. |
| 204 |
/// |
| 205 |
/// # Examples |
| 206 |
/// |
| 207 |
/// ``` |
| 208 |
/// use constant_time_eq::constant_time_eq; |
| 209 |
/// |
| 210 |
/// assert!(constant_time_eq(b"foo", b"foo")); |
| 211 |
/// assert!(!constant_time_eq(b"foo", b"bar")); |
| 212 |
/// assert!(!constant_time_eq(b"bar", b"baz")); |
| 213 |
/// # assert!(constant_time_eq(b"", b"")); |
| 214 |
/// |
| 215 |
/// // Not equal-sized, so won't take constant time. |
| 216 |
/// assert!(!constant_time_eq(b"foo", b"")); |
| 217 |
/// assert!(!constant_time_eq(b"foo", b"quux")); |
| 218 |
/// ``` |
| 219 |
#[must_use] |
| 220 |
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { |
| 221 |
with_dit(|| constant_time_eq_impl(a, b, 0)) |
| 222 |
} |
| 223 |
|
| 224 |
/// Compares two fixed-size byte strings in constant time. |
| 225 |
/// |
| 226 |
/// # Examples |
| 227 |
/// |
| 228 |
/// ``` |
| 229 |
/// use constant_time_eq::constant_time_eq_n; |
| 230 |
/// |
| 231 |
/// assert!(constant_time_eq_n(&[3; 20], &[3; 20])); |
| 232 |
/// assert!(!constant_time_eq_n(&[3; 20], &[7; 20])); |
| 233 |
/// ``` |
| 234 |
#[must_use] |
| 235 |
pub fn constant_time_eq_n<const N: usize>(a: &[u8; N], b: &[u8; N]) -> bool { |
| 236 |
with_dit(|| constant_time_eq_impl(&a[..], &b[..], 0)) |
| 237 |
} |
| 238 |
|
| 239 |
#[cfg(test)] |
| 240 |
mod tests { |
| 241 |
#[cfg(feature = "count_instructions_test")] |
| 242 |
extern crate std; |
| 243 |
|
| 244 |
#[cfg(feature = "count_instructions_test")] |
| 245 |
#[test] |
| 246 |
fn count_optimizer_hide_instructions() -> std::io::Result<()> { |
| 247 |
use super::{Word, optimizer_hide}; |
| 248 |
use count_instructions::count_instructions; |
| 249 |
|
| 250 |
fn count() -> std::io::Result<usize> { |
| 251 |
// If optimizer_hide does not work, constant propagation and folding |
| 252 |
// will make this identical to count_optimized() below. |
| 253 |
let mut count = 0; |
| 254 |
assert_eq!( |
| 255 |
10 as Word, |
| 256 |
count_instructions( |
| 257 |
|| optimizer_hide(1) |
| 258 |
+ optimizer_hide(2) |
| 259 |
+ optimizer_hide(3) |
| 260 |
+ optimizer_hide(4), |
| 261 |
|_| count += 1 |
| 262 |
)? |
| 263 |
); |
| 264 |
Ok(count) |
| 265 |
} |
| 266 |
|
| 267 |
fn count_optimized() -> std::io::Result<usize> { |
| 268 |
#[inline(always)] |
| 269 |
fn inline_identity(value: Word) -> Word { |
| 270 |
value |
| 271 |
} |
| 272 |
|
| 273 |
let mut count = 0; |
| 274 |
assert_eq!( |
| 275 |
10 as Word, |
| 276 |
count_instructions( |
| 277 |
|| inline_identity(1) |
| 278 |
+ inline_identity(2) |
| 279 |
+ inline_identity(3) |
| 280 |
+ inline_identity(4), |
| 281 |
|_| count += 1 |
| 282 |
)? |
| 283 |
); |
| 284 |
Ok(count) |
| 285 |
} |
| 286 |
|
| 287 |
assert!(count()? > count_optimized()?); |
| 288 |
Ok(()) |
| 289 |
} |
| 290 |
} |