keystore: port keystore_encrypt_and_store_seed to Rust
What changed, and why it matters
This commit rewrites a single security-sensitive function from C to Rust. It is a language port/refactor of the code that encrypts and stores the wallet seed. The logic is essentially the same: it checks the device is not already initialized, validates the seed length, stretches the password through the secure chip, encrypts the seed, stores it, and verifies it can be decrypted again. There is no indication in the commit that this fixes a known vulnerability or changes behavior in a security-relevant way.
Treat as a normal refactor. If reviewing for security, verify that the Rust implementation preserves the original behavior exactly, especially: seed length validation (16/24/32 bytes), memory initialization check, secure chip password stretching, AES-HMAC encryption overhead size, encrypted length sanity check, storage failure handling, and the verify-then-retain sequence. No immediate security action is indicated by the commit itself.
Security signals we found
Language port of seed encryption/storage routine from C to Rust.
Removes C wrapper `_encrypt_and_store_seed` and C-exported `rust_keystore_verify_seed`.
Adds Rust AES-HMAC encryption call with explicit random IV.
Adds new Rust wrappers for secure chip and memory operations.
No explicit security bug fix or vulnerability disclosure in commit message or diff.
Evidence from the diff
The change ports keystore_encrypt_and_store_seed from C to Rust. The C implementation is removed from src/keystore.c, and a new Rust implementation is added in src/rust/bitbox02-rust/src/keystore.rs. Supporting FFI bindings and Rust wrappers are added for securechip_init_new_password, securechip_stretch_password, memory_set_encrypted_seed_and_hmac, memory_reset_hww, and usb_processing_timeout_reset. The Rust version uses bitbox_aes::encrypt_with_hmac instead of the C cipher_aes_hmac_encrypt, generates a 16-byte IV from random_32_bytes, and keeps the same verification and seed-retention flow. The old C FFI wrapper _encrypt_and_store_seed and the C export rust_keystore_verify_seed are removed as they are no longer needed.
Changed components
src/keystore.csrc/keystore.hsrc/rust/bitbox02-rust/src/keystore.rssrc/rust/bitbox02/src/keystore.rssrc/rust/bitbox02/src/memory.rssrc/rust/bitbox02/src/securechip.rssrc/rust/bitbox02/src/usb_processing.rssrc/rust/bitbox02-sys/build.rssrc/rust/bitbox02-sys/wrapper.hInspect captured patch +114 / −90
diff --git a/src/keystore.c b/src/keystore.c
index 21edc7e..37cc627 100644
--- a/src/keystore.c
+++ b/src/keystore.c
@@ -19,7 +19,6 @@
#include "keystore.h"
#include "memory/bitbox02_smarteeprom.h"
#include "memory/memory.h"
-#include "random.h"
#include "reset.h"
#include "salt.h"
#include "securechip/securechip.h"
@@ -103,59 +102,6 @@ USE_RESULT static keystore_error_t _retain_seed(const uint8_t* seed, size_t seed
return KEYSTORE_OK;
}
-keystore_error_t keystore_encrypt_and_store_seed(
- const uint8_t* seed,
- size_t seed_length,
- const char* password)
-{
- if (memory_is_initialized()) {
- return KEYSTORE_ERR_MEMORY;
- }
- rust_keystore_lock();
- if (!_validate_seed_length(seed_length)) {
- return KEYSTORE_ERR_SEED_SIZE;
- }
-
- usb_processing_timeout_reset(LONG_TIMEOUT);
-
- if (securechip_init_new_password(password)) {
- return KEYSTORE_ERR_SECURECHIP;
- }
- uint8_t secret[32] = {0};
- UTIL_CLEANUP_32(secret);
- if (securechip_stretch_password(password, secret)) {
- return KEYSTORE_ERR_SECURECHIP;
- }
-
- size_t encrypted_seed_len = seed_length + 64;
- uint8_t encrypted_seed[encrypted_seed_len];
- UTIL_CLEANUP_32(encrypted_seed);
- if (!cipher_aes_hmac_encrypt(seed, seed_length, encrypted_seed, &encrypted_seed_len, secret)) {
- return KEYSTORE_ERR_ENCRYPT;
- }
- if (encrypted_seed_len > 255) { // sanity check, can't happen
- Abort("keystore_encrypt_and_store_seed");
- }
- uint8_t encrypted_seed_len_u8 = (uint8_t)encrypted_seed_len;
- if (!memory_set_encrypted_seed_and_hmac(encrypted_seed, encrypted_seed_len_u8)) {
- return KEYSTORE_ERR_MEMORY;
- }
- if (!rust_keystore_verify_seed(
- rust_util_bytes(secret, sizeof(secret)), rust_util_bytes(seed, seed_length))) {
- if (!memory_reset_hww()) {
- return KEYSTORE_ERR_MEMORY;
- }
- return KEYSTORE_ERR_MEMORY;
- }
-
- keystore_error_t retain_seed_result = _retain_seed(seed, seed_length);
- if (retain_seed_result != KEYSTORE_OK) {
- return retain_seed_result;
- }
-
- return KEYSTORE_OK;
-}
-
keystore_error_t keystore_unlock(
const char* password,
uint8_t* remaining_attempts_out,
diff --git a/src/keystore.h b/src/keystore.h
index a01e974..96b7598 100644
--- a/src/keystore.h
+++ b/src/keystore.h
@@ -50,9 +50,6 @@ typedef enum {
* @param[in] seed_length The length of the seed (max. 32 bytes).
* @param[in] password The password with which we encrypt the seed.
*/
-USE_RESULT keystore_error_t
-keystore_encrypt_and_store_seed(const uint8_t* seed, size_t seed_length, const char* password);
-
/** 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.
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index d360e46..0a1271a 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -36,6 +36,10 @@ const EC_PUBLIC_KEY_LEN: usize = 33;
/// aes256cbc-hmac cipher adds 16 bytes IV, 16 bytes padding, 32 bytes hmac.
const ENCRYPTION_OVERHEAD: usize = 64;
+// Unlocking the keystore takes longer than the default 500 ms watchdog. Bump the watchdog timeout
+// to roughly seven seconds so we don't assume communication was lost mid-unlock.
+const LONG_TIMEOUT: i16 = -70;
+
#[derive(Copy, Clone)]
struct ReadOnlyBuffer {
// 64 is the biggest retained buffer (bip39 seed) we will store, and 64 is added for the
@@ -174,6 +178,44 @@ fn retain_seed(seed: &[u8]) -> Result<(), Error> {
Ok(())
}
+/// Restores a seed. This also unlocks the keystore with this seed.
+/// `password` is the password with which we encrypt the seed.
+pub fn encrypt_and_store_seed(seed: &[u8], password: &str) -> Result<(), Error> {
+ if bitbox02::memory::is_initialized() {
+ return Err(Error::Memory);
+ }
+
+ if !matches!(seed.len(), 16 | 24 | 32) {
+ return Err(Error::SeedSize);
+ }
+
+ lock();
+
+ bitbox02::usb_processing::timeout_reset(LONG_TIMEOUT);
+
+ securechip::init_new_password(password)?;
+
+ let secret = securechip::stretch_password(password)?;
+
+ let iv: [u8; 16] = bitbox02::random::random_32_bytes()[..16]
+ .try_into()
+ .unwrap();
+ let encrypted = bitbox_aes::encrypt_with_hmac(&iv, &secret, seed);
+
+ if encrypted.len() > u8::MAX as usize {
+ panic!("encrypted seed length overflow");
+ }
+
+ bitbox02::memory::set_encrypted_seed_and_hmac(&encrypted).map_err(|_| Error::Memory)?;
+
+ if !verify_seed(&secret, seed) {
+ bitbox02::memory::reset_hww().map_err(|_| Error::Memory)?;
+ return Err(Error::Memory);
+ }
+
+ retain_seed(seed)
+}
+
// Checks if the retained seed matches the passed seed.
fn check_retained_seed(seed: &[u8]) -> Result<(), ()> {
if RETAINED_SEED.read().is_none() {
@@ -236,12 +278,6 @@ pub fn copy_bip39_seed() -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
.map_err(|_| ())
}
-/// Restores a seed. This also unlocks the keystore with this seed.
-/// `password` is the password with which we encrypt the seed.
-pub fn encrypt_and_store_seed(seed: &[u8], password: &str) -> Result<(), Error> {
- keystore::_encrypt_and_store_seed(seed, password)
-}
-
/// Generates the seed, mixes it with host_entropy, and stores it encrypted with the
/// password. The size of the host entropy determines the size of the seed. Can be either 16 or 32
/// bytes, resulting in 12 or 24 BIP39 recovery words.
@@ -429,14 +465,6 @@ pub extern "C" fn rust_keystore_retain_seed(seed: util::bytes::Bytes) -> bool {
retain_seed(seed.as_ref()).is_ok()
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_keystore_verify_seed(
- encryption_key: util::bytes::Bytes,
- expected_seed: util::bytes::Bytes,
-) -> bool {
- verify_seed(encryption_key.as_ref(), expected_seed.as_ref())
-}
-
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 a29bb5c..3b7af49 100644
--- a/src/rust/bitbox02-sys/build.rs
+++ b/src/rust/bitbox02-sys/build.rs
@@ -76,7 +76,6 @@ const ALLOWLIST_FNS: &[&str] = &[
"fake_securechip_event_counter",
"gmtime",
"keystore_bip39_mnemonic_to_seed",
- "keystore_encrypt_and_store_seed",
"keystore_get_bip39_word",
"keystore_secp256k1_nonce_commit",
"keystore_secp256k1_sign",
@@ -97,6 +96,7 @@ const ALLOWLIST_FNS: &[&str] = &[
"memory_get_salt_root",
"memory_get_securechip_type",
"memory_get_seed_birthdate",
+ "memory_reset_hww",
"memory_is_initialized",
"memory_is_mnemonic_passphrase_enabled",
"memory_is_seeded",
@@ -107,6 +107,7 @@ const ALLOWLIST_FNS: &[&str] = &[
"memory_set_initialized",
"memory_set_mnemonic_passphrase_enabled",
"memory_set_salt_root",
+ "memory_set_encrypted_seed_and_hmac",
"memory_set_seed_birthdate",
"memory_setup",
"memory_spi_get_active_ble_firmware_version",
@@ -141,8 +142,10 @@ const ALLOWLIST_FNS: &[&str] = &[
"secp256k1_ecdsa_s2c_opening_parse",
"securechip_attestation_sign",
"securechip_kdf",
+ "securechip_init_new_password",
"securechip_model",
"securechip_monotonic_increments_remaining",
+ "securechip_stretch_password",
"securechip_u2f_counter_set",
"smarteeprom_bb02_config",
"smarteeprom_disable",
@@ -162,6 +165,8 @@ const ALLOWLIST_FNS: &[&str] = &[
"ui_screen_stack_push",
"unlock_animation_create",
"util_format_datetime",
+ "communication_mode_ble_enabled",
+ "usb_processing_timeout_reset",
];
const RUSTIFIED_ENUMS: &[&str] = &[
diff --git a/src/rust/bitbox02-sys/wrapper.h b/src/rust/bitbox02-sys/wrapper.h
index df4f059..69447cb 100644
--- a/src/rust/bitbox02-sys/wrapper.h
+++ b/src/rust/bitbox02-sys/wrapper.h
@@ -28,6 +28,7 @@
#include <secp256k1_ecdsa_adaptor.h>
#include <secp256k1_ecdsa_s2c.h>
#include <securechip/securechip.h>
+#include <usb/usb_processing.h>
#include <system.h>
#include <time.h>
#include <ui/components/confirm.h>
diff --git a/src/rust/bitbox02/src/keystore.rs b/src/rust/bitbox02/src/keystore.rs
index 62d1418..a8cde05 100644
--- a/src/rust/bitbox02/src/keystore.rs
+++ b/src/rust/bitbox02/src/keystore.rs
@@ -18,8 +18,6 @@ use alloc::vec::Vec;
use bitcoin::secp256k1::{All, Secp256k1};
-use core::convert::TryInto;
-
use bitbox02_sys::keystore_error_t;
/// Length of a compressed secp256k1 pubkey.
@@ -152,19 +150,3 @@ pub fn _secp256k1_nonce_commit(
false => Err(()),
}
}
-
-pub fn _encrypt_and_store_seed(seed: &[u8], password: &str) -> Result<(), Error> {
- match unsafe {
- bitbox02_sys::keystore_encrypt_and_store_seed(
- seed.as_ptr(),
- seed.len(),
- crate::util::str_to_cstr_vec(password)
- .unwrap()
- .as_ptr()
- .cast(),
- )
- } {
- keystore_error_t::KEYSTORE_OK => Ok(()),
- err => Err(err.into()),
- }
-}
diff --git a/src/rust/bitbox02/src/lib.rs b/src/rust/bitbox02/src/lib.rs
index a37b8f4..b7f93d3 100644
--- a/src/rust/bitbox02/src/lib.rs
+++ b/src/rust/bitbox02/src/lib.rs
@@ -44,6 +44,7 @@ pub mod secp256k1;
pub mod securechip;
pub mod spi_mem;
pub mod ui;
+pub mod usb_processing;
use core::ffi::c_int;
use core::time::Duration;
diff --git a/src/rust/bitbox02/src/memory.rs b/src/rust/bitbox02/src/memory.rs
index 0a9232b..a0661a9 100644
--- a/src/rust/bitbox02/src/memory.rs
+++ b/src/rust/bitbox02/src/memory.rs
@@ -151,6 +151,25 @@ pub fn get_seed_birthdate() -> u32 {
}
}
+pub fn set_encrypted_seed_and_hmac(data: &[u8]) -> Result<(), ()> {
+ if data.len() > u8::MAX as usize {
+ return Err(());
+ }
+ match unsafe {
+ bitbox02_sys::memory_set_encrypted_seed_and_hmac(data.as_ptr(), data.len() as u8)
+ } {
+ true => Ok(()),
+ false => Err(()),
+ }
+}
+
+pub fn reset_hww() -> Result<(), ()> {
+ match unsafe { bitbox02_sys::memory_reset_hww() } {
+ true => Ok(()),
+ false => Err(()),
+ }
+}
+
pub fn multisig_set_by_hash(hash: &[u8], name: &str) -> Result<(), MemoryError> {
if hash.len() != 32 {
return Err(MemoryError::MEMORY_ERR_INVALID_INPUT);
diff --git a/src/rust/bitbox02/src/securechip.rs b/src/rust/bitbox02/src/securechip.rs
index 793aca7..fca0e43 100644
--- a/src/rust/bitbox02/src/securechip.rs
+++ b/src/rust/bitbox02/src/securechip.rs
@@ -85,6 +85,31 @@ pub fn monotonic_increments_remaining() -> Result<u32, ()> {
}
}
+pub fn init_new_password(password: &str) -> Result<(), Error> {
+ let password = crate::util::str_to_cstr_vec_zeroizing(password)
+ .map_err(|_| Error::SecureChip(SecureChipError::SC_ERR_INVALID_ARGS))?;
+ let status = unsafe { bitbox02_sys::securechip_init_new_password(password.as_ptr().cast()) };
+ if status == 0 {
+ Ok(())
+ } else {
+ Err(Error::from_status(status))
+ }
+}
+
+pub fn stretch_password(password: &str) -> Result<Zeroizing<Vec<u8>>, Error> {
+ let password = crate::util::str_to_cstr_vec_zeroizing(password)
+ .map_err(|_| Error::SecureChip(SecureChipError::SC_ERR_INVALID_ARGS))?;
+ let mut stretched = Zeroizing::new(vec![0u8; 32]);
+ let status = unsafe {
+ bitbox02_sys::securechip_stretch_password(password.as_ptr().cast(), stretched.as_mut_ptr())
+ };
+ if status == 0 {
+ Ok(stretched)
+ } else {
+ Err(Error::from_status(status))
+ }
+}
+
/// Perform the secure chip KDF with the message in `msg` and return the zeroizing 32-byte result.
pub fn kdf(msg: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error> {
let mut result = Zeroizing::new(vec![0u8; 32]);
diff --git a/src/rust/bitbox02/src/usb_processing.rs b/src/rust/bitbox02/src/usb_processing.rs
new file mode 100644
index 0000000..f24561b
--- /dev/null
+++ b/src/rust/bitbox02/src/usb_processing.rs
@@ -0,0 +1,20 @@
+// Copyright 2025 Shift Crypto AG
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/// Reset the USB processing timeout to the given value.
+pub fn timeout_reset(value: i16) {
+ unsafe {
+ bitbox02_sys::usb_processing_timeout_reset(value);
+ }
+}
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.