secp256k1: randomize the context once per boot
What changed, and why it matters
This commit hardens the BitBox02 hardware wallet against advanced physical attacks. It randomizes the internal math context used for Bitcoin private-key operations once each time the device boots, using a mix of randomness from the microcontroller, secure chip, and factory-stored randomness. Public keys and signatures remain unchanged; the change only makes it harder for an attacker with physical access to extract secrets through power or electromagnetic side-channel analysis.
No immediate user action required. This is a defensive hardening patch. Ensure firmware builds and tests pass, and verify that production startup cannot reach the main loop if secp256k1 context initialization fails. Review that the random_32_bytes_from_hal helper and secure-chip randomness path remain robust, since startup now depends on them.
Security signals we found
Side-channel countermeasure: secp256k1 context blinding/randomization
Source of randomness combines MCU, secure chip, and factory randomness
Initialization is required before production access; panics if uninitialized
Idempotent init prevents re-randomization while references may be held
No change to public keys or deterministic signatures
No new dependencies or secp256k1 library modifications
Evidence from the diff
The commit replaces the lazily initialized deterministic secp256k1 GlobalContext with one that must be explicitly initialized with a 32-byte seed before production use. The seed comes from bitbox_core_utils::random::random_32_bytes_from_hal, which combines MCU, secure-chip, and factory randomness. The context is then created with Secp256k1::new() and blinded via context.seeded_randomize(seed) before being published in a OnceCell. Repeated init calls are idempotent. Test and simulator builds retain lazy initialization via new ‘c-unit-testing’ and existing ‘testing’ features, and both graphical simulators now explicitly call the init function.
Changed components
src/rust/bitbox-secp256k1/src/lib.rssrc/rust/bitbox02-rust/src/secp256k1.rssrc/rust/bitbox02-rust-c/src/firmware_c_api.rstest/simulator-graphical/src/main.rstest/simulator-graphical-bb03/src/main.rsInspect captured patch +79 / −12
### src/rust/bitbox-secp256k1/Cargo.toml
@@ -22,3 +22,4 @@ cc = { version = "1.2", features = ["parallel"] }
[features]
testing = []
+c-unit-testing = []
### src/rust/bitbox-secp256k1/src/lib.rs
@@ -98,31 +98,48 @@ pub struct SignResult {
pub recid: u8,
}
-#[derive(Debug, Copy, Clone)]
+#[derive(Debug)]
pub struct GlobalContext {
- __private: (), // prevents direct init
+ context: OnceCell<Secp256k1<All>>,
}
/// Global context, initialized once.
///
/// Port of https://docs.rs/secp256k1/latest/secp256k1/global/struct.GlobalContext.html to no_std.
-pub static SECP256K1: &GlobalContext = &GlobalContext { __private: () };
-
-struct SyncWrapper(OnceCell<Secp256k1<All>>);
+pub static SECP256K1: &GlobalContext = {
+ static INSTANCE: GlobalContext = GlobalContext {
+ context: OnceCell::new(),
+ };
+ &INSTANCE
+};
// SAFETY: Embedded single-threaded use only, can't use from an interrupt context.
-unsafe impl Sync for SyncWrapper {}
+unsafe impl Sync for GlobalContext {}
+
+impl GlobalContext {
+ pub fn init(&self, seed: &[u8; 32]) {
+ self.context.get_or_init(|| {
+ let mut context = Secp256k1::new();
+ context.seeded_randomize(seed);
+ context
+ });
+ }
+}
impl Deref for GlobalContext {
type Target = Secp256k1<All>;
fn deref(&self) -> &Self::Target {
- static CONTEXT: SyncWrapper = SyncWrapper(OnceCell::new());
-
- CONTEXT.0.get_or_init(|| {
+ // Allow tests to use the context without explicit initialization.
+ #[cfg(any(test, feature = "testing", feature = "c-unit-testing"))]
+ self.context.get_or_init(|| {
// Initialized on first access
Secp256k1::new()
- })
+ });
+
+ self.context
+ .get()
+ .expect("secp256k1 context not initialized")
}
}
### src/rust/bitbox-secp256k1/tests/context.rs
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+
+use bitbox_secp256k1::SECP256K1;
+use bitcoin::secp256k1::{Message, PublicKey, Secp256k1, SecretKey};
+use hex_lit::hex;
+
+#[test]
+fn test_init() {
+ #[cfg(not(any(feature = "testing", feature = "c-unit-testing")))]
+ assert!(std::panic::catch_unwind(|| SECP256K1.ctx()).is_err());
+
+ let seed = hex!("d863bf4c526a840b541c4bc1d7335cf5e4fab8f07a2b2b0e3cc036952528641a");
+ SECP256K1.init(&seed);
+
+ let reference = Secp256k1::new();
+ let secret_key = SecretKey::from_slice(&hex!(
+ "e90610a2b3bd72f3b4691f0529b0541702272b07f60d8ad5e781adf77474845b"
+ ))
+ .unwrap();
+ let message = Message::from_digest(hex!(
+ "ff3a9828e6127d5cc71e6898f6562538abf97f4de99544e1e64b517773612694"
+ ));
+ assert_eq!(
+ PublicKey::from_secret_key(SECP256K1, &secret_key),
+ PublicKey::from_secret_key(&reference, &secret_key),
+ );
+ assert_eq!(
+ SECP256K1.sign_ecdsa_recoverable(&message, &secret_key),
+ reference.sign_ecdsa_recoverable(&message, &secret_key),
+ );
+
+ let context = SECP256K1.ctx();
+ SECP256K1.init(&hex!(
+ "61d55a53c6728a04d62e7d37e9adab07102f73dc206b4f6087652e608eb8778a"
+ ));
+ assert_eq!(SECP256K1.ctx(), context);
+}
### src/rust/bitbox02-rust-c/src/firmware_c_api.rs
@@ -19,7 +19,10 @@ pub enum rust_memory_securechip_type_t {
#[cfg(not(any(feature = "c-unit-testing", feature = "simulator-graphical")))]
#[unsafe(no_mangle)]
pub extern "C" fn rust_main_loop() -> ! {
- bitbox02_rust::main_loop::main_loop(&mut crate::HalImpl::new())
+ let mut hal = crate::HalImpl::new();
+ util::bb02_async::block_on(bitbox02_rust::secp256k1::init(&mut hal))
+ .expect("secp256k1 context initialization failed");
+ bitbox02_rust::main_loop::main_loop(&mut hal)
}
#[unsafe(no_mangle)]
### src/rust/bitbox02-rust/Cargo.toml
@@ -107,7 +107,7 @@ testing = [
"util/testing"
]
-c-unit-testing = []
+c-unit-testing = ["bitbox-secp256k1/c-unit-testing"]
simulator-graphical = [
"bitbox02/simulator-graphical",
### src/rust/bitbox02-rust/src/secp256k1.rs
@@ -1,3 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
pub use bitbox_secp256k1::*;
+
+pub async fn init(hal: &mut impl crate::hal::Hal) -> Result<(), bitbox_hal::securechip::Error> {
+ let seed = bitbox_core_utils::random::random_32_bytes_from_hal(hal).await?;
+ SECP256K1.init(&seed);
+ Ok(())
+}
### test/simulator-graphical-bb03/src/main.rs
@@ -211,6 +211,8 @@ fn init_hww(
bitbox: &mut BitBox03,
args: &Args,
) -> Option<bitbox02_rust::hww::transport::HwwTransport<BitBox03>> {
+ block_on(bitbox02_rust::secp256k1::init(bitbox)).unwrap();
+
//bitbox02::screen::init(pixel_fn, mirror_fn, clear_fn);
//bitbox02::screen::splash();
### test/simulator-graphical/src/main.rs
@@ -163,6 +163,7 @@ fn init_hww(
info!("Memory setup: success");
let mut hal = SimulatorHal::new();
+ block_on(bitbox02_rust::secp256k1::init(&mut hal)).unwrap();
if preseed {
let mnemonic = "boring mistake dish oyster truth pigeon viable emerge sort crash wire portion cannon couple enact box walk height pull today solid off enable tide";Why this scored 37/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.