keystore: port keystore_unlock to Rust
What changed, and why it matters
This commit rewrites the wallet-unlock routine from C into Rust. It is a language port/refactor: the same password-stretching, seed-decryption, attempt-counting, and device-reset logic is preserved. There is no indication in the commit or supplied references that this fixes a security bug or introduces a vulnerability. It is a routine code-quality/migration change.
No security action required. Treat as normal code-review item; verify the Rust port preserves the original semantics and that tests cover unlock success, wrong-password, and max-attempts paths.
Security signals we found
Refactor/port of sensitive unlock routine to a memory-safe language (Rust)
Sensitive material (seed, stretched secret) is handled with zeroize::Zeroizing in the new Rust code
Attempt-counter and reset logic is preserved
No new trust boundary, input validation change, or cryptographic change is introduced
Evidence from the diff
The patch removes the C implementation of keystore_unlock() and the keystore_error_t enum, and moves the logic into bitbox02-rust/src/keystore.rs. The Rust version keeps the same behavior: checks is_seeded(), enforces MAX_UNLOCK_ATTEMPTS, stretches the password via the secure chip, decrypts the seed with AES-HMAC, validates seed length (16/24/32 bytes), retains the seed, resets failed-attempt counters on success, and resets the device after too many failures. Bindings for the removed C helpers are also cleaned up. No security-relevant semantic change is visible in the diff.
Changed components
src/keystore.csrc/keystore.hsrc/rust/bitbox02-rust/src/keystore.rssrc/rust/bitbox02-sys/build.rssrc/rust/bitbox02/src/keystore.rssrc/rust/bitbox02/src/memory.rsInspect captured patch +56 / −250
diff --git a/src/keystore.c b/src/keystore.c
index 96dd4be..9d6b52e 100644
--- a/src/keystore.c
+++ b/src/keystore.c
@@ -28,138 +28,6 @@
#include <rust/rust.h>
#include <secp256k1_ecdsa_s2c.h>
-// 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)
-
-/**
- * We allow seeds of 16, 24 or 32 bytes.
- */
-static bool _validate_seed_length(size_t seed_len)
-{
- return seed_len == 16 || seed_len == 24 || seed_len == 32;
-}
-
-/**
- * Retrieves the encrypted seed and attempts to decrypt it using the password.
- *
- * `securechip_result_out`, if not NULL, will contain the error code from `securechip_kdf()` if
- * there was a secure chip error, and 0 otherwise.
- */
-static keystore_error_t _get_and_decrypt_seed(
- const char* password,
- uint8_t* decrypted_seed_out,
- size_t* decrypted_seed_len_out,
- int* securechip_result_out)
-{
- uint8_t encrypted_seed_and_hmac[96];
- UTIL_CLEANUP_32(encrypted_seed_and_hmac);
- uint8_t encrypted_len;
- if (!memory_get_encrypted_seed_and_hmac(encrypted_seed_and_hmac, &encrypted_len)) {
- return KEYSTORE_ERR_MEMORY;
- }
- uint8_t secret[32];
- UTIL_CLEANUP_32(secret);
- int stretch_result = securechip_stretch_password(password, secret);
- if (stretch_result) {
- if (stretch_result == SC_ERR_INCORRECT_PASSWORD) {
- // Our Optiga securechip implementation fails password stretching if the password is
- // wrong, so we can early-abort here. The ATECC stretches the password without checking
- // if the password is correct, and we determine if it is correct in the seed decryption
- // step below.
- return KEYSTORE_ERR_INCORRECT_PASSWORD;
- }
- if (securechip_result_out != NULL) {
- *securechip_result_out = stretch_result;
- }
- return KEYSTORE_ERR_SECURECHIP;
- }
- if (encrypted_len < 49) {
- Abort("_get_and_decrypt_seed: underflow / zero size");
- }
- size_t decrypted_len = encrypted_len - 48;
- uint8_t decrypted[decrypted_len];
- bool password_correct = cipher_aes_hmac_decrypt(
- encrypted_seed_and_hmac, encrypted_len, decrypted, &decrypted_len, secret);
- if (!password_correct) {
- return KEYSTORE_ERR_INCORRECT_PASSWORD;
- }
- if (!_validate_seed_length(decrypted_len)) {
- util_zero(decrypted, sizeof(decrypted));
- return KEYSTORE_ERR_SEED_SIZE;
- }
- *decrypted_seed_len_out = decrypted_len;
- memcpy(decrypted_seed_out, decrypted, decrypted_len);
-
- 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 KEYSTORE_OK;
-}
-
-keystore_error_t keystore_unlock(
- const char* password,
- int* securechip_result_out,
- uint8_t* seed_out,
- size_t* seed_len_out)
-{
- if (!memory_is_seeded()) {
- return KEYSTORE_ERR_UNSEEDED;
- }
- uint8_t failed_attempts = bitbox02_smarteeprom_get_unlock_attempts();
- if (failed_attempts >= MAX_UNLOCK_ATTEMPTS) {
- /*
- * We reset the device as soon as the MAX_UNLOCK_ATTEMPTSth attempt
- * is made. So we should never enter this branch...
- * This is just an extraordinary measure for added resilience.
- */
- reset_reset(false);
- return KEYSTORE_ERR_MAX_ATTEMPTS_EXCEEDED;
- }
- usb_processing_timeout_reset(LONG_TIMEOUT);
-
- bitbox02_smarteeprom_increment_unlock_attempts();
- uint8_t seed[KEYSTORE_MAX_SEED_LENGTH] = {0};
- UTIL_CLEANUP_32(seed);
- size_t seed_len;
- keystore_error_t result =
- _get_and_decrypt_seed(password, seed, &seed_len, securechip_result_out);
- if (result != KEYSTORE_OK) {
- failed_attempts = bitbox02_smarteeprom_get_unlock_attempts();
-
- if (failed_attempts >= MAX_UNLOCK_ATTEMPTS) {
- reset_reset(false);
- return KEYSTORE_ERR_MAX_ATTEMPTS_EXCEEDED;
- }
-
- return result;
- }
-
- if (rust_keystore_is_unlocked_device()) {
- // Already unlocked. Fail if the seed changed under our feet (should never happen).
- if (!rust_keystore_check_retained_seed(rust_util_bytes(seed, seed_len))) {
- Abort("Seed has suddenly changed. This should never happen.");
- }
- } else {
- keystore_error_t retain_seed_result = _retain_seed(seed, seed_len);
- if (retain_seed_result != KEYSTORE_OK) {
- return retain_seed_result;
- }
- }
- bitbox02_smarteeprom_reset_unlock_attempts();
-
- if (seed_out != NULL && seed_len_out != NULL) {
- memcpy(seed_out, seed, seed_len);
- *seed_len_out = seed_len;
- }
- return KEYSTORE_OK;
-}
-
bool keystore_get_bip39_word_stack(uint16_t idx, char* word_out, size_t word_out_size)
{
return rust_get_bip39_word(idx, rust_util_bytes_mut((uint8_t*)word_out, word_out_size));
diff --git a/src/keystore.h b/src/keystore.h
index e2c52d3..99a4a29 100644
--- a/src/keystore.h
+++ b/src/keystore.h
@@ -23,58 +23,11 @@
#include <secp256k1.h>
-#define KEYSTORE_MAX_SEED_LENGTH (32)
#define KEYSTORE_U2F_SEED_LENGTH SHA256_LEN
// Max. length of an xpub string, including the null terminator.
#define XPUB_ENCODED_LEN 113
-typedef enum {
- KEYSTORE_OK,
- KEYSTORE_ERR_INCORRECT_PASSWORD,
- KEYSTORE_ERR_MAX_ATTEMPTS_EXCEEDED,
- KEYSTORE_ERR_UNSEEDED,
- KEYSTORE_ERR_MEMORY,
- KEYSTORE_ERR_SECURECHIP,
- KEYSTORE_ERR_SEED_SIZE,
- KEYSTORE_ERR_SALT,
- KEYSTORE_ERR_HASH,
- KEYSTORE_ERR_ENCRYPT,
- KEYSTORE_ERR_DECRYPT,
- KEYSTORE_ERR_STRETCH_RETAINED_SEED_KEY,
-} keystore_error_t;
-
-/**
- * Restores a seed. This also unlocks the keystore with this seed.
- * @param[in] seed The seed that is to be restored.
- * @param[in] seed_length The length of the seed (max. 32 bytes).
- * @param[in] password The password with which we encrypt the seed.
- */
-/** Unlocks the keystore seed or checks the password:
- * If the keystore is locked, it decrypts and loads the seed, unlocking the keystore:
- * 1) loads the stored seed and tries to decrypt using password.
- * 2) if successful, the bip39 seed should be derived using keystore_unlock_bip39().
- * If the keystore is already unlocked, this function does *not* change the state (can be used to
- * check the password).
- * @param[in] password keystore password, used to decrypt the seed.
- * If it is false, the keystore is not unlocked.
- * @param[out] securechip_result_out, if not NULL, will contain the error code from
- * @param[out] seed_out The seed bytes copied from the retained seed.
- * The buffer should be KEYSTORE_MAX_SEED_LENGTH bytes long. The caller must
- * zero the seed once it is no longer needed.
- * @param[out] seed_len_out The seed length.
- * `securechip_kdf()` if there was a secure chip error, and 0 otherwise.
- * @return
- * - KEYSTORE_OK if they keystore was successfully unlocked
- * - KEYSTORE_ERR_* if unsuccessful.
- * Only call this if memory_is_seeded() returns true.
- */
-USE_RESULT keystore_error_t keystore_unlock(
- const char* password,
- int* securechip_result_out,
- uint8_t* seed_out,
- size_t* seed_len_out);
-
/**
* Retrieves the BIP39 word by index. `word_out` should be of at least 9 bytes long.
*/
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index 0fd3531..9c60755 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -231,8 +231,60 @@ fn check_retained_seed(seed: &[u8]) -> Result<(), ()> {
Ok(())
}
+fn get_and_decrypt_seed(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
+ let encrypted = bitbox02::memory::get_encrypted_seed_and_hmac().map_err(|_| Error::Memory)?;
+ // Our Optiga securechip implementation fails password stretching if the password is
+ // wrong, so it already returns an error here. The ATECC stretches the password without checking
+ // if the password is correct, and we determine if it is correct in the seed decryption
+ // step below.
+ let secret = securechip::stretch_password(password)?;
+ let seed = match bitbox_aes::decrypt_with_hmac(&secret, &encrypted) {
+ Ok(seed) => seed,
+ Err(()) => return Err(Error::IncorrectPassword),
+ };
+
+ if !matches!(seed.len(), 16 | 24 | 32) {
+ return Err(Error::SeedSize);
+ }
+ Ok(seed)
+}
+
pub fn unlock(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
- keystore::_unlock(password)
+ if !bitbox02::memory::is_seeded() {
+ return Err(Error::Unseeded);
+ }
+ if get_remaining_unlock_attempts() == 0 {
+ //
+ // We reset the device as soon as the MAX_UNLOCK_ATTEMPTSth attempt
+ // is made. So we should never enter this branch...
+ // This is just an extraordinary measure for added resilience.
+ //
+ bitbox02::reset(false);
+ return Err(Error::MaxAttemptsExceeded);
+ }
+ bitbox02::usb_processing::timeout_reset(LONG_TIMEOUT);
+ bitbox02::memory::smarteeprom_increment_unlock_attempts();
+ let seed = match get_and_decrypt_seed(password) {
+ Ok(seed) => seed,
+ err @ Err(_) => {
+ if get_remaining_unlock_attempts() == 0 {
+ bitbox02::reset(false);
+ return Err(Error::MaxAttemptsExceeded);
+ }
+ return err;
+ }
+ };
+
+ if RETAINED_SEED.read().is_some() {
+ // Already unlocked. Fail if the seed changed under our feet (should never happen).
+ if check_retained_seed(&seed).is_err() {
+ panic!("Seed has suddenly changed. This should never happen.");
+ }
+ } else {
+ retain_seed(&seed)?;
+ }
+ bitbox02::memory::smarteeprom_reset_unlock_attempts();
+ Ok(seed)
}
/// Returns the number of remaining unlock attempts (calls to `unlock()`) that are allowed before
@@ -461,21 +513,6 @@ pub extern "C" fn rust_keystore_is_locked() -> bool {
is_locked()
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_keystore_is_unlocked_device() -> bool {
- RETAINED_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()
-}
-
fn bip85_entropy(keypath: &[u32]) -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
let priv_key = secp256k1_get_private_key_twice(keypath)?;
diff --git a/src/rust/bitbox02-sys/build.rs b/src/rust/bitbox02-sys/build.rs
index 79ca6b9..b24b73d 100644
--- a/src/rust/bitbox02-sys/build.rs
+++ b/src/rust/bitbox02-sys/build.rs
@@ -27,7 +27,6 @@ const ALLOWLIST_VARS: &[&str] = &[
"font_monogram_5X9",
"font_password_11X12",
"INPUT_STRING_MAX_SIZE",
- "KEYSTORE_MAX_SEED_LENGTH",
"MAX_LABEL_SIZE",
"MAX_PK_SCRIPT_SIZE",
"MAX_UNLOCK_ATTEMPTS",
@@ -92,7 +91,6 @@ const ALLOWLIST_FNS: &[&str] = &[
"keystore_get_bip39_word",
"keystore_secp256k1_nonce_commit",
"keystore_secp256k1_sign",
- "keystore_unlock",
"label_create",
"memory_add_noise_remote_static_pubkey",
"memory_ble_enable",
@@ -192,7 +190,6 @@ const ALLOWLIST_FNS: &[&str] = &[
const RUSTIFIED_ENUMS: &[&str] = &[
"event_types",
- "keystore_error_t",
"keystore_secp256k1_pubkey_format",
"memory_result_t",
"multisig_script_type_t",
diff --git a/src/rust/bitbox02/src/keystore.rs b/src/rust/bitbox02/src/keystore.rs
index 49045ab..259aaf0 100644
--- a/src/rust/bitbox02/src/keystore.rs
+++ b/src/rust/bitbox02/src/keystore.rs
@@ -14,15 +14,10 @@
extern crate alloc;
-use alloc::vec::Vec;
-
use bitcoin::secp256k1::{All, Secp256k1};
-use bitbox02_sys::keystore_error_t;
-
/// Length of a compressed secp256k1 pubkey.
const EC_PUBLIC_KEY_LEN: usize = 33;
-pub const MAX_SEED_LENGTH: usize = bitbox02_sys::KEYSTORE_MAX_SEED_LENGTH as usize;
#[derive(Debug)]
pub enum Error {
@@ -44,57 +39,15 @@ pub enum Error {
impl core::convert::From<crate::securechip::Error> for Error {
fn from(error: crate::securechip::Error) -> Self {
match error {
+ crate::securechip::Error::SecureChip(
+ crate::securechip::SecureChipError::SC_ERR_INCORRECT_PASSWORD,
+ ) => Error::IncorrectPassword,
crate::securechip::Error::SecureChip(sc_err) => Error::SecureChip(sc_err as i32),
crate::securechip::Error::Status(status) => Error::SecureChip(status),
}
}
}
-impl core::convert::From<keystore_error_t> for Error {
- fn from(error: keystore_error_t) -> Self {
- match error {
- keystore_error_t::KEYSTORE_ERR_MAX_ATTEMPTS_EXCEEDED => Error::MaxAttemptsExceeded,
- keystore_error_t::KEYSTORE_ERR_UNSEEDED => Error::Unseeded,
- keystore_error_t::KEYSTORE_ERR_MEMORY => Error::Memory,
- keystore_error_t::KEYSTORE_ERR_SECURECHIP => Error::SecureChip(0),
- keystore_error_t::KEYSTORE_ERR_SEED_SIZE => Error::SeedSize,
- keystore_error_t::KEYSTORE_ERR_SALT => Error::Salt,
- keystore_error_t::KEYSTORE_ERR_HASH => Error::Hash,
- keystore_error_t::KEYSTORE_ERR_ENCRYPT => Error::Encrypt,
- keystore_error_t::KEYSTORE_ERR_DECRYPT => Error::Decrypt,
- keystore_error_t::KEYSTORE_ERR_STRETCH_RETAINED_SEED_KEY => {
- Error::StretchRetainedSeedKey
- }
- _ => panic!("cannot convert error"),
- }
- }
-}
-
-pub fn _unlock(password: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Error> {
- let mut securechip_result: i32 = 0;
- let mut seed = zeroize::Zeroizing::new([0u8; MAX_SEED_LENGTH].to_vec());
- let mut seed_len: usize = 0;
- match unsafe {
- bitbox02_sys::keystore_unlock(
- crate::util::str_to_cstr_vec_zeroizing(password)
- .unwrap()
- .as_ptr()
- .cast(),
- &mut securechip_result,
- seed.as_mut_ptr(),
- &mut seed_len,
- )
- } {
- keystore_error_t::KEYSTORE_OK => {
- seed.truncate(seed_len);
- Ok(seed)
- }
- keystore_error_t::KEYSTORE_ERR_INCORRECT_PASSWORD => Err(Error::IncorrectPassword),
- keystore_error_t::KEYSTORE_ERR_SECURECHIP => Err(Error::SecureChip(securechip_result)),
- err => Err(err.into()),
- }
-}
-
pub struct SignResult {
pub signature: [u8; 64],
pub recid: u8,
diff --git a/src/rust/bitbox02/src/memory.rs b/src/rust/bitbox02/src/memory.rs
index 38c7cb4..c9d2e78 100644
--- a/src/rust/bitbox02/src/memory.rs
+++ b/src/rust/bitbox02/src/memory.rs
@@ -174,14 +174,12 @@ pub fn smarteeprom_get_unlock_attempts() -> u8 {
unsafe { bitbox02_sys::bitbox02_smarteeprom_get_unlock_attempts() }
}
-#[cfg(feature = "testing")]
pub fn smarteeprom_increment_unlock_attempts() {
unsafe {
bitbox02_sys::bitbox02_smarteeprom_increment_unlock_attempts();
}
}
-#[cfg(feature = "testing")]
pub fn smarteeprom_reset_unlock_attempts() {
unsafe {
bitbox02_sys::bitbox02_smarteeprom_reset_unlock_attempts();
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.