Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/rust/bitbox02-rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub mod hal;
pub mod hash;
pub mod hww;
pub mod keystore;
pub mod salt;
pub mod secp256k1;
#[cfg(feature = "app-u2f")]
mod u2f;
Expand Down
131 changes: 131 additions & 0 deletions src/rust/bitbox02-rust/src/salt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// 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.

use alloc::vec::Vec;
use core::ffi::c_char;

use bitbox02::memory;
use sha2::Digest;
use util::bytes::{Bytes, BytesMut};
use zeroize::Zeroizing;

/// Creates `SHA256(salt_root || purpose || data)`, where `salt_root` is a persisted value that
/// remains unchanged until the device is reset. The `purpose` string namespaces individual uses of
/// the salt, and the provided `data` slice is hashed alongside it.
///
/// Returns `Err(())` if the salt root cannot be retrieved from persistent storage.
pub fn hash_data(data: &[u8], purpose: &str) -> Result<Zeroizing<Vec<u8>>, ()> {
let salt_root = memory::get_salt_root()?;

let mut hasher = sha2::Sha256::new();
hasher.update(salt_root.as_slice());
hasher.update(purpose.as_bytes());
hasher.update(data);

Ok(Zeroizing::new(hasher.finalize().to_vec()))
}

/// # Safety
///
/// `purpose` must be a valid, null-terminated UTF-8 string pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_salt_hash_data(
data: Bytes,
purpose: *const c_char,
mut hash_out: BytesMut,
) -> bool {
let purpose_str = match unsafe { bitbox02::util::str_from_null_terminated_ptr(purpose) } {
Ok(purpose) => purpose,
Err(()) => return false,
};
match hash_data(data.as_ref(), purpose_str) {
Ok(hash) => {
hash_out.as_mut()[..32].copy_from_slice(&hash);
true
}
Err(()) => false,
}
}

#[cfg(test)]
mod tests {
use super::*;
use bitbox02::testing::mock_memory;
use core::convert::TryInto;
use core::ptr;
use hex_lit::hex;

const MOCK_SALT_ROOT: [u8; 32] =
hex!("0000000000000000111111111111111122222222222222223333333333333333");

#[test]
fn test_hash_data() {
mock_memory();
memory::set_salt_root(&MOCK_SALT_ROOT).unwrap();

let data = hex!("001122334455667788");
let expected = hex!("62db8dcd47ddf8e81809c377ed96643855d3052bb73237100ca81f0f5a7611e6");

let hash = hash_data(&data, "test purpose").unwrap();
assert_eq!(hash.as_slice(), &expected);
}

#[test]
fn test_hash_data_empty_inputs() {
mock_memory();
memory::set_salt_root(&MOCK_SALT_ROOT).unwrap();

let expected = hex!("2dbb05dd73d94edba6946611aaca367f76c809e96f20499ad674e596050f9833");

let hash = hash_data(&[], "").unwrap();
assert_eq!(hash.as_slice(), &expected);
}

#[test]
fn test_rust_salt_hash_data() {
mock_memory();
memory::set_salt_root(&MOCK_SALT_ROOT).unwrap();

let data = hex!("001122334455667788");
let expected = hex!("62db8dcd47ddf8e81809c377ed96643855d3052bb73237100ca81f0f5a7611e6");

let mut hash_out = [0u8; 32];
let purpose = c"test purpose";
assert!(unsafe {
rust_salt_hash_data(
util::bytes::rust_util_bytes(data.as_ptr(), data.len()),
purpose.as_ptr(),
util::bytes::rust_util_bytes_mut(hash_out.as_mut_ptr(), hash_out.len()),
)
});
assert_eq!(hash_out, expected);
}

#[test]
fn test_rust_salt_hash_data_empty_inputs() {
mock_memory();
memory::set_salt_root(&MOCK_SALT_ROOT).unwrap();

let expected = hex!("2dbb05dd73d94edba6946611aaca367f76c809e96f20499ad674e596050f9833");
let mut hash_out = [0u8; 32];
assert!(unsafe {
rust_salt_hash_data(
util::bytes::rust_util_bytes(ptr::null(), 0),
c"".as_ptr(),
util::bytes::rust_util_bytes_mut(hash_out.as_mut_ptr(), hash_out.len()),
)
});
assert_eq!(hash_out, expected);
}
}
1 change: 1 addition & 0 deletions src/rust/bitbox02-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ const ALLOWLIST_FNS: &[&str] = &[
"memory_is_initialized",
"memory_is_mnemonic_passphrase_enabled",
"memory_is_seeded",
"memory_get_salt_root",
"memory_multisig_get_by_hash",
"memory_multisig_set_by_hash",
"memory_set_device_name",
Expand Down
1 change: 1 addition & 0 deletions src/rust/bitbox02/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ hex = { workspace = true }
hex = { workspace = true }
bitbox-aes = { path = "../bitbox-aes" }
bitbox02-rust = { path = "../bitbox02-rust" }
hex_lit = { workspace = true }

[features]
# Only to be enabled in unit tests and simulators
Expand Down
32 changes: 31 additions & 1 deletion src/rust/bitbox02/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;

// deduct one for the null terminator.
pub const DEVICE_NAME_MAX_LEN: usize = bitbox02_sys::MEMORY_DEVICE_NAME_MAX_LEN as usize - 1;
Expand Down Expand Up @@ -232,6 +233,15 @@ pub fn ble_enable(enable: bool) -> Result<(), ()> {
if res { Ok(()) } else { Err(()) }
}

pub fn get_salt_root() -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
let mut salt_root = zeroize::Zeroizing::new(vec![0u8; 32]);
if unsafe { bitbox02_sys::memory_get_salt_root(salt_root.as_mut_ptr()) } {
Ok(salt_root)
} else {
Err(())
}
}

#[cfg(feature = "testing")]
pub fn set_salt_root(salt_root: &[u8; 32]) -> Result<(), ()> {
match unsafe { bitbox02_sys::memory_set_salt_root(salt_root.as_ptr()) } {
Expand All @@ -244,9 +254,29 @@ pub fn set_salt_root(salt_root: &[u8; 32]) -> Result<(), ()> {
mod tests {
use super::*;

use hex_lit::hex;

#[test]
fn test_get_attestation_bootloader_hash() {
let expected: [u8; 32] = *b"\x71\x3d\xf0\xd5\x8c\x71\x7d\x40\x31\x78\x7c\xdc\x8f\xa3\x5b\x90\x25\x82\xbe\x6a\xb6\xa2\x2e\x09\xde\x44\x77\xd3\x0e\x22\x30\xfc";
let expected: [u8; 32] =
hex!("713df0d58c717d4031787cdc8fa35b902582be6ab6a22e09de4477d30e2230fc");
assert_eq!(get_attestation_bootloader_hash(), expected);
}

#[test]
fn test_get_salt_root_roundtrip() {
let original = get_salt_root().unwrap();

let expected = hex!("00112233445566778899aabbccddeefffeeddccbbaa998877665544332211000");

set_salt_root(expected.as_slice().try_into().unwrap()).unwrap();
let salt_root = get_salt_root().unwrap();
assert_eq!(salt_root.as_slice(), &expected);

let erased = [0xffu8; 32];
set_salt_root(&erased).unwrap();
assert!(get_salt_root().is_err());

set_salt_root(original.as_slice().try_into().unwrap()).unwrap();
}
}
22 changes: 3 additions & 19 deletions src/salt.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,9 @@

bool salt_hash_data(const uint8_t* data, size_t data_len, const char* purpose, uint8_t* hash_out)
{
if (data_len > 0 && data == NULL) {
if ((data_len > 0 && data == NULL) || purpose == NULL || hash_out == NULL) {
return false;
}
if (!purpose || !hash_out) {
return false;
}

uint8_t salt_root[32];
UTIL_CLEANUP_32(salt_root);
if (!memory_get_salt_root(salt_root)) {
return false;
}

void* ctx = rust_sha256_new();
rust_sha256_update(ctx, salt_root, sizeof(salt_root));
rust_sha256_update(ctx, purpose, strlen(purpose));
if (data != NULL) {
rust_sha256_update(ctx, data, data_len);
}
rust_sha256_finish(&ctx, hash_out);
return true;
return rust_salt_hash_data(
rust_util_bytes(data, data_len), purpose, rust_util_bytes_mut(hash_out, 32));
}
3 changes: 0 additions & 3 deletions test/unit-test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-parameter -Wno-missing-prototype
add_library(mocks STATIC EXCLUDE_FROM_ALL
framework/src/mock_gestures.c
framework/src/mock_screen_stack.c
framework/src/mock_memory.c
framework/src/mock_qtouch.c
)
target_link_libraries(mocks PUBLIC c-unit-tests_rust_c ${CMOCKA_LDFLAGS})
Expand Down Expand Up @@ -66,8 +65,6 @@ set(TEST_LIST
"-Wl,--wrap=memory_read_chunk_fake,--wrap=memory_write_chunk_fake,--wrap=rust_noise_generate_static_private_key,--wrap=memory_read_shared_bootdata_fake,--wrap=memory_write_to_address_fake,--wrap=random_32_bytes_mcu"
memory_functional
""
salt
"-Wl,--wrap=memory_get_salt_root"
cipher
"-Wl,--wrap=cipher_fake_iv"
util
Expand Down
76 changes: 0 additions & 76 deletions test/unit-test/framework/src/mock_memory.c

This file was deleted.

Loading