rust/keystore: wrap unlock() in bitbox02-rust
What changed, and why it matters
This commit is a routine internal code reorganization in the BitBox02 firmware. It moves the keystore `unlock()` function and its tests from one Rust module to another, renames the original C wrapper to `_unlock()` so the compiler catches any missed references, and exposes a constant for maximum unlock attempts. There is no change to security behavior, no bug fix, and no indication of a vulnerability.
No security action required. This is a refactoring commit. Standard code review and regression testing are sufficient.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch refactors the Rust keystore API: bitbox02::keystore::unlock() is renamed to bitbox02::keystore::_unlock() and re-exported as bitbox02_rust::keystore::unlock(). Callers in workflow/unlock.rs are updated to use the new path. Unit tests for unlock() and test_seeds() are moved from bitbox02/src/keystore.rs to bitbox02-rust/src/keystore.rs, with minor adjustments (e.g., using bitbox02::memory::MAX_UNLOCK_ATTEMPTS instead of bitbox02_sys::MAX_UNLOCK_ATTEMPTS). A test-only helper test_get_retained_seed_encrypted() is added. The functional behavior of unlock, seed retention, password checks, and max-attempts reset is unchanged.
Changed components
src/rust/bitbox02-rust/src/keystore.rssrc/rust/bitbox02-rust/src/workflow/unlock.rssrc/rust/bitbox02/src/keystore.rssrc/rust/bitbox02/src/memory.rsInspect captured patch +136 / −125
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index c60f65f..85d4ae3 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -19,6 +19,7 @@ use alloc::string::String;
use alloc::vec::Vec;
use crate::bip32;
+pub use bitbox02::keystore::Error;
pub use bitbox02::keystore::SignResult;
use bitbox02::{keystore, securechip};
@@ -31,7 +32,7 @@ use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256, sha512};
/// Length of a compressed secp256k1 pubkey.
const EC_PUBLIC_KEY_LEN: usize = 33;
-/// Locks the keystore (resets to state before `keystore::unlock()`).
+/// Locks the keystore (resets to state before `unlock()`).
pub fn lock() {
keystore::_lock();
}
@@ -41,6 +42,10 @@ pub fn is_locked() -> bool {
keystore::_is_locked()
}
+pub fn unlock(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
+ keystore::_unlock(password)
+}
+
/// Returns a copy of the retained seed. Errors if the keystore is locked.
pub fn copy_seed() -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
keystore::_copy_seed()
@@ -156,17 +161,16 @@ pub fn stretch_retained_seed_encryption_key(
encryption_key: &[u8; 32],
purpose_in: &str,
purpose_out: &str,
-) -> Result<zeroize::Zeroizing<Vec<u8>>, keystore::Error> {
- let salted_in =
- crate::salt::hash_data(encryption_key, purpose_in).map_err(|_| keystore::Error::Salt)?;
+) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
+ let salted_in = crate::salt::hash_data(encryption_key, purpose_in).map_err(|_| 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),
+ securechip::Error::SecureChip(sc_err) => Error::SecureChip(sc_err as i32),
+ securechip::Error::Status(status) => Error::SecureChip(status),
})?;
let salted_out =
- crate::salt::hash_data(encryption_key, purpose_out).map_err(|_| keystore::Error::Salt)?;
+ crate::salt::hash_data(encryption_key, purpose_out).map_err(|_| Error::Salt)?;
let mut engine = HmacEngine::<sha256::Hash>::new(salted_out.as_slice());
engine.input(kdf.as_slice());
@@ -458,6 +462,72 @@ mod tests {
assert!(is_locked());
}
+ #[test]
+ fn test_unlock() {
+ mock_memory();
+ lock();
+
+ assert!(matches!(unlock("password"), Err(Error::Unseeded)));
+
+ let seed = hex::decode("cb33c20cea62a5c277527e2002da82e6e2b37450a755143a540a54cea8da9044")
+ .unwrap();
+
+ let mock_salt_root =
+ hex::decode("3333333333333333444444444444444411111111111111112222222222222222")
+ .unwrap();
+ bitbox02::memory::set_salt_root(mock_salt_root.as_slice().try_into().unwrap()).unwrap();
+
+ assert!(keystore::encrypt_and_store_seed(&seed, "password").is_ok());
+ lock();
+
+ // First call: unlock. The first one does a seed rentention (1 securechip event).
+ bitbox02::securechip::fake_event_counter_reset();
+ assert_eq!(unlock("password").unwrap().as_slice(), seed);
+ assert_eq!(bitbox02::securechip::fake_event_counter(), 6);
+
+ // Loop to check that unlocking works while unlocked.
+ for _ in 0..2 {
+ // Further calls perform a password check.The password check does not do the retention
+ // so it ends up needing one secure chip operation less.
+ bitbox02::securechip::fake_event_counter_reset();
+ assert_eq!(unlock("password").unwrap().as_slice(), seed);
+ assert_eq!(bitbox02::securechip::fake_event_counter(), 5);
+ }
+
+ // Also check that the retained seed was encrypted with the expected encryption key.
+ let decrypted = {
+ let retained_seed_encrypted: &[u8] = keystore::test_get_retained_seed_encrypted();
+ let expected_retained_seed_secret =
+ hex::decode("b156be416530c6fc00018844161774a3546a53ac6dd4a0462608838e216008f7")
+ .unwrap();
+ bitbox_aes::decrypt_with_hmac(&expected_retained_seed_secret, retained_seed_encrypted)
+ .unwrap()
+ };
+ assert_eq!(decrypted.as_slice(), seed.as_slice());
+
+ // First 9 wrong attempts.
+ for i in 1..bitbox02::memory::MAX_UNLOCK_ATTEMPTS {
+ assert!(matches!(
+ unlock("invalid password"),
+ Err(Error::IncorrectPassword { remaining_attempts }) if remaining_attempts
+ == bitbox02::memory::MAX_UNLOCK_ATTEMPTS - i
+ ));
+ // Still seeded.
+ assert!(bitbox02::memory::is_seeded());
+ // Wrong password does not lock the keystore again if already unlocked.
+ assert!(copy_seed().is_ok());
+ }
+ // Last attempt, triggers reset.
+ assert!(matches!(
+ unlock("invalid password"),
+ Err(Error::MaxAttemptsExceeded),
+ ));
+ // Last wrong attempt locks & resets. There is no more seed.
+ assert!(!bitbox02::memory::is_seeded());
+ assert!(copy_seed().is_err());
+ assert!(matches!(unlock("password"), Err(Error::Unseeded)));
+ }
+
#[test]
fn test_secp256k1_get_private_key() {
lock();
@@ -696,7 +766,7 @@ mod tests {
let encryption_key = [0u8; 32];
let result =
stretch_retained_seed_encryption_key(&encryption_key, "purpose_in", "purpose_out");
- assert!(matches!(result, Err(keystore::Error::Salt)));
+ assert!(matches!(result, Err(Error::Salt)));
}
#[test]
@@ -979,4 +1049,48 @@ mod tests {
.is_ok()
);
}
+
+ // Functional test to store seeds, lock/unlock, retrieve seed.
+ #[test]
+ fn test_seeds() {
+ let seed = hex::decode("cb33c20cea62a5c277527e2002da82e6e2b37450a755143a540a54cea8da9044")
+ .unwrap();
+
+ for seed_size in [16, 24, 32] {
+ mock_memory();
+ lock();
+
+ // Can repeat until initialized - initialized means backup has been created.
+ for _ in 0..2 {
+ assert!(keystore::encrypt_and_store_seed(&seed[..seed_size], "foo").is_ok());
+ }
+ // Also unlocks, so we can get the retained seed.
+ assert_eq!(copy_seed().unwrap().as_slice(), &seed[..seed_size]);
+
+ lock();
+ // Can't get seed before unlock.
+ assert!(copy_seed().is_err());
+
+ // Wrong password.
+ assert!(matches!(
+ unlock("bar"),
+ Err(Error::IncorrectPassword {
+ remaining_attempts: 9
+ })
+ ));
+
+ // Correct password. First time: unlock. After unlock, it becomes a password check.
+ for _ in 0..3 {
+ assert_eq!(unlock("foo").unwrap().as_slice(), &seed[..seed_size]);
+ }
+ assert_eq!(copy_seed().unwrap().as_slice(), &seed[..seed_size]);
+
+ // Can't store new seed once initialized.
+ bitbox02::memory::set_initialized().unwrap();
+ assert!(matches!(
+ keystore::encrypt_and_store_seed(&seed[..seed_size], "foo"),
+ Err(Error::Memory)
+ ));
+ }
+ }
}
diff --git a/src/rust/bitbox02-rust/src/workflow/unlock.rs b/src/rust/bitbox02-rust/src/workflow/unlock.rs
index 9e85e10..70ecc29 100644
--- a/src/rust/bitbox02-rust/src/workflow/unlock.rs
+++ b/src/rust/bitbox02-rust/src/workflow/unlock.rs
@@ -90,9 +90,9 @@ pub async fn unlock_keystore(
)
.await?;
- match keystore::unlock(&password) {
+ match crate::keystore::unlock(&password) {
Ok(seed) => Ok(seed),
- Err(keystore::Error::IncorrectPassword { remaining_attempts }) => {
+ Err(crate::keystore::Error::IncorrectPassword { remaining_attempts }) => {
let msg = match remaining_attempts {
1 => "Wrong password\n1 try remains".into(),
n => format!("Wrong password\n{} tries remain", n),
diff --git a/src/rust/bitbox02/src/keystore.rs b/src/rust/bitbox02/src/keystore.rs
index e722896..1c4e9ac 100644
--- a/src/rust/bitbox02/src/keystore.rs
+++ b/src/rust/bitbox02/src/keystore.rs
@@ -67,7 +67,7 @@ impl core::convert::From<keystore_error_t> for Error {
}
}
-pub fn unlock(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
+pub fn _unlock(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
let mut remaining_attempts: u8 = 0;
let mut securechip_result: i32 = 0;
let mut seed = zeroize::Zeroizing::new([0u8; MAX_SEED_LENGTH].to_vec());
@@ -139,6 +139,15 @@ async fn derive_bip39_seed(
(bip39_seed, root_fingerprint)
}
+#[cfg(feature = "testing")]
+pub fn test_get_retained_seed_encrypted() -> &'static [u8] {
+ unsafe {
+ let mut len = 0usize;
+ let ptr = bitbox02_sys::keystore_test_get_retained_seed_encrypted(&mut len);
+ core::slice::from_raw_parts(ptr, len)
+ }
+}
+
/// Unlocks the bip39 seed. The input seed must be the keystore seed (i.e. must match the output
/// of `keystore_copy_seed()`).
/// `mnemonic_passphrase` is the bip39 passphrase used in the derivation. Use the empty string if no
@@ -361,76 +370,6 @@ mod tests {
assert!(bip39_mnemonic_from_seed(b"foo").is_err());
}
- #[test]
- fn test_unlock() {
- mock_memory();
- _lock();
-
- assert!(matches!(unlock("password"), Err(Error::Unseeded)));
-
- let seed = hex::decode("cb33c20cea62a5c277527e2002da82e6e2b37450a755143a540a54cea8da9044")
- .unwrap();
-
- let mock_salt_root =
- hex::decode("3333333333333333444444444444444411111111111111112222222222222222")
- .unwrap();
- crate::memory::set_salt_root(mock_salt_root.as_slice().try_into().unwrap()).unwrap();
-
- assert!(encrypt_and_store_seed(&seed, "password").is_ok());
- _lock();
-
- // First call: unlock. The first one does a seed rentention (1 securechip event).
- crate::securechip::fake_event_counter_reset();
- assert_eq!(unlock("password").unwrap().as_slice(), seed);
- assert_eq!(crate::securechip::fake_event_counter(), 6);
-
- // Loop to check that unlocking works while unlocked.
- for _ in 0..2 {
- // Further calls perform a password check.The password check does not do the retention
- // so it ends up needing one secure chip operation less.
- crate::securechip::fake_event_counter_reset();
- assert_eq!(unlock("password").unwrap().as_slice(), seed);
- assert_eq!(crate::securechip::fake_event_counter(), 5);
- }
-
- // Also check that the retained seed was encrypted with the expected encryption key.
- let decrypted = {
- let retained_seed_encrypted: &[u8] = unsafe {
- let mut len = 0usize;
- let ptr = bitbox02_sys::keystore_test_get_retained_seed_encrypted(&mut len);
- core::slice::from_raw_parts(ptr, len)
- };
- let expected_retained_seed_secret =
- hex::decode("b156be416530c6fc00018844161774a3546a53ac6dd4a0462608838e216008f7")
- .unwrap();
- bitbox_aes::decrypt_with_hmac(&expected_retained_seed_secret, retained_seed_encrypted)
- .unwrap()
- };
- assert_eq!(decrypted.as_slice(), seed.as_slice());
-
- // First 9 wrong attempts.
- for i in 1..bitbox02_sys::MAX_UNLOCK_ATTEMPTS {
- assert!(matches!(
- unlock("invalid password"),
- Err(Error::IncorrectPassword { remaining_attempts }) if remaining_attempts
- == (bitbox02_sys::MAX_UNLOCK_ATTEMPTS - i) as u8
- ));
- // Still seeded.
- assert!(crate::memory::is_seeded());
- // Wrong password does not lock the keystore again if already unlocked.
- assert!(_copy_seed().is_ok());
- }
- // Last attempt, triggers reset.
- assert!(matches!(
- unlock("invalid password"),
- Err(Error::MaxAttemptsExceeded),
- ));
- // Last wrong attempt locks & resets. There is no more seed.
- assert!(!crate::memory::is_seeded());
- assert!(_copy_seed().is_err());
- assert!(matches!(unlock("password"), Err(Error::Unseeded)));
- }
-
#[test]
fn test_derive_bip39_seed() {
struct Test {
@@ -637,48 +576,4 @@ mod tests {
assert!(encrypt_and_store_seed(&seed2, "password").is_ok());
assert_eq!(_copy_seed().unwrap().as_slice(), &seed2);
}
-
- // Functional test to store seeds, lock/unlock, retrieve seed.
- #[test]
- fn test_seeds() {
- let seed = hex::decode("cb33c20cea62a5c277527e2002da82e6e2b37450a755143a540a54cea8da9044")
- .unwrap();
-
- for seed_size in [16, 24, 32] {
- mock_memory();
- _lock();
-
- // Can repeat until initialized - initialized means backup has been created.
- for _ in 0..2 {
- assert!(encrypt_and_store_seed(&seed[..seed_size], "foo").is_ok());
- }
- // Also unlocks, so we can get the retained seed.
- assert_eq!(_copy_seed().unwrap().as_slice(), &seed[..seed_size]);
-
- _lock();
- // Can't get seed before unlock.
- assert!(_copy_seed().is_err());
-
- // Wrong password.
- assert!(matches!(
- unlock("bar"),
- Err(Error::IncorrectPassword {
- remaining_attempts: 9
- })
- ));
-
- // Correct password. First time: unlock. After unlock, it becomes a password check.
- for _ in 0..3 {
- assert_eq!(unlock("foo").unwrap().as_slice(), &seed[..seed_size]);
- }
- assert_eq!(_copy_seed().unwrap().as_slice(), &seed[..seed_size]);
-
- // Can't store new seed once initialized.
- crate::memory::set_initialized().unwrap();
- assert!(matches!(
- encrypt_and_store_seed(&seed[..seed_size], "foo"),
- Err(Error::Memory)
- ));
- }
- }
}
diff --git a/src/rust/bitbox02/src/memory.rs b/src/rust/bitbox02/src/memory.rs
index fa21ab8..ff52f68 100644
--- a/src/rust/bitbox02/src/memory.rs
+++ b/src/rust/bitbox02/src/memory.rs
@@ -17,6 +17,8 @@ extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
+pub const MAX_UNLOCK_ATTEMPTS: u8 = bitbox02_sys::MAX_UNLOCK_ATTEMPTS as u8;
+
// deduct one for the null terminator.
pub const DEVICE_NAME_MAX_LEN: usize = bitbox02_sys::MEMORY_DEVICE_NAME_MAX_LEN as usize - 1;
Why this scored 15/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.