chore(core): expose the SHA-3 hazard guard API
What changed, and why it matters
This commit is a routine code cleanup that exposes an existing internal SHA-3/Keccak hashing helper API so other parts of the firmware can reuse it safely. It adds buffer-size checks and tests, but does not fix any reported bug or vulnerability.
No immediate action required; review is routine. If consuming this newly public API elsewhere, ensure callers respect the documented init-before-reuse contract and pass buffers of exactly digest_size().
Security signals we found
Adds explicit buffer length checks before calling unsafe finalize FFI functions
Documents zeroization-after-finalize and required re-init before context reuse
Exposes previously internal API with 'HazardGuard' secret-handling semantics
Evidence from the diff
The change makes Sha3Guard, SHA3_CTX::init, update, sha3_finalize, and keccak_finalize public, and adds a digest_size() helper plus ensure! length checks in the finalize methods. It also adds unit tests for incremental updates, context reuse, and digest-size computation. There is no patch of a security flaw; the work is defensive API hardening.
Changed components
core/embed/crypto/src/sha3.rsInspect captured patch +111 / −9
### core/embed/crypto/src/sha3.rs
@@ -7,14 +7,18 @@ use super::secret::{HazardGuard, SecretContext, SecretContextLock, ZeroableMemor
use super::{Error, ffi};
pub type Sha3Ctx = SecretContext<ffi::SHA3_CTX>;
+pub type Sha3Guard<'a> = HazardGuard<'a, ffi::SHA3_CTX>;
impl ffi::SHA3_CTX {
/// Initialize the SHA3/Keccak context for the given digest bit size.
///
+ /// Called by the hasher constructors. Call again when reusing the context
+ /// after finalizing it.
+ ///
/// # Copy hazard
///
/// None because a "freshly initialized context" is public information.
- fn init(&mut self, bit_size: u32) -> Result<(), Error> {
+ pub fn init(&mut self, bit_size: u32) -> Result<(), Error> {
// SAFETY: ffi
// COPY HAZARD: no sensitive data is encoded into the state
if unsafe { ffi::sha3_Init(self, bit_size) } {
@@ -23,27 +27,53 @@ impl ffi::SHA3_CTX {
Err(Error::InvalidParams)
}
}
+
+ /// Digest size in bytes, derived from the rate set by [`Self::init`] (the
+ /// same way `sha3_Final` and `keccak_Final` compute it).
+ pub fn digest_size(&self) -> usize {
+ 100 - self.block_size as usize / 2
+ }
}
-impl HazardGuard<'_, ffi::SHA3_CTX> {
+impl Sha3Guard<'_> {
/// Update the SHA3/Keccak context with the given data.
- fn update(&mut self, data: &[u8]) {
+ pub fn update(&mut self, data: &[u8]) {
let ptr = CSlice::from(data);
// SAFETY: ffi
// COPY HAZARD: operates on the guarded context in place
unsafe { ffi::sha3_Update(self.hazard_mut(), ptr.ptr(), ptr.len()) };
}
- /// Finalize as SHA-3 into `buffer`.
- fn sha3_finalize(&mut self, buffer: &mut [u8]) {
- // SAFETY: ffi
+ /// Finalize as SHA-3 into `buffer`, which must be exactly
+ /// [`ffi::SHA3_CTX::digest_size`] bytes long.
+ ///
+ /// After calling this method, the context is in a zeroized state. Before
+ /// reusing it, the caller must call [`ffi::SHA3_CTX::init`] to
+ /// reinitialize it.
+ pub fn sha3_finalize(&mut self, buffer: &mut [u8]) {
+ let ctx = self.hazard_mut();
+ ensure!(
+ buffer.len() == ctx.digest_size(),
+ "Invalid SHA3 buffer size"
+ );
+ // SAFETY: ffi, `buffer` holds exactly the digest size checked above
// COPY HAZARD: operates on the guarded context in place
unsafe { ffi::sha3_Final(self.hazard_mut(), buffer.as_mut_ptr()) };
}
- /// Finalize as Keccak into `buffer`.
- fn keccak_finalize(&mut self, buffer: &mut [u8]) {
- // SAFETY: ffi
+ /// Finalize as Keccak into `buffer`, which must be exactly
+ /// [`ffi::SHA3_CTX::digest_size`] bytes long.
+ ///
+ /// After calling this method, the context is in a zeroized state. Before
+ /// reusing it, the caller must call [`ffi::SHA3_CTX::init`] to
+ /// reinitialize it.
+ pub fn keccak_finalize(&mut self, buffer: &mut [u8]) {
+ let ctx = self.hazard_mut();
+ ensure!(
+ buffer.len() == ctx.digest_size(),
+ "Invalid Keccak buffer size"
+ );
+ // SAFETY: ffi, `buffer` holds exactly the digest size checked above
// COPY HAZARD: operates on the guarded context in place
unsafe { ffi::keccak_Final(self.hazard_mut(), buffer.as_mut_ptr()) };
}
@@ -218,4 +248,76 @@ mod test {
assert_eq!(hex::encode(Keccak512::digest(data)), *expected);
}
}
+
+ #[test]
+ fn test_update() {
+ macro_rules! check_update {
+ ($hasher:ident, $vectors:expr) => {
+ for (data, expected) in $vectors {
+ let mut ctx = Sha3Ctx::default();
+ let mut sha = $hasher::new(&mut ctx);
+ sha.update(data);
+ assert_eq!(hex::encode(sha.finalize()), *expected);
+ }
+ };
+ }
+ check_update!(Sha3_256, SHA3_256_VECTORS);
+ check_update!(Keccak256, KECCAK_256_VECTORS);
+ check_update!(Sha3_512, SHA3_512_VECTORS);
+ check_update!(Keccak512, KECCAK_512_VECTORS);
+ }
+
+ #[test]
+ fn test_update_million_a() {
+ let mut ctx = Sha3Ctx::default();
+ let mut sha = Sha3_256::new(&mut ctx);
+ for _ in 0..1_000_000 {
+ sha.update(b"a");
+ }
+ assert_eq!(
+ hex::encode(sha.finalize()),
+ "5c8875ae474a3634ba4fd55ec85bffd661f32aca75c6d699d0cdcb6c115891c1"
+ );
+
+ let mut ctx = Sha3Ctx::default();
+ let mut sha = Sha3_512::new(&mut ctx);
+ for _ in 0..1_000_000 {
+ sha.update(b"a");
+ }
+ assert_eq!(
+ hex::encode(sha.finalize()),
+ "3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87"
+ );
+ }
+
+ #[test]
+ fn test_guard_reuse() {
+ let mut ctx = Sha3Ctx::default();
+ for (is_keccak, expected) in [
+ (false, hex::encode(Sha3_256::digest(b"abc"))),
+ (true, hex::encode(Keccak256::digest(b"abc"))),
+ ] {
+ for _ in 0..2 {
+ ctx.hazard_mut().init(256).unwrap();
+ let mut guard = Sha3Guard::hazard_new(&mut ctx);
+ guard.update(b"abc");
+ let mut out = [0u8; 32];
+ if is_keccak {
+ guard.keccak_finalize(&mut out);
+ } else {
+ guard.sha3_finalize(&mut out);
+ }
+ assert_eq!(hex::encode(out), expected);
+ }
+ }
+ }
+
+ #[test]
+ fn test_digest_size() {
+ let mut ctx = Sha3Ctx::default();
+ for bit_size in [224, 256, 384, 512] {
+ ctx.hazard_mut().init(bit_size).unwrap();
+ assert_eq!(ctx.hazard_mut().digest_size(), bit_size as usize / 8);
+ }
+ }
}Why this scored 12/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.