util/cell: make read/write safe by using critical_section
What changed, and why it matters
This commit replaces a hand-rolled unsafe global cell with a safer version that uses a critical section (a short lock) around reads and writes. It also adds a Copy requirement so the compiler can safely copy values in and out without unexpected destruction. The change removes unsafe blocks from callers and reduces the chance of race conditions or memory-safety bugs in firmware that stores things like the wallet's root fingerprint. There is no claim in the commit that this fixes a known exploitable vulnerability.
Treat as a defensive hardening improvement. Review that critical_section::with on this single-core Cortex-M target correctly disables interrupts for the short duration of the read/write and that no code path can panic inside the critical section. Continue normal testing; no emergency response is indicated by the commit itself.
Security signals we found
Replaced unsynchronized UnsafeCell access with critical_section-protected access
Removed unsafe blocks from keystore root-fingerprint read/write
Added Copy bound to prevent drop-semantics bugs in cell read/write
Build feature changes to support critical-section in test/simulator builds
Evidence from the diff
The patch renames util::cell::SyncUnsafeCell to SyncCell and wraps the underlying UnsafeCell::read/write operations in critical_section::with(…). It requires T: Copy in both read() and write() to avoid double-drop or missed-drop hazards when values are copied across the cell boundary. Callers in bitbox02-rust/src/keystore.rs (ROOT_FINGERPRINT) drop their unsafe blocks. Build wiring is updated: util now depends on critical-section, cortex-m is always included (not just via rtt), and c-unit-testing enables critical-section/std. The panic handler is also compiled out for c-unit-testing builds.
Changed components
src/rust/util/src/cell.rs (SyncCell implementation)src/rust/bitbox02-rust/src/keystore.rs (ROOT_FINGERPRINT usage)src/rust/util/Cargo.toml (critical-section dependency)src/rust/bitbox02-rust-c/Cargo.toml (c-unit-testing feature wiring)src/rust/bitbox02-rust-c/src/lib.rs (panic handler cfg)src/CMakeLists.txt (build-std flags)Inspect captured patch +32 / −38
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 254529c..fd3383b 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -400,7 +400,7 @@ foreach(type ${RUST_LIBS})
# We build the rust standard libs so that everything from the rust runtime
# is included (like eh_personality).
if(type STREQUAL "c-unit-tests")
- set(RUST_CARGO_FLAGS ${RUST_CARGO_FLAGS} -Zbuild-std)
+ set(RUST_CARGO_FLAGS ${RUST_CARGO_FLAGS} -Zbuild-std=std,panic_abort)
endif()
set(lib ${RUST_BINARY_DIR}/feature-${type}/${RUST_TARGET_ARCH_DIR}/${RUST_PROFILE}/libbitbox02_rust_c.a)
# The dummy output is to always trigger rebuild (cargo is clever enough to
diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock
index 3e9e57d..0ff39fa 100644
--- a/src/rust/Cargo.lock
+++ b/src/rust/Cargo.lock
@@ -1065,6 +1065,7 @@ version = "0.1.0"
dependencies = [
"bitcoin",
"cortex-m",
+ "critical-section",
"hex",
"num-bigint",
"p256",
diff --git a/src/rust/bitbox02-rust-c/Cargo.toml b/src/rust/bitbox02-rust-c/Cargo.toml
index 62ecab4..dff55b6 100644
--- a/src/rust/bitbox02-rust-c/Cargo.toml
+++ b/src/rust/bitbox02-rust-c/Cargo.toml
@@ -88,7 +88,7 @@ firmware = [
testing = ["bitbox02-rust/testing", "bitbox02/testing"]
# Active when the Rust code is compiled to be linked into the C unit tests and simulator.
-c-unit-testing = ["bitbox02-rust/c-unit-testing", "bitbox02/c-unit-testing"]
+c-unit-testing = ["bitbox02-rust/c-unit-testing", "bitbox02/c-unit-testing", "util/c-unit-testing"]
app-ethereum = [
# enable this feature in the deps
diff --git a/src/rust/bitbox02-rust-c/src/lib.rs b/src/rust/bitbox02-rust-c/src/lib.rs
index 3ca41cc..e2b7bff 100644
--- a/src/rust/bitbox02-rust-c/src/lib.rs
+++ b/src/rust/bitbox02-rust-c/src/lib.rs
@@ -38,9 +38,8 @@ extern crate util;
// Whenever execution reaches somewhere it isn't supposed to rust code will "panic". Our panic
// handler will print the available information on the screen and over RTT. If we compile with
// `panic=abort` this code will never get executed.
-#[cfg(not(test))]
-#[cfg(not(feature = "testing"))]
#[cfg_attr(feature = "bootloader", allow(unused_variables))]
+#[cfg(not(any(test, feature = "testing", feature = "c-unit-testing")))]
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
#[cfg(feature = "firmware")]
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index 5259a12..dec46ea 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -24,7 +24,7 @@ pub use bitbox02::keystore::SignResult;
use bitbox02::{keystore, securechip};
use util::bip32::HARDENED;
-use util::cell::SyncUnsafeCell;
+use util::cell::SyncCell;
use crate::secp256k1::SECP256K1;
@@ -33,12 +33,12 @@ use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256, sha512};
/// Length of a compressed secp256k1 pubkey.
const EC_PUBLIC_KEY_LEN: usize = 33;
-static ROOT_FINGERPRINT: SyncUnsafeCell<Option<[u8; 4]>> = SyncUnsafeCell::new(None);
+static ROOT_FINGERPRINT: SyncCell<Option<[u8; 4]>> = SyncCell::new(None);
/// Locks the keystore (resets to state before `unlock()`).
pub fn lock() {
keystore::_lock();
- unsafe { ROOT_FINGERPRINT.write(None) }
+ ROOT_FINGERPRINT.write(None)
}
/// Returns false if the keystore is unlocked (unlock() followed by unlock_bip39()), true otherwise.
@@ -74,9 +74,7 @@ pub async fn unlock_bip39(
keystore::unlock_bip39_finalize(bip39_seed.as_slice().try_into().unwrap())?;
// Store root fingerprint.
- unsafe {
- ROOT_FINGERPRINT.write(Some(root_fingerprint));
- }
+ ROOT_FINGERPRINT.write(Some(root_fingerprint));
Ok(())
}
@@ -208,7 +206,7 @@ pub fn root_fingerprint() -> Result<Vec<u8>, ()> {
if is_locked() {
return Err(());
}
- unsafe { ROOT_FINGERPRINT.read().ok_or(()).map(|fp| fp.to_vec()) }
+ ROOT_FINGERPRINT.read().ok_or(()).map(|fp| fp.to_vec())
}
/// Stretches the given encryption_key using the securechip. The resulting key is used to encrypt
diff --git a/src/rust/util/Cargo.toml b/src/rust/util/Cargo.toml
index f27b99d..b5973d8 100644
--- a/src/rust/util/Cargo.toml
+++ b/src/rust/util/Cargo.toml
@@ -23,14 +23,15 @@ license = "Apache-2.0"
[dependencies]
num-bigint = { workspace = true, default-features = false }
rtt-target = { version = "0.6.1", optional = true }
-cortex-m = { version = "0.7.7", features = ["critical-section-single-core"], optional = true }
+cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] }
hex = {workspace = true}
sha2 = { workspace = true, optional = true }
p256 = { version = "0.13.2", default-features = false, features = ["arithmetic", "ecdsa"], optional = true }
bitcoin = {workspace = true}
+critical-section = { version = "1.2.0", default-features = false, features = [] }
[features]
-rtt = ["dep:rtt-target", "dep:cortex-m"]
-testing = []
-c-unit-testing = []
+rtt = ["dep:rtt-target"]
+testing = ["critical-section/std"]
+c-unit-testing = ["critical-section/std"]
firmware = []
diff --git a/src/rust/util/src/cell.rs b/src/rust/util/src/cell.rs
index 04918a8..d2956b9 100644
--- a/src/rust/util/src/cell.rs
+++ b/src/rust/util/src/cell.rs
@@ -12,48 +12,43 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// Same as `core::sync::SyncUnsafeCell`, which is still in nightly. Can remove once it is stable.
-pub struct SyncUnsafeCell<T: ?Sized> {
+// Link library to provide symbols necessary for critical section even if code isn't called
+// explicitly. See
+// https://github.com/rust-embedded/critical-section/blob/bc0d1736c3b14e340c1b0c29042edb3e6bffe6b8/README.md#undefined-reference-errors
+#[cfg(not(any(feature = "testing", feature = "c-unit-testing")))]
+#[allow(unused_imports)]
+use cortex_m as _;
+
+// A cell useful for global mutable state.
+pub struct SyncCell<T: ?Sized> {
value: core::cell::UnsafeCell<T>,
}
// Implement Sync if the wrapped type is Sync.
-unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
+unsafe impl<T: ?Sized + Sync> Sync for SyncCell<T> {}
-impl<T> SyncUnsafeCell<T> {
+impl<T> SyncCell<T> {
pub const fn new(val: T) -> Self {
- SyncUnsafeCell {
+ SyncCell {
value: core::cell::UnsafeCell::new(val),
}
}
/// Reads the value from `self` without moving it. This leaves the
/// memory in `self` unchanged.
- ///
- /// # Safety
- ///
- /// This is unsafe because it allows accessing the interior value without
- /// synchronization. The caller must ensure no other code is currently
- /// writing to this cell during the read operation.
- pub unsafe fn read(&self) -> T
+ pub fn read(&self) -> T
where
- T: Sized,
+ T: Sized + Copy,
{
- unsafe { self.value.get().read() }
+ critical_section::with(|_| unsafe { self.value.get().read() })
}
/// Overwrites a memory location with the given value without reading or
/// dropping the old value.
- ///
- /// # Safety
- ///
- /// This is unsafe because it allows accessing the interior value without
- /// synchronization. The caller must ensure no other code is currently
- /// accessing this cell (either reading or writing) during the write operation.
- pub unsafe fn write(&self, val: T)
+ pub fn write(&self, val: T)
where
- T: Sized,
+ T: Sized + Copy,
{
- unsafe { self.value.get().write(val) }
+ critical_section::with(|_| unsafe { self.value.get().write(val) })
}
}
Why this scored 44/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.