keystore: port stretch_retained_seed_encryption_key to Rust
What changed, and why it matters
This commit rewrites an existing cryptographic key-stretching function from C into Rust. It is a language port/refactor: the same operations (salted hash, secure-chip KDF, HMAC) are performed in the same order, and the function is still called from C. There is no evidence in the commit of a security bug being fixed or introduced.
No immediate security action required. Treat as a normal refactor; standard review of the Rust FFI boundary and test coverage is sufficient.
Security signals we found
Language port of a cryptographic key-derivation routine with no algorithmic change visible in the diff.
New unsafe FFI wrapper enforces 32-byte input/output lengths and null-terminated purpose strings; returns false on any error.
Error granularity reduced: distinct salt/securechip errors collapsed to a single boolean false / new generic error code.
No mention of vulnerability, CVE, security fix, or external report in commit message or changed code.
Evidence from the diff
The change ports keystore_stretch_retained_seed_encryption_key from C to Rust. The C implementation used salt_hash_data, securechip_kdf, and rust_hmac_sha256. The Rust implementation uses crate::salt::hash_data, securechip::kdf, and HmacEngine::<sha256::Hash>. The algorithmic steps and purposes strings are preserved. The C callers now invoke rust_keystore_stretch_retained_seed_encryption_key via an extern "C" FFI boundary. Error handling is simplified: the function returns bool instead of keystore_error_t; one callsite maps failure to a new generic error code KEYSTORE_ERR_STRETCH_RETAINED_SEED_KEY. A unit test verifies the output matches a fixed expected value. No vulnerability or security fix is described in the commit message or diff.
Changed components
src/keystore.csrc/keystore.hsrc/rust/bitbox02-rust/src/keystore.rssrc/rust/bitbox02-sys/build.rssrc/rust/bitbox02/src/keystore.rsInspect captured patch +109 / −66
diff --git a/src/keystore.c b/src/keystore.c
index 6c0da48..e3a8dd0 100644
--- a/src/keystore.c
+++ b/src/keystore.c
@@ -63,27 +63,6 @@ static bool _validate_seed_length(size_t seed_len)
return seed_len == 16 || seed_len == 24 || seed_len == 32;
}
-USE_RESULT keystore_error_t keystore_stretch_retained_seed_encryption_key(
- const uint8_t* encryption_key,
- const char* purpose_in,
- const char* purpose_out,
- uint8_t* out)
-{
- uint8_t salted_hashed[32] = {0};
- UTIL_CLEANUP_32(salted_hashed);
- if (!salt_hash_data(encryption_key, 32, purpose_in, salted_hashed)) {
- return KEYSTORE_ERR_SALT;
- }
- if (securechip_kdf(salted_hashed, 32, out)) {
- return KEYSTORE_ERR_SECURECHIP;
- }
- if (!salt_hash_data(encryption_key, 32, purpose_out, salted_hashed)) {
- return KEYSTORE_ERR_SALT;
- }
- rust_hmac_sha256(salted_hashed, sizeof(salted_hashed), out, 32, out);
- return KEYSTORE_OK;
-}
-
bool keystore_copy_seed(uint8_t* seed_out, size_t* length_out)
{
if (!_is_unlocked_device) {
@@ -92,11 +71,15 @@ bool keystore_copy_seed(uint8_t* seed_out, size_t* length_out)
uint8_t retained_seed_encryption_key[32] = {0};
UTIL_CLEANUP_32(retained_seed_encryption_key);
- if (keystore_stretch_retained_seed_encryption_key(
- _unstretched_retained_seed_encryption_key,
+ if (!rust_keystore_stretch_retained_seed_encryption_key(
+ rust_util_bytes(
+ _unstretched_retained_seed_encryption_key,
+ sizeof(_unstretched_retained_seed_encryption_key)),
"keystore_retained_seed_access_in",
"keystore_retained_seed_access_out",
- retained_seed_encryption_key) != KEYSTORE_OK) {
+ rust_util_bytes_mut(
+ retained_seed_encryption_key,
+ sizeof(retained_seed_encryption_key)))) {
return false;
}
size_t len = _retained_seed_encrypted_len - 48;
@@ -122,11 +105,15 @@ bool keystore_copy_bip39_seed(uint8_t* bip39_seed_out)
uint8_t retained_bip39_seed_encryption_key[32] = {0};
UTIL_CLEANUP_32(retained_bip39_seed_encryption_key);
- if (keystore_stretch_retained_seed_encryption_key(
- _unstretched_retained_bip39_seed_encryption_key,
+ if (!rust_keystore_stretch_retained_seed_encryption_key(
+ rust_util_bytes(
+ _unstretched_retained_bip39_seed_encryption_key,
+ sizeof(_unstretched_retained_bip39_seed_encryption_key)),
"keystore_retained_bip39_seed_access_in",
"keystore_retained_bip39_seed_access_out",
- retained_bip39_seed_encryption_key) != KEYSTORE_OK) {
+ rust_util_bytes_mut(
+ retained_bip39_seed_encryption_key,
+ sizeof(retained_bip39_seed_encryption_key)))) {
return false;
}
size_t len = _retained_bip39_seed_encrypted_len - 48;
@@ -266,13 +253,15 @@ USE_RESULT static keystore_error_t _retain_seed(const uint8_t* seed, size_t seed
#endif
uint8_t retained_seed_encryption_key[32] = {0};
UTIL_CLEANUP_32(retained_seed_encryption_key);
- keystore_error_t result = keystore_stretch_retained_seed_encryption_key(
- _unstretched_retained_seed_encryption_key,
+ bool stretched = rust_keystore_stretch_retained_seed_encryption_key(
+ rust_util_bytes(
+ _unstretched_retained_seed_encryption_key,
+ sizeof(_unstretched_retained_seed_encryption_key)),
"keystore_retained_seed_access_in",
"keystore_retained_seed_access_out",
- retained_seed_encryption_key);
- if (result != KEYSTORE_OK) {
- return result;
+ rust_util_bytes_mut(retained_seed_encryption_key, sizeof(retained_seed_encryption_key)));
+ if (!stretched) {
+ return KEYSTORE_ERR_STRETCH_RETAINED_SEED_KEY;
}
size_t len = seed_len + 64;
if (!cipher_aes_hmac_encrypt(
@@ -299,11 +288,15 @@ USE_RESULT static bool _retain_bip39_seed(const uint8_t* bip39_seed)
#endif
uint8_t retained_bip39_seed_encryption_key[32] = {0};
UTIL_CLEANUP_32(retained_bip39_seed_encryption_key);
- if (keystore_stretch_retained_seed_encryption_key(
- _unstretched_retained_bip39_seed_encryption_key,
+ if (!rust_keystore_stretch_retained_seed_encryption_key(
+ rust_util_bytes(
+ _unstretched_retained_bip39_seed_encryption_key,
+ sizeof(_unstretched_retained_bip39_seed_encryption_key)),
"keystore_retained_bip39_seed_access_in",
"keystore_retained_bip39_seed_access_out",
- retained_bip39_seed_encryption_key) != KEYSTORE_OK) {
+ rust_util_bytes_mut(
+ retained_bip39_seed_encryption_key,
+ sizeof(retained_bip39_seed_encryption_key)))) {
return false;
}
size_t len = sizeof(_retained_bip39_seed_encrypted);
diff --git a/src/keystore.h b/src/keystore.h
index 9fcf71c..c37a30d 100644
--- a/src/keystore.h
+++ b/src/keystore.h
@@ -41,6 +41,7 @@ typedef enum {
KEYSTORE_ERR_HASH,
KEYSTORE_ERR_ENCRYPT,
KEYSTORE_ERR_DECRYPT,
+ KEYSTORE_ERR_STRETCH_RETAINED_SEED_KEY,
} keystore_error_t;
/**
@@ -62,12 +63,6 @@ USE_RESULT bool keystore_copy_seed(uint8_t* seed_out, size_t* length_out);
*/
USE_RESULT bool keystore_copy_bip39_seed(uint8_t* bip32_seed_out);
-USE_RESULT keystore_error_t keystore_stretch_retained_seed_encryption_key(
- const uint8_t* encryption_key,
- const char* purpose_in,
- const char* purpose_out,
- uint8_t* out);
-
/**
* Restores a seed. This also unlocks the keystore with this seed.
* @param[in] seed The seed that is to be restored.
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index 7cf5a96..4b46901 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -19,13 +19,13 @@ use alloc::string::String;
use alloc::vec::Vec;
use crate::bip32;
-use bitbox02::keystore;
+use bitbox02::{keystore, securechip};
use util::bip32::HARDENED;
use crate::secp256k1::SECP256K1;
-use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha512};
+use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256, sha512};
/// Returns the keystore's seed encoded as a BIP-39 mnemonic.
pub fn get_bip39_mnemonic() -> Result<zeroize::Zeroizing<String>, ()> {
@@ -138,7 +138,53 @@ pub fn stretch_retained_seed_encryption_key(
purpose_in: &str,
purpose_out: &str,
) -> Result<zeroize::Zeroizing<Vec<u8>>, keystore::Error> {
- keystore::stretch_retained_seed_encryption_key(encryption_key, purpose_in, purpose_out)
+ let salted_in =
+ crate::salt::hash_data(encryption_key, purpose_in).map_err(|_| keystore::Error::Salt)?;
+
+ let kdf = securechip::kdf(salted_in.as_slice()).map_err(|err| match err {
+ securechip::Error::SecureChip(sc_err) => keystore::Error::SecureChip(sc_err as i32),
+ securechip::Error::Status(status) => keystore::Error::SecureChip(status),
+ })?;
+
+ let salted_out =
+ crate::salt::hash_data(encryption_key, purpose_out).map_err(|_| keystore::Error::Salt)?;
+
+ let mut engine = HmacEngine::<sha256::Hash>::new(salted_out.as_slice());
+ engine.input(kdf.as_slice());
+ let stretched = Hmac::<sha256::Hash>::from_engine(engine).to_byte_array();
+
+ Ok(zeroize::Zeroizing::new(stretched.to_vec()))
+}
+
+/// # Safety
+///
+/// `encryption_key` must refer to a 32-byte buffer and `out` must have space for 32 bytes.
+/// `purpose_in` and `purpose_out` must be null-terminated C strings.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_keystore_stretch_retained_seed_encryption_key(
+ encryption_key: util::bytes::Bytes,
+ purpose_in: *const core::ffi::c_char,
+ purpose_out: *const core::ffi::c_char,
+ mut out: util::bytes::BytesMut,
+) -> bool {
+ let encryption_key: [u8; 32] = match encryption_key.as_ref().try_into() {
+ Ok(key) => key,
+ Err(_) => return false,
+ };
+ let purpose_in = unsafe { bitbox02::util::str_from_null_terminated_ptr(purpose_in) };
+ let purpose_out = unsafe { bitbox02::util::str_from_null_terminated_ptr(purpose_out) };
+ let (purpose_in, purpose_out) = match (purpose_in, purpose_out) {
+ (Ok(purpose_in), Ok(purpose_out)) => (purpose_in, purpose_out),
+ _ => return false,
+ };
+
+ match stretch_retained_seed_encryption_key(&encryption_key, purpose_in, purpose_out) {
+ Ok(stretched) => {
+ out.as_mut().copy_from_slice(stretched.as_slice());
+ true
+ }
+ Err(_) => false,
+ }
}
fn bip85_entropy(keypath: &[u32]) -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
@@ -485,6 +531,37 @@ mod tests {
assert_eq!(stretched.as_slice(), expected.as_slice());
}
+ #[test]
+ fn test_rust_keystore_stretch_retained_seed_encryption_key_success() {
+ mock_memory();
+ let salt_root =
+ hex::decode("0000000000000000111111111111111122222222222222223333333333333333")
+ .unwrap();
+ bitbox02::memory::set_salt_root(salt_root.as_slice().try_into().unwrap()).unwrap();
+
+ let encryption_key_vec =
+ hex::decode("00112233445566778899aabbccddeeff112233445566778899aabbccddeeff00")
+ .unwrap();
+
+ let mut out = [0u8; 32];
+ let purpose_in = c"keystore_retained_seed_access_in";
+ let purpose_out = c"keystore_retained_seed_access_out";
+
+ let success = unsafe {
+ rust_keystore_stretch_retained_seed_encryption_key(
+ util::bytes::rust_util_bytes(encryption_key_vec.as_ptr(), encryption_key_vec.len()),
+ purpose_in.as_ptr(),
+ purpose_out.as_ptr(),
+ util::bytes::rust_util_bytes_mut(out.as_mut_ptr(), out.len()),
+ )
+ };
+ assert!(success);
+ let expected =
+ hex::decode("b6b20683810aee16b5603ae95d14eaae5ae2c8d9df9b66e1b67c698e627bb208")
+ .unwrap();
+ assert_eq!(out, expected.as_slice());
+ }
+
#[test]
fn test_stretch_retained_seed_encryption_key_salt_error() {
mock_memory();
diff --git a/src/rust/bitbox02-sys/build.rs b/src/rust/bitbox02-sys/build.rs
index cf0d9f9..22f1879 100644
--- a/src/rust/bitbox02-sys/build.rs
+++ b/src/rust/bitbox02-sys/build.rs
@@ -77,7 +77,6 @@ const ALLOWLIST_FNS: &[&str] = &[
"keystore_get_bip39_word",
"keystore_is_locked",
"keystore_lock",
- "keystore_stretch_retained_seed_encryption_key",
"keystore_mock_unlocked",
"keystore_secp256k1_nonce_commit",
"keystore_secp256k1_sign",
diff --git a/src/rust/bitbox02/src/keystore.rs b/src/rust/bitbox02/src/keystore.rs
index 10807dc..a0f5b23 100644
--- a/src/rust/bitbox02/src/keystore.rs
+++ b/src/rust/bitbox02/src/keystore.rs
@@ -213,27 +213,6 @@ pub fn copy_bip39_seed() -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
}
}
-pub fn stretch_retained_seed_encryption_key(
- encryption_key: &[u8; 32],
- purpose_in: &str,
- purpose_out: &str,
-) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
- let purpose_in_c = crate::util::str_to_cstr_vec(purpose_in).unwrap();
- let purpose_out_c = crate::util::str_to_cstr_vec(purpose_out).unwrap();
- let mut out = zeroize::Zeroizing::new(vec![0u8; 32]);
- match unsafe {
- bitbox02_sys::keystore_stretch_retained_seed_encryption_key(
- encryption_key.as_ptr(),
- purpose_in_c.as_ptr().cast(),
- purpose_out_c.as_ptr().cast(),
- out.as_mut_ptr(),
- )
- } {
- keystore_error_t::KEYSTORE_OK => Ok(out),
- err => Err(err.into()),
- }
-}
-
pub fn bip39_mnemonic_from_seed(seed: &[u8]) -> Result<zeroize::Zeroizing<String>, ()> {
let mnemonic = bip39::Mnemonic::from_entropy(seed).map_err(|_| ())?;
Ok(zeroize::Zeroizing::new(mnemonic.to_string()))
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.