keystore: port retained_seed_hash to Rust
What changed, and why it matters
This commit is a straightforward refactoring: it moves the logic that stores and compares a hash of the device's secret seed from C code to Rust code. There is no change in security behavior visible in the diff; the same hash computation, the same comparison checks, and the same cleanup on lock are preserved. It appears to be part of an ongoing effort to rewrite the keystore in Rust, not a security fix.
No security action required. Treat as normal code-review item; verify Rust implementation matches C behavior (HMAC-SHA256 over seed with salted key, zeroization on lock, abort on mismatch).
Security signals we found
Refactor only: same HMAC-SHA256 seed hash moved from C to Rust
No new trust boundaries or privilege changes
No change to salt, key derivation, or comparison semantics
Lock routine still clears retained seed hash
No vendor mention of security relevance or vulnerability fix
Evidence from the diff
The patch ports retained_seed_hash management from src/keystore.c to src/rust/bitbox02-rust/src/keystore.rs. It removes the C static _retained_seed_hash, _hash_seed(), _check_retained_seed(), keystore_unlock_bip39_check(), keystore_lock(), and keystore_mock_unlocked(), and adds equivalent Rust functions hash_seed(), check_retained_seed(), RETAINED_SEED_HASH, plus a C-export rust_keystore_check_retained_seed(). The HMAC-SHA256 construction with salt label keystore_retain_seed_hash and the unlock-time seed-consistency abort are retained. No algorithmic or access-control changes are evident.
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 +34 / −113
diff --git a/src/keystore.c b/src/keystore.c
index bc39f26..d36163c 100644
--- a/src/keystore.c
+++ b/src/keystore.c
@@ -29,10 +29,6 @@
#include <rust/rust.h>
#include <secp256k1_ecdsa_s2c.h>
-// A hash of the unencrypted retained seed, used for comparing seeds without knowing their
-// plaintext.
-static uint8_t _retained_seed_hash[32] = {0};
-
// Unlocking the keystore take longer than the 500ms watchdog we have setup. Reset the watchdog
// counter to (~7s) to avoid incorrectly assuming we lost communication with the app.
#define LONG_TIMEOUT (-70)
@@ -99,29 +95,12 @@ static keystore_error_t _get_and_decrypt_seed(
return KEYSTORE_OK;
}
-static keystore_error_t _hash_seed(const uint8_t* seed, size_t seed_len, uint8_t* out)
-{
- uint8_t salted_key[32] = {0};
- if (!salt_hash_data(NULL, 0, "keystore_retain_seed_hash", salted_key)) {
- return KEYSTORE_ERR_SALT;
- }
-
- rust_hmac_sha256(salted_key, sizeof(salted_key), seed, seed_len, out);
- return KEYSTORE_OK;
-}
-
USE_RESULT static keystore_error_t _retain_seed(const uint8_t* seed, size_t seed_len)
{
if (!rust_keystore_retain_seed(rust_util_bytes(seed, seed_len))) {
return KEYSTORE_ERR_STRETCH_RETAINED_SEED_KEY;
}
-
- return _hash_seed(seed, seed_len, _retained_seed_hash);
-}
-
-static void _delete_retained_seeds(void)
-{
- util_zero(_retained_seed_hash, sizeof(_retained_seed_hash));
+ return KEYSTORE_OK;
}
keystore_error_t keystore_encrypt_and_store_seed(
@@ -177,23 +156,6 @@ keystore_error_t keystore_encrypt_and_store_seed(
return KEYSTORE_OK;
}
-// Checks if the retained seed matches the passed seed.
-static bool _check_retained_seed(const uint8_t* seed, size_t seed_length)
-{
- if (!rust_keystore_is_unlocked_device()) {
- return false;
- }
- uint8_t seed_hashed[32] = {0};
- UTIL_CLEANUP_32(seed_hashed);
- if (_hash_seed(seed, seed_length, seed_hashed) != KEYSTORE_OK) {
- return false;
- }
- if (!MEMEQ(seed_hashed, _retained_seed_hash, sizeof(_retained_seed_hash))) {
- return false;
- }
- return true;
-}
-
keystore_error_t keystore_unlock(
const char* password,
uint8_t* remaining_attempts_out,
@@ -229,7 +191,7 @@ keystore_error_t keystore_unlock(
if (result == KEYSTORE_OK) {
if (rust_keystore_is_unlocked_device()) {
// Already unlocked. Fail if the seed changed under our feet (should never happen).
- if (!_check_retained_seed(seed, seed_len)) {
+ if (!rust_keystore_check_retained_seed(rust_util_bytes(seed, seed_len))) {
Abort("Seed has suddenly changed. This should never happen.");
}
} else {
@@ -258,24 +220,6 @@ keystore_error_t keystore_unlock(
return result;
}
-bool keystore_unlock_bip39_check(const uint8_t* seed, size_t seed_length)
-{
- if (!rust_keystore_is_unlocked_device()) {
- return false;
- }
-
- if (!_check_retained_seed(seed, seed_length)) {
- return false;
- }
-
- return true;
-}
-
-void keystore_lock(void)
-{
- _delete_retained_seeds();
-}
-
bool keystore_is_locked(void)
{
bool unlocked = rust_keystore_is_unlocked_device() && rust_keystore_is_unlocked_bip39();
@@ -324,14 +268,3 @@ bool keystore_secp256k1_sign(
}
return true;
}
-
-#ifdef TESTING
-void keystore_mock_unlocked(const uint8_t* seed, size_t seed_len)
-{
- if (seed != NULL) {
- if (_retain_seed(seed, seed_len) != KEYSTORE_OK) {
- Abort("couldn't retain seed");
- }
- }
-}
-#endif
diff --git a/src/keystore.h b/src/keystore.h
index f5de6dc..b1d9903 100644
--- a/src/keystore.h
+++ b/src/keystore.h
@@ -81,20 +81,6 @@ USE_RESULT keystore_error_t keystore_unlock(
uint8_t* seed_out,
size_t* seed_len_out);
-/**
- * Checks if bip39 unlocking can be performed. It can be performed if `keystore_unlock()`
- * successfully and the input seed matches the keystore seed (i.e. must match the output
- * of `keystore_copy_seed()`).
- * @param[in] seed the input seed to BIP39.
- * @param[in] seed_length the size of the seed
- */
-USE_RESULT bool keystore_unlock_bip39_check(const uint8_t* seed, size_t seed_length);
-
-/**
- * Locks the keystore (resets to state before `keystore_unlock()`).
- */
-void keystore_lock(void);
-
/**
* @return false if the keystore is unlocked (keystore_unlock() followed by
* keystore_unlock_bip39()), true otherwise.
@@ -159,11 +145,4 @@ USE_RESULT bool keystore_secp256k1_sign(
uint8_t* sig_compact_out,
int* recid_out);
-#ifdef TESTING
-/**
- * convenience to mock the keystore state (locked, seed) in tests.
- */
-void keystore_mock_unlocked(const uint8_t* seed, size_t seed_len);
-#endif
-
#endif
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index 836bd3d..09431d0 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -103,6 +103,9 @@ impl RetainedEncryptedBuffer {
// Stores the encrypted seed after unlock.
static RETAINED_SEED: SyncCell<Option<RetainedEncryptedBuffer>> = SyncCell::new(None);
+// A hash of the unencrypted retained seed, used for comparing seeds without knowing their
+// plaintext.
+static RETAINED_SEED_HASH: SyncCell<Option<[u8; 32]>> = SyncCell::new(None);
// Stores the encrypted BIP-39 seed after bip39-unlock.
static RETAINED_BIP39_SEED: SyncCell<Option<RetainedEncryptedBuffer>> = SyncCell::new(None);
@@ -110,9 +113,9 @@ static ROOT_FINGERPRINT: SyncCell<Option<[u8; 4]>> = SyncCell::new(None);
/// Locks the keystore (resets to state before `unlock()`).
pub fn lock() {
- keystore::_lock();
ROOT_FINGERPRINT.write(None);
RETAINED_SEED.write(None);
+ RETAINED_SEED_HASH.write(None);
RETAINED_BIP39_SEED.write(None);
}
@@ -138,6 +141,15 @@ fn verify_seed(encryption_key: &[u8], expected_seed: &[u8]) -> bool {
decrypted.as_slice() == expected_seed
}
+fn hash_seed(seed: &[u8]) -> Result<[u8; 32], Error> {
+ let salted_key =
+ crate::salt::hash_data(&[], "keystore_retain_seed_hash").map_err(|_| Error::Salt)?;
+
+ let mut engine = HmacEngine::<sha256::Hash>::new(salted_key.as_slice());
+ engine.input(seed);
+ Ok(Hmac::<sha256::Hash>::from_engine(engine).to_byte_array())
+}
+
fn retain_seed(seed: &[u8]) -> Result<(), Error> {
// TODO: temporary inline mocked value for testing until we are able to pass through the HAL
// instance properly.
@@ -157,6 +169,18 @@ fn retain_seed(seed: &[u8]) -> Result<(), Error> {
seed,
"keystore_retained_seed_access",
)?));
+ RETAINED_SEED_HASH.write(Some(hash_seed(seed)?));
+ Ok(())
+}
+
+// Checks if the retained seed matches the passed seed.
+fn check_retained_seed(seed: &[u8]) -> Result<(), ()> {
+ if RETAINED_SEED.read().is_none() {
+ return Err(());
+ }
+ if hash_seed(seed).map_err(|_| ())? != RETAINED_SEED_HASH.read().ok_or(())? {
+ return Err(());
+ }
Ok(())
}
@@ -174,7 +198,7 @@ pub async fn unlock_bip39(
mnemonic_passphrase: &str,
yield_now: impl AsyncFn(),
) -> Result<(), Error> {
- keystore::unlock_bip39_check(seed)?;
+ check_retained_seed(seed).map_err(|_| Error::CannotUnlockBIP39)?;
let (bip39_seed, root_fingerprint) =
crate::bip39::derive_seed(seed, mnemonic_passphrase, &yield_now).await;
@@ -397,6 +421,11 @@ pub extern "C" fn rust_keystore_is_unlocked_bip39() -> bool {
RETAINED_BIP39_SEED.read().is_some()
}
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_keystore_check_retained_seed(seed: util::bytes::Bytes) -> bool {
+ check_retained_seed(seed.as_ref()).is_ok()
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn rust_keystore_retain_seed(seed: util::bytes::Bytes) -> bool {
retain_seed(seed.as_ref()).is_ok()
@@ -601,7 +630,7 @@ pub mod testing {
/// This mocks an unlocked keystore with the given bip39 recovery words and bip39 passphrase.
pub fn mock_unlocked_using_mnemonic(mnemonic: &str, passphrase: &str) {
let seed = crate::bip39::mnemonic_to_seed(mnemonic).unwrap();
- bitbox02::keystore::mock_unlocked(&seed);
+ super::retain_seed(&seed).unwrap();
util::bb02_async::block_on(super::unlock_bip39(
&mut crate::hal::testing::TestingRandom::new(),
&seed,
diff --git a/src/rust/bitbox02-sys/build.rs b/src/rust/bitbox02-sys/build.rs
index 5ae05d3..fcec222 100644
--- a/src/rust/bitbox02-sys/build.rs
+++ b/src/rust/bitbox02-sys/build.rs
@@ -76,12 +76,9 @@ const ALLOWLIST_FNS: &[&str] = &[
"keystore_encrypt_and_store_seed",
"keystore_get_bip39_word",
"keystore_is_locked",
- "keystore_lock",
- "keystore_mock_unlocked",
"keystore_secp256k1_nonce_commit",
"keystore_secp256k1_sign",
"keystore_unlock",
- "keystore_unlock_bip39_check",
"label_create",
"gmtime",
"memory_set_salt_root",
diff --git a/src/rust/bitbox02/src/keystore.rs b/src/rust/bitbox02/src/keystore.rs
index b3225ba..c3707a7 100644
--- a/src/rust/bitbox02/src/keystore.rs
+++ b/src/rust/bitbox02/src/keystore.rs
@@ -96,18 +96,6 @@ pub fn _unlock(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
}
}
-pub fn _lock() {
- unsafe { bitbox02_sys::keystore_lock() }
-}
-
-pub fn unlock_bip39_check(seed: &[u8]) -> Result<(), Error> {
- if unsafe { bitbox02_sys::keystore_unlock_bip39_check(seed.as_ptr(), seed.len()) } {
- Ok(())
- } else {
- Err(Error::CannotUnlockBIP39)
- }
-}
-
pub struct SignResult {
pub signature: [u8; 64],
pub recid: u8,
@@ -175,8 +163,3 @@ pub fn _encrypt_and_store_seed(seed: &[u8], password: &str) -> Result<(), Error>
err => Err(err.into()),
}
}
-
-#[cfg(feature = "testing")]
-pub fn mock_unlocked(seed: &[u8]) {
- unsafe { bitbox02_sys::keystore_mock_unlocked(seed.as_ptr(), seed.len() as _) }
-}
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.