ring
ring copied to clipboard
Value barrier in pure rust
https://github.com/briansmith/ring/pull/1434 deals with rewriting constant time functions in pure rust, however, one of the last functions to stay behind in C is the CONSTANT_TIME_value_barrier_w
function, guaranteed by clang compiler internals not to be optimised away.
This could probably be guaranteed in pure rust with either intrinsics copy, ptr read, or more strongly, read_volatile.
In particular, the Volatile section on a rust operating system blog makes a strong case for these, where the volatile
library is simply a wrapper for above API. The volatile apis explicitly signal to the compiler that "this read has side effects, don't optimize it", in this case we want a memory barrier, so we perform a volatile read on a value that can only be generated through the constant-time compare process.
Another interesting comparison to this approach is this function, which almost exclusively uses the same approach as the value barrier in C, only using rust ASM macros.
I just encountered subtle, which aims to provide primitives to deal with constant-time evaluation.
It pulls in no other crates, is small, and only has little unsafe
unsafe usage (which is also well-documented), @briansmith what do you think?
Feels like you want core::arch::asm!
:
pub fn CONSTANT_TIME_value_barrier_w(mut x: CryptoWord) -> CryptoWord {
unsafe {
core::arch::asm!(
"/* {0} */",
inout(reg) x,
options(nostack,preserves_flags,nomem,pure),
);
}
x
}
Stable since Rust 1.59.
Edit: Ah, never mind, that is exactly what the function in timing-shield you linked does.