Merge remote-tracking branch 'agent/benma-agent/secp256k1-randomize'
What changed, and why it matters
This commit changes how the BitBox02 hardware wallet initializes the secp256k1 cryptographic library. Previously, the library's global context was created automatically on first use. Now, it must be explicitly initialized with a random 32-byte seed before use. The seed is used to randomize internal computations, which is a standard side-channel defense. If the context is used before initialization, the firmware will panic (crash). The change also adds test-only fallbacks so existing tests still work without providing a seed.
Treat this as a hardening / side-channel mitigation change rather than a vulnerability fix. Verify that all firmware entry points and simulators call `secp256k1::init()` before any secp256k1 operation, and that the random seed source is trustworthy. Review whether any other code paths (bootloader, factory setup, recovery flows) access secp256k1 without going through `rust_main_loop()` or the simulators. No immediate patch deployment is required solely based on this commit.
Security signals we found
Adds `context.seeded_randomize(seed)` to the secp256k1 context initialization
Requires explicit initialization before cryptographic use, replacing lazy initialization
Panics if the global context is dereferenced before `init()` is called
Sources the seed from `random_32_bytes_from_hal(hal)`, tied to the secure chip / TRNG
Introduces `c-unit-testing` feature to preserve test behavior without seed
Evidence from the diff
The patch refactors bitbox-secp256k1’s GlobalContext from an on-demand OnceCell-based lazy initializer to an explicit init(seed) model. SECP256K1 is now a static GlobalContext whose inner OnceCell<Secp256k1<All>> is populated by init() using context.seeded_randomize(seed). The firmware’s rust_main_loop() and both graphical simulators now call bitbox02_rust::secp256k1::init(hal), which obtains 32 random bytes from the secure chip / HAL and seeds the context. A new c-unit-testing feature allows tests to auto-initialize the context without a seed. A test verifies that uninitialized access panics and that re-initialization is idempotent.
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 45/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.