Merge pull request #692 from betrusted-io/signing

WIP: image signing
This commit is contained in:
bunnie 2025-10-06 23:39:40 +08:00 committed by GitHub
commit defb8b502e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 2280 additions and 90 deletions

5
.gitignore vendored
View file

@ -84,3 +84,8 @@ share/python-wheels/
*.egg
*.pyc
MANIFEST
# Deployment credentials
signing/credentials
# Signer target directory
signing/fido-signer/target

10
.vscode/settings.json vendored
View file

@ -8,11 +8,11 @@
"--target-dir",
"target/analyzer",
"--features",
"precursor",
"bao1x",
"--features",
"utralib/precursor",
"utralib/bao1x",
"--features",
"utralib/precursor-pvt",
"board-baosec",
"--message-format",
"json"
],
@ -20,9 +20,9 @@
"XOUS_SVD_FILE": "../precursors/soc.svd"
},
"rust-analyzer.cargo.features": [
"precursor",
"bao1x",
"board-baosec",
"swap",
"mass-storage"
],
"rust-analyzer.files.excludeDirs": [
"./loader/**"

8
Cargo.lock generated
View file

@ -800,18 +800,18 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "bytemuck"
version = "1.19.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8334215b81e418a0a7bdb8ef0849474f40bb10c8b71f1c4ed315cff49f32494d"
checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.10.1"
version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f154e572231cb6ba2bd1176980827e3d5dc04cc183a75dea38109fbdd672d29"
checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
dependencies = [
"proc-macro2",
"quote",

View file

@ -143,6 +143,8 @@ exclude = [
"libs/mass-storage/packing",
# This directory is dedicated to out-of-tree tests and examples
"planning/",
# This is for signing images, and requires dependencies that are incompatible with Xous
"signing/fido-signer"
]
[profile.release]

View file

@ -3,6 +3,7 @@ use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use bao1x_api::signatures::FunctionCode;
#[allow(unused_imports)]
use bao1x_api::*;
use bao1x_hal::acram::OneWayCounter;
@ -21,10 +22,13 @@ pub struct Repl {
cmdline: String,
do_cmd: bool,
local_echo: bool,
lockdown_armed: bool,
}
impl Repl {
pub fn new() -> Self { Self { cmdline: String::new(), do_cmd: false, local_echo: true } }
pub fn new() -> Self {
Self { cmdline: String::new(), do_cmd: false, local_echo: true, lockdown_armed: false }
}
#[allow(dead_code)]
pub fn init_cmd(&mut self, cmd: &str) {
@ -69,6 +73,32 @@ impl Repl {
let mut parts = self.cmdline.split_whitespace();
let cmd = parts.next().unwrap_or("").to_string();
let args: Vec<String> = parts.map(|s| s.to_string()).collect();
// process two-phase lockdown command
if self.lockdown_armed {
if args.len() == 0 && cmd.as_str() == "YES" {
let owc = OneWayCounter::new();
let devkey_offsets = [
("loader", LOADER_REVOCATION_OFFSET + bao1x_api::pubkeys::DEVELOPER_KEY_SLOT),
("boot0", BOOT0_REVOCATION_OFFSET + bao1x_api::pubkeys::DEVELOPER_KEY_SLOT),
("boot1", BOOT1_REVOCATION_OFFSET + bao1x_api::pubkeys::DEVELOPER_KEY_SLOT),
];
for &(desc, devkey) in devkey_offsets.iter() {
match unsafe { owc.inc(devkey) } {
Ok(_) => crate::println!("{} locked", desc),
Err(e) => crate::println!("Couldn't lock {}: {:?}", desc, e),
}
}
} else {
crate::println!("Lockdown aborted.");
}
self.lockdown_armed = false;
self.abort_cmd();
return Ok(());
}
self.lockdown_armed = false;
// now process any further commands
match cmd.as_str() {
"reset" => {
let mut rcurst = CSR::new(utra::sysctrl::HW_SYSCTRL_BASE as *mut u32);
@ -168,6 +198,120 @@ impl Repl {
}
crate::println!("Board type set to {:?} after {} increments", new_type, count);
}
"audit" => {
let owc = OneWayCounter::new();
crate::println!(
"Board type reads as: {:?}",
owc.get_decoded::<bao1x_api::offsets::BoardTypeCoding>()
);
crate::println!(
"Boot partition is: {:?}",
owc.get_decoded::<bao1x_api::offsets::AltBootCoding>()
);
crate::println!("Revocations:");
crate::println!("Stage key0 key1 key2 key3");
let key_array = [
("boot0 ", BOOT0_REVOCATION_OFFSET),
("boot1 ", BOOT1_REVOCATION_OFFSET),
("next stage ", LOADER_REVOCATION_OFFSET),
];
for (img_type, start) in key_array {
crate::print!("{}", img_type);
for offset in start..(start + PUBKEY_SLOTS) {
if owc.get(offset).unwrap_or(1) == 0 {
crate::print!("enabled ");
} else {
crate::print!("revoked ");
}
}
crate::println!("");
}
match bao1x_hal::sigcheck::validate_image(
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_REVOCATION_OFFSET,
&[FunctionCode::Boot0 as u32],
false,
None,
) {
Ok((k, tag)) => crate::println!(
"Boot0: key {} ({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Boot0 did not validate: {:?}", e),
}
match bao1x_hal::sigcheck::validate_image(
bao1x_api::BOOT1_START as *const u32,
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_REVOCATION_OFFSET,
&[
FunctionCode::Boot1 as u32,
FunctionCode::UpdatedBoot1 as u32,
FunctionCode::Developer as u32,
],
false,
None,
) {
Ok((k, tag)) => crate::println!(
"Boot1: key {} ({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Boot1 did not validate: {:?}", e),
}
match bao1x_hal::sigcheck::validate_image(
bao1x_api::LOADER_START as *const u32,
bao1x_api::BOOT1_START as *const u32,
bao1x_api::BOOT1_REVOCATION_OFFSET,
&crate::secboot::ALLOWED_FUNCTIONS,
false,
None,
) {
Ok((k, tag)) => crate::println!(
"Next stage: key {} ({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Next stage did not validate: {:?}", e),
}
// TODO:
// - devboot seen
// - oem keys erased
// - uuid
}
"lockdown" => {
match bao1x_hal::sigcheck::validate_image(
bao1x_api::BOOT1_START as *const u32,
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_REVOCATION_OFFSET,
&[
FunctionCode::Boot1 as u32,
FunctionCode::UpdatedBoot1 as u32,
FunctionCode::Developer as u32,
],
false,
None,
) {
Ok((k, _tag)) => {
if k != bao1x_api::pubkeys::DEVELOPER_KEY_SLOT {
crate::println!(
"This will permanently disable developer mode. It cannot be undone!"
);
crate::println!("Proceed? (type 'YES' in all caps to proceed)");
self.lockdown_armed = true;
} else {
crate::println!(
"Boot1 is signed with the developer key. Refusing to lockdown, as that would brick the chip."
)
}
}
Err(_e) => {
crate::println!("Boot1 has no valid signature, lockdown would brick the chip.")
}
}
}
#[cfg(feature = "unsafe-debug")]
"peek" => {
const COLUMNS: usize = 4;
@ -206,7 +350,9 @@ impl Repl {
}
_ => {
crate::println!("Command not recognized: {}", cmd);
crate::print!("Commands include: reset, echo, boot, bootwait, localecho, uf2, boardtype");
crate::print!(
"Commands include: reset, echo, boot, bootwait, localecho, uf2, boardtype, audit, lockdown"
);
crate::println!("");
}
}

View file

@ -1,6 +1,6 @@
use bao1x_api::signatures::FunctionCode;
const ALLOWED_FUNCTIONS: [u32; 5] = [
pub const ALLOWED_FUNCTIONS: [u32; 5] = [
FunctionCode::Baremetal as u32,
FunctionCode::UpdatedBaremetal as u32,
FunctionCode::Loader as u32,
@ -32,7 +32,11 @@ pub fn boot_or_die() -> ! {
true,
None,
) {
Ok(k) => crate::println!("**should be unreachable** Booted with key {}", k),
Ok((k, tag)) => crate::println!(
"**should be unreachable** Booted with key {}({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Image did not validate: {:?}", e),
}
crate::println!("No valid loader or baremetal image found. Halting!");

View file

@ -13,7 +13,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [
"std",
"alloc",
], optional = true }
bytemuck = { version = "1.0", features = ["derive"] }
bytemuck = { version = "1.24", features = ["derive"] }
bitbybit = "1.4.0"
[features]

View file

@ -16,6 +16,7 @@ pub mod offsets;
pub mod sce;
pub mod signatures;
pub use offsets::*;
pub mod pubkeys;
/// UF2 Family ID. Randomly generated, no collisions with the known list, still to be merged
/// into the "official" list

View file

@ -96,3 +96,5 @@ pub const BOOT1_REVOCATION_OFFSET: usize = LOADER_REVOCATION_OFFSET + PUBKEY_SLO
/// Offset in the one-way counter array for boot0 key revocations. Provisions for up to four
/// key slots, from [124..=127].
pub const BOOT0_REVOCATION_OFFSET: usize = BOOT1_REVOCATION_OFFSET + PUBKEY_SLOTS;
// slots from 128..=255 are totally unused by the boot logic

View file

@ -0,0 +1,18 @@
/// ===== PLACEHOLDER - bao2 signing HSM ceremony pending ======
#[allow(unused_imports)]
use super::*;
use crate::signatures::Pubkey;
/// Bao1 public key. Will be extracted from signing/bao1_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_PUB: [u8; 32] = [0u8; 32];
/// Bao1 public key "key handle"
pub const ID_ED25519_SK_CRED_ID: [u8; 241] = [0u8; 241];
/// Bao1 public key "relying party"
pub const ID_ED25519_SK_RP: &'static str = "ssh:";
pub const PUBKEY: Pubkey = Pubkey {
pk: ID_ED25519_SK_PUB,
// Placeholder: tag is 0.
tag: [0u8; 4], // *KEYSLOT_INITIAL_TAGS[BAO1_KEY_SLOT],
};

View file

@ -0,0 +1,18 @@
/// ===== PLACEHOLDER - bao2 signing HSM ceremony pending ======
#[allow(unused_imports)]
use super::*;
use crate::signatures::Pubkey;
/// Bao1 public key. Will be extracted from signing/bao1_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_PUB: [u8; 32] = [0u8; 32];
/// Bao1 public key "key handle"
pub const ID_ED25519_SK_CRED_ID: [u8; 241] = [0u8; 241];
/// Bao1 public key "relying party"
pub const ID_ED25519_SK_RP: &'static str = "ssh:";
pub const PUBKEY: Pubkey = Pubkey {
pk: ID_ED25519_SK_PUB,
// Placeholder: tag is 0.
tag: [0u8; 4], // *KEYSLOT_INITIAL_TAGS[BAO2_KEY_SLOT],
};

View file

@ -0,0 +1,33 @@
use super::*;
use crate::signatures::Pubkey;
/// Beta public key. Extracted from signing/beta_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_PUB: [u8; 32] = [
0x80, 0x97, 0x99, 0x29, 0xed, 0xd0, 0x4e, 0x40, 0x12, 0x4b, 0x52, 0xca, 0xe9, 0xae, 0x54, 0xb2, 0x4b,
0xdf, 0xf7, 0x2a, 0x7b, 0x8a, 0x00, 0x4c, 0x41, 0x06, 0x5b, 0xd1, 0x40, 0x20, 0x78, 0xa7,
];
/// Beta public key "key handle" - used to retrieve the key for signing from the token.
/// Extracted from signing/beta_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_CRED_ID: [u8; 241] = [
0x01, 0x06, 0x60, 0x8b, 0xfa, 0x05, 0x28, 0x24, 0x0d, 0x5b, 0x33, 0x92, 0x1b, 0xb1, 0x38, 0x4e, 0xbe,
0xae, 0xf3, 0xe4, 0x73, 0x7a, 0x5e, 0xb2, 0xd0, 0x7e, 0x77, 0x80, 0x5b, 0x88, 0xcb, 0x1e, 0xd6, 0xea,
0xfc, 0x75, 0xd4, 0x21, 0xc9, 0x41, 0xfa, 0x8d, 0x09, 0xe2, 0x4b, 0x4a, 0x4c, 0xec, 0x98, 0x85, 0xdd,
0x76, 0xc0, 0xfd, 0xa1, 0x66, 0x0c, 0x4d, 0x6e, 0x72, 0xe4, 0xf3, 0xba, 0x6b, 0xba, 0xc0, 0x68, 0xc8,
0x75, 0x32, 0x7b, 0x4f, 0x4d, 0xbd, 0xab, 0x87, 0x36, 0x80, 0xe7, 0x52, 0x58, 0x28, 0x84, 0xf1, 0xb7,
0x80, 0xd1, 0xfc, 0xb0, 0xde, 0xcd, 0x53, 0x00, 0x7e, 0x7a, 0x6b, 0x5b, 0x8c, 0x61, 0x81, 0xea, 0x74,
0xf1, 0xb5, 0x73, 0xde, 0x72, 0x99, 0x2d, 0x2c, 0x07, 0x96, 0x5f, 0x5c, 0x81, 0x08, 0x75, 0xed, 0x11,
0xf3, 0x42, 0x43, 0x66, 0x8b, 0x18, 0xeb, 0x99, 0x42, 0x56, 0x8c, 0x57, 0x8f, 0x7c, 0x03, 0xfa, 0xbf,
0x6e, 0xbd, 0xc8, 0x19, 0xc9, 0x48, 0xd9, 0xc9, 0x69, 0xef, 0x2b, 0xb1, 0x26, 0x6c, 0xd0, 0xd1, 0xa0,
0xd5, 0x2e, 0x1c, 0x37, 0xe3, 0x23, 0x6a, 0x07, 0x56, 0xe5, 0x41, 0x0f, 0x31, 0x7e, 0x62, 0x28, 0xb1,
0x08, 0x85, 0xc8, 0x33, 0xaa, 0xae, 0x94, 0xa8, 0x89, 0x7b, 0xe4, 0x6f, 0xb6, 0x7b, 0xd4, 0xc8, 0xc2,
0x6b, 0x01, 0x21, 0x16, 0x2c, 0xb0, 0x46, 0x15, 0xae, 0xf8, 0x2c, 0x6a, 0x6e, 0x6f, 0xa7, 0x6b, 0x9c,
0x5f, 0x03, 0x4a, 0x3d, 0xda, 0x15, 0x04, 0xcd, 0x2e, 0x09, 0x9d, 0xcc, 0x1d, 0x03, 0xff, 0xb8, 0x2b,
0xe4, 0x97, 0xfe, 0x96, 0x1f, 0x7a, 0x4a, 0xd8, 0x6b, 0x7d, 0x6c, 0xcd, 0x73, 0x3f, 0xaa, 0xfe, 0x94,
0x4a, 0x85, 0x8b,
];
/// Beta public key "relying party"
/// Extracted from signing/beta_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_RP: &'static str = "ssh:";
pub const PUBKEY: Pubkey = Pubkey { pk: ID_ED25519_SK_PUB, tag: *KEYSLOT_INITIAL_TAGS[BETA_KEY_SLOT] };

View file

@ -0,0 +1,11 @@
use super::*;
use crate::signatures::Pubkey;
/// Developer public key. The private key is the devkey/ directory, included here for your
/// convenience: "MC4CAQAwBQYDK2VwBCIEIKindlyNoteThisIsADevKeyDontUseForProduction" (base64)
pub const PUB: [u8; 32] = [
0x1c, 0x9b, 0xea, 0xe3, 0x2a, 0xea, 0xc8, 0x75, 0x07, 0xc1, 0x80, 0x94, 0x38, 0x7e, 0xff, 0x1c, 0x74,
0x61, 0x42, 0x82, 0xaf, 0xfd, 0x81, 0x52, 0xd8, 0x71, 0x35, 0x2e, 0xdf, 0x3f, 0x58, 0xbb,
];
pub const PUBKEY: Pubkey = Pubkey { pk: PUB, tag: *KEYSLOT_INITIAL_TAGS[DEVELOPER_KEY_SLOT] };

View file

@ -0,0 +1,40 @@
use crate::signatures::Pubkey;
pub mod bao1;
pub mod bao2;
pub mod beta;
pub mod developer;
pub const BAO1_KEY_SLOT: usize = 0;
pub const BAO2_KEY_SLOT: usize = 1;
pub const BETA_KEY_SLOT: usize = 2;
pub const DEVELOPER_KEY_SLOT: usize = 3;
/// Nominal purposes of pub key slots:
/// - slot 0 is Baochip secured signing key 1
/// - slot 1 is Baochip secured signing key 2
/// - slot 2 is a Beta signing key. It's kept in a secured token but also available in a development
/// environment.
/// - slot 3 is the Developer signing key. It's a well-known key that anyone can use to sign an image. If
/// revoked, it is not a valid signing key. When not revoked, upon being presented with an image signed by
/// this, the bootloader will automatically erase all device-local secrets.
///
/// The dual signing keys for Baochip allows for a laddered upgrade path in case a signing key
/// needs to be replaced, upgraded, or cycled out for any reason.
pub const KEYSLOT_INITIAL_TAGS: [&'static [u8; 4]; 4] = [b"bao1", b"bao2", b"beta", b"dev "];
// helper function to pad arrays out, if needed. Previously used for auth_data until
// I realized that auth_data changes with every signing.
#[allow(dead_code)]
const fn pad_array<const N: usize, const M: usize>(input: &[u8; N]) -> [u8; M] {
let mut result = [0u8; M];
let mut i = 0;
while i < N && i < M {
result[i] = input[i];
i += 1;
}
result
}
/// This is the exported record that should be copied into the header of all boot images
pub const PUBKEY_HEADER: [Pubkey; 4] = [bao1::PUBKEY, bao2::PUBKEY, beta::PUBKEY, developer::PUBKEY];

View file

@ -1,11 +1,15 @@
use bytemuck::{Pod, Zeroable};
pub const SIGBLOCK_LEN: usize = 768; // this is adjusted inside builder.rs, in the sign-image invocation
// The jump instruction and the signature itself are not protected
pub const UNSIGNED_LEN: usize = size_of::<u32>() + SIGNATURE_LENGTH;
/// Total reserved space for the signature block
pub const SIGBLOCK_LEN: usize = 768;
/// The jump instruction and the signature itself are not protected
pub const UNSIGNED_LEN: usize = SignatureInFlash::sealed_data_offset();
// These are vendored in so we don't have a circular dependency on ed25519 crate
pub const SIGNATURE_LENGTH: usize = 64; // length of an ed25519 signature.
pub const PUBLIC_KEY_LENGTH: usize = 32; // length of an ed25519 public key.
pub const AAD_LENGTH: usize = 60; // at least 37 bytes, rounded up to the nearest 32-byte boundary
/// These are notional and subject to change
#[repr(u32)]
#[derive(PartialEq, Eq, Clone, Copy)]
@ -40,7 +44,8 @@ pub enum FunctionCode {
}
pub const BAOCHIP_SIG_VERSION: u32 = 0x1_00;
pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::<SealedFields>() - SIGNATURE_LENGTH - size_of::<u32>();
pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::<SignatureInFlash>();
pub const MAGIC_NUMBER: [u32; 2] = [u32::from_be_bytes(*b"yumy"), u32::from_be_bytes(*b"Bao3")];
/// Representation of the signature block in memory.
#[repr(C)]
#[derive(Copy, Clone)]
@ -50,10 +55,17 @@ pub struct SignatureInFlash {
pub _jal_instruction: u32,
/// The actual signature.
pub signature: [u8; SIGNATURE_LENGTH],
/// `aad_len` also specifies the signing protocol. If it is `0`, then a pure `ed25519ph`
/// signature is assumed. If it is greater than `0`, then it's assumed to be a
/// FIDO2/WebAuthn signature format using ed25519, where the signature is computed as:
/// `signature = Ed25519.sign(authenticatorData || SHA-256(clientData))`
/// `authenticatorData` is a field that is at least 37 bytes in size. The size is influenced
/// by the type of signing and operation, but for our implementation I think it stays
/// fixed at 37 bytes.
pub aad_len: u32,
pub aad: [u8; AAD_LENGTH],
/// All data from this point onward are included in the signature computation.
pub sealed_data: SealedFields,
/// Padding to target length
pub padding: [u8; PADDING_LEN],
}
unsafe impl Zeroable for SignatureInFlash {}
unsafe impl Pod for SignatureInFlash {}
@ -68,17 +80,44 @@ impl Default for SignatureInFlash {
Self {
_jal_instruction: 0,
signature: [0u8; SIGNATURE_LENGTH],
aad_len: 0,
aad: [0u8; AAD_LENGTH],
sealed_data: SealedFields::default(),
padding: [0u8; PADDING_LEN],
}
}
}
impl SignatureInFlash {
// The offset is after the jal instruction + signature.
pub const fn sealed_data_offset() -> usize {
size_of::<u32>() + SIGNATURE_LENGTH + size_of::<u32>() + AAD_LENGTH
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Pubkey {
pub pk: [u8; PUBLIC_KEY_LENGTH],
pub tag: [u8; 4],
}
unsafe impl Zeroable for Pubkey {}
unsafe impl Pod for Pubkey {}
impl Default for Pubkey {
fn default() -> Self { Self { pk: [0u8; PUBLIC_KEY_LENGTH], tag: [0u8; 4] } }
}
impl Pubkey {
pub fn populate_from(&mut self, record: &Pubkey) {
self.pk.copy_from_slice(&record.pk);
self.tag.copy_from_slice(&record.tag);
}
}
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub struct SealedFields {
/// Version number of this signature record
pub version: u32,
/// Magic number, to quickly differentiate uninitialized memory from a valid signature record
pub magic: [u32; 2],
/// Length of the signed code.
pub signed_len: u32,
/// Function code of the signed block. Used to provide metadata about what is inside the signed
@ -106,7 +145,7 @@ pub struct SealedFields {
/// is erased and boot is allowed to proceed.
///
/// If no valid keys are found, the device is effectively bricked and goes into a "die" state.
pub pubkeys: [[u8; PUBLIC_KEY_LENGTH]; 4],
pub pubkeys: [Pubkey; 4],
}
impl AsRef<[u8]> for SealedFields {
@ -115,13 +154,14 @@ impl AsRef<[u8]> for SealedFields {
impl Default for SealedFields {
fn default() -> Self {
Self {
version: 0,
version: BAOCHIP_SIG_VERSION,
magic: MAGIC_NUMBER,
signed_len: 0,
function_code: 0,
reserved: 0,
min_semver: [0u8; 16],
semver: [0u8; 16],
pubkeys: [[0u8; PUBLIC_KEY_LENGTH]; 4],
pubkeys: [Pubkey::default(); 4],
}
}
}

View file

@ -9,9 +9,11 @@ pub const ACRAM_DATASLOT_START: usize = 0x603D_C000;
pub const ACRAM_KEYSLOT_START: usize = 0x603D_E000;
// pub const ACRAM_GKEYSLOT_START: usize = 0x603D_E400; // This is mentioned in the docs but I don't see it in
// the code?
pub const ONEWAY_START: usize = 0x603D_A000;
pub const ONEWAY2_START: usize = 0x603D_B000;
pub const ONEWAY_LEN: usize = 2048; // in u32-sized elements
pub const ONEWAY_START: usize = 0x603D_A000; // page with 128 counters
pub const ONEWAY2_START: usize = 0x603D_B000; // page with another 128 counters
const ONEWAY_LEN: usize = 256 / 8; // in bytes
const COUNTER_STRIDE_U32: usize = ONEWAY_LEN / size_of::<u32>();
pub const MAX_ONEWAY_COUNTERS: usize = 8192 / ONEWAY_LEN;
pub const CODESEL_END: usize = 0x603D_A000;
#[bitfield(u32)]
@ -94,7 +96,6 @@ pub struct OneWayCounter {
#[cfg(feature = "std")]
mapping: MemoryRange,
}
const COUNTER_STRIDE_U32: usize = 8;
impl OneWayCounter {
pub fn new() -> Self {
#[cfg(not(feature = "std"))]
@ -103,9 +104,9 @@ impl OneWayCounter {
#[cfg(feature = "std")]
let ret = OneWayCounter {
mapping: xous::syscall::map_memory(
xous::MemoryAddress::new(ONEWAY2_START),
xous::MemoryAddress::new(ONEWAY_START),
None,
ONEWAY_LEN * size_of::<u32>(),
ONEWAY_LEN * MAX_ONEWAY_COUNTERS,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map oneway range"),
@ -119,7 +120,7 @@ impl OneWayCounter {
let base = ONEWAY_START as *const u32;
#[cfg(feature = "std")]
let base = self.mapping.as_ptr() as *const u32;
if offset < ONEWAY_LEN {
if offset < MAX_ONEWAY_COUNTERS {
// safety: only safe because the pointer is length-checked
// we use this form to access the array because we need to read_volatile()
Ok(unsafe { base.add(offset * COUNTER_STRIDE_U32).read_volatile() })
@ -139,7 +140,7 @@ impl OneWayCounter {
#[cfg(feature = "std")]
let base = self.mapping.as_mut_ptr() as *mut u32;
if offset < ONEWAY_LEN {
if offset < MAX_ONEWAY_COUNTERS {
let starting_value = self.get(offset).unwrap(); // offset is already checked
// this will cause the increment in hardware
unsafe { base.add(offset * COUNTER_STRIDE_U32).write_volatile(0) }
@ -165,7 +166,7 @@ impl OneWayCounter {
let base = self.mapping.as_mut_ptr() as *mut u32;
let offset = T::OFFSET;
if offset < ONEWAY_LEN {
if offset < MAX_ONEWAY_COUNTERS {
let starting_value = self.get(offset).unwrap(); // offset is already checked
// this will cause the increment in hardware
unsafe { base.add(offset * COUNTER_STRIDE_U32).write_volatile(0) }

View file

@ -1,9 +1,10 @@
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use bao1x_api::signatures::*;
use digest::Digest;
use sha2_bao1x::Sha512;
use sha2_bao1x::{Sha256, Sha512};
use xous::arch::PAGE_SIZE;
use crate::acram::OneWayCounter;
@ -33,7 +34,7 @@ use crate::udma::Spim;
/// the wrong phase of the boot sequence. Passed as a list of u32-values that are allowed.
///
/// `auto_jump` is a flag which, when `true`, causes the code to diverge into the signed block.
/// If `false` the function returns the key index of the first passing public key, or an error
/// If `false` the function returns the `(key_index, tag)` of the first passing public key, or an error
/// if none were found.
pub fn validate_image(
img_offset: *const u32,
@ -42,7 +43,7 @@ pub fn validate_image(
function_codes: &[u32],
auto_jump: bool,
mut spim: Option<&mut Spim>,
) -> Result<usize, String> {
) -> Result<(usize, [u8; 4]), String> {
// Copy the signature into a structure so we can unpack it.
let mut sig = SignatureInFlash::default();
if let Some(ref mut spim) = spim {
@ -56,9 +57,15 @@ pub fn validate_image(
let pubkey_ptr = pubkeys_offset as *const SignatureInFlash;
let pk_src: &SignatureInFlash = unsafe { pubkey_ptr.as_ref().unwrap() };
if pk_src.sealed_data.magic != MAGIC_NUMBER {
return Err(String::from("Invalid magic number in verifying key record"));
}
let signed_len = sig.sealed_data.signed_len;
if sig.sealed_data.magic != MAGIC_NUMBER {
return Err(String::from("Invalid magic number on incoming record to be verified"));
}
if sig.sealed_data.version != BAOCHIP_SIG_VERSION {
crate::println!(
"Version {:x} sig found, should be {:x}",
@ -77,11 +84,12 @@ pub fn validate_image(
let developer = sig.sealed_data.function_code == FunctionCode::Developer as u32;
// crate::println!("Signature: {:x?}", sig.signature);
let one_way_counters = OneWayCounter::new();
let mut secure = false;
let mut passing_key: Option<usize> = None;
for (i, key) in pk_src.sealed_data.pubkeys.iter().enumerate() {
if key.iter().all(|&x| x == 0) {
if key.tag == [0u8; 4] {
continue;
}
let revocation_value = one_way_counters.get(revocation_offset + i).expect("internal error");
@ -90,9 +98,10 @@ pub fn validate_image(
continue;
}
let verifying_key =
ed25519_dalek::VerifyingKey::from_bytes(key).or(Err(String::from("invalid public key")))?;
ed25519_dalek::VerifyingKey::from_bytes(&key.pk).or(Err(String::from("invalid public key")))?;
let ed25519_signature = ed25519_dalek::Signature::from(sig.signature);
let mut h: Sha512 = Sha512::new();
if let Some(ref mut spim) = spim {
// need to read the data out page by page and hash it.
@ -113,24 +122,61 @@ pub fn validate_image(
signed_len as usize,
)
};
// crate::println!("Verifying image {:x?} with {:x?}", &image[..16], &key);
h.update(&image);
}
// debugging note: h.clone() does *not* work. You have to print the hash by modifying
// the function inside the ed25519 crate.
match verifying_key.verify_prehashed(h, None, &ed25519_signature) {
Ok(_) => {
passing_key = Some(i);
if i != sig.sealed_data.pubkeys.len() - 1 {
secure = true;
break;
} else if i == sig.sealed_data.pubkeys.len() - 1 {
// this is the developer key slot
secure = false;
break;
if sig.aad_len == 0 {
// crate::println!("ed25519ph verifying with {:x?}", &key.pk);
// debugging note: h.clone() does *not* work. You have to print the hash by modifying
// the function inside the ed25519 crate.
match verifying_key.verify_prehashed(h, None, &ed25519_signature) {
Ok(_) => {
crate::println!("ed25519ph verification passed");
passing_key = Some(i);
if i != sig.sealed_data.pubkeys.len() - 1 {
secure = true;
break;
} else if i == sig.sealed_data.pubkeys.len() - 1 {
// this is the developer key slot
secure = false;
break;
}
}
_ => {
crate::println!("ed25519ph verification failed");
}
}
} else {
let sha512_hashed_image = h.finalize();
// create a *new* hasher because a token can only sign a hash, not the full image.
let mut h: Sha256 = Sha256::new();
// hash dat hash!
// crate::println!("verifying base hash {:x?}", &sha512_hashed_image.as_slice());
h.update(&sha512_hashed_image.as_slice());
let hashed_hash = h.finalize();
// crate::println!("hashed hash: {:x?}", hashed_hash.as_slice());
let mut msg: Vec<u8> = Vec::new();
msg.extend_from_slice(&sig.aad[..sig.aad_len as usize]);
msg.extend_from_slice(hashed_hash.as_slice());
// crate::println!("assembled msg({}): {:x?}", msg.len(), msg);
match verifying_key.verify_strict(&msg, &ed25519_signature) {
Ok(_) => {
crate::println!("FIDO2 ed25519 verification passed");
passing_key = Some(i);
if i != sig.sealed_data.pubkeys.len() - 1 {
secure = true;
break;
} else if i == sig.sealed_data.pubkeys.len() - 1 {
// this is the developer key slot
secure = false;
break;
}
}
_ => {
crate::println!("FIDO2 verification failed");
}
}
_ => {}
}
}
@ -141,7 +187,7 @@ pub fn validate_image(
if auto_jump {
jump_to(img_offset as usize);
}
Ok(valid_key)
Ok((valid_key, pk_src.sealed_data.pubkeys[valid_key].tag))
} else {
Err(String::from("No valid pubkeys found or signature invalid"))
}

View file

@ -266,7 +266,11 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
false,
None,
) {
Ok(k) => println!("*** Kernel signature check by key @ {} OK ***", k),
Ok((k, tag)) => println!(
"*** Kernel signature check by key @ {}({}) OK ***",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => {
println!("Kernel failed signature check. Dying: {:?}", e);
bao1x_hal::sigcheck::die_no_std();
@ -285,8 +289,12 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
false,
None,
) {
Ok(k) => {
println!("*** Detached app signature check by key @ {} OK ***", k);
Ok((k, tag)) => {
println!(
"*** Detached app signature check by key @ {}({}) OK ***",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
);
true
}
Err(_e) => {

28
signing/README.md Normal file
View file

@ -0,0 +1,28 @@
# Image Signing and Deployment
The scripts in this directory are used for image signing and deployment.
The primary method for securing images is by signing them with a Precursor or Baochip device. There is a `beta` key, which is kept within such a device, but the device is regularly accessible for testing purposes. There is also at least one `deployment` key, which is kept in a similar device, but the device is kept in a physically secured location and deploying it requires some ceremony and effort.
Here is the flow for generating and deploying signatures:
## Preparation
1. The "HSM" (as it may be -- really just a signing token) is a Precursor/Baochip device. The signature type is `ed25519`. The device is primed with a PIN like a normal FIDO device.
1. A residential SSH key is created on the device using `ssh-keygen -t ed25519-sk`
1. The "private key" resulting from this contains the credential ID, public key, relying party,
## Signing
2. The image to be signed is fed into `fido-signer`:
1. The signing token must be connected to the computer
2. The PIN must be provided by the signer
3. Depending on the host, this may need to run at an elevated privilege level (Windows in particular enforces that)
3. Assuming the prequisites are met, `fido-signer` patches a unified signed Baochip image to inject the `signature` and `auth_data` into the designated key slot. It also generates a `.uf2` file for convenience.
In the case that a `deployment` key is used, additional physical security measures are invoked, a list of which are not publicly documented because in physical security, obscurity and the element of surprise are valid and useful countermeasures.
## Other notes
The `credentials` directory is in the `.gitignore` and should not be checked in. If you see a `credentials` directory in the tree, there was an operational security problem.
That being said, `credentials` does *not* store the actual private key used for signing. The main thing the directory contains is the PIN to unlock the signing token, which is a secondary security precaution.

View file

@ -0,0 +1 @@
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDo= bunnie@bunnie-desktop

View file

@ -0,0 +1,12 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAASgAAABpzay1zc2
gtZWQyNTUxOUBvcGVuc3NoLmNvbQAAACCAl5kp7dBOQBJLUsrprlSyS9/3KnuKAExBBlvR
QCB4pwAAAARzc2g6AAABaBoLZaIaC2WiAAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY2
9tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDoBAAAA8QEG
YIv6BSgkDVszkhuxOE6+rvPkc3pestB+d4BbiMse1ur8ddQhyUH6jQniS0pM7JiF3XbA/a
FmDE1ucuTzumu6wGjIdTJ7T029q4c2gOdSWCiE8beA0fyw3s1TAH56a1uMYYHqdPG1c95y
mS0sB5ZfXIEIde0R80JDZosY65lCVoxXj3wD+r9uvcgZyUjZyWnvK7EmbNDRoNUuHDfjI2
oHVuVBDzF+YiixCIXIM6qulKiJe+RvtnvUyMJrASEWLLBGFa74LGpub6drnF8DSj3aFQTN
LgmdzB0D/7gr5Jf+lh96SthrfWzNcz+q/pRKhYsAAAAAAAAAFWJ1bm5pZUBidW5uaWUtZG
Vza3RvcAECAw==
-----END OPENSSH PRIVATE KEY-----

View file

@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""
Extract FIDO/U2F credential id (key_handle) from an OpenSSH sk private key.
Usage:
python3 extract_sk_credential.py /path/to/id_ed25519_sk
cat /path/to/id_ed25519_sk | python3 extract_sk_credential.py -
"""
import sys, argparse, base64, struct
from pathlib import Path
def read_u32(buf, off):
if off+4 > len(buf):
raise ValueError("unexpected end while reading u32")
return struct.unpack(">I", buf[off:off+4])[0], off+4
def read_string(buf, off):
l, off = read_u32(buf, off)
if off + l > len(buf):
raise ValueError("unexpected end while reading string")
return buf[off:off+l], off + l
def read_byte(buf, off):
if off >= len(buf):
raise ValueError("unexpected end while reading byte")
return buf[off], off+1
def extract_key_info(priv_blob):
# priv_blob layout: two checkints, then for each key:
# string keytype
# string pubkey_blob
# string privkey_blob
off = 0
_, off = read_u32(priv_blob, off)
_, off = read_u32(priv_blob, off)
key_type, off = read_string(priv_blob, off)
print(f"Key type: {key_type.decode('utf-8')}")
pubkey_blob, off = read_string(priv_blob, off)
relying_party, off = read_string(priv_blob, off)
print(f"Relying party: {relying_party.decode('utf-8')}")
flags, off = read_byte(priv_blob, off)
key_handle, off = read_string(priv_blob, off)
return (pubkey_blob, key_handle)
def load_openssh_private(data_bytes):
b = data_bytes.strip()
if b.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"):
body = b.split(b"-----BEGIN OPENSSH PRIVATE KEY-----",1)[1]
body = body.split(b"-----END OPENSSH PRIVATE KEY-----",1)[0]
body = b"".join(body.splitlines())
raw = base64.b64decode(body)
else:
# try base64 decode; if invalid, assume already binary openssh blob
try:
raw = base64.b64decode(b, validate=True)
except Exception:
raw = data_bytes
return raw
def extract_from_file(path):
data = sys.stdin.buffer.read() if path == "-" else open(path, "rb").read()
raw = load_openssh_private(data)
magic = b"openssh-key-v1\0"
if not raw.startswith(magic):
raise ValueError("not an openssh-key-v1 private key (magic mismatch)")
off = len(magic)
# string ciphername, string kdfname, string kdfoptions, uint32 nkeys
_, off = read_string(raw, off)
_, off = read_string(raw, off)
_, off = read_string(raw, off)
nkeys, off = read_u32(raw, off)
for _ in range(nkeys):
_, off = read_string(raw, off) # public key blob(s)
priv_block, off = read_string(raw, off)
return extract_key_info(priv_block)
def main():
p = argparse.ArgumentParser(description="Extract FIDO/U2F key_handle (credential id) from an OpenSSH sk private key")
p.add_argument("infile", nargs="?", default="./testing_id_ed25519_sk", help="private key file (PEM or base64). Use '-' for stdin")
args, _ = p.parse_known_args()
infile = Path(args.infile)
try:
(pubkey_blob, key_handle) = extract_from_file(infile)
except Exception as e:
sys.stderr.write("ERROR: " + str(e) + "\n")
sys.exit(2)
name = infile.stem.upper()
pubkey_formatted = ', '.join(f"0x{byte:02x}" for byte in pubkey_blob)
print(f"pub const {name}_PUB: [u8; 32] = [{pubkey_formatted}];")
print(f"pubkey base64: {base64.b64encode(pubkey_blob)}")
key_handle_formatted = ', '.join(f"0x{byte:02x}" for byte in key_handle)
print(f"pub const {name}_CRED_ID: [u8; {len(key_handle)}] = [{key_handle_formatted}];")
print(f"cred id base64: {base64.b64encode(key_handle)}")
if __name__ == "__main__":
main()

1261
signing/fido-signer/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,24 @@
[package]
name = "auth-sign-test"
version = "0.1.0"
edition = "2021"
[dependencies]
hex = "0.4"
ctap-hid-fido2 = "3.5.5"
clap = { version = "4.5", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
base64 = "0.22.1"
bao1x-api = { path = "../../libs/bao1x-api" }
sha2 = "0.10.9"
digest = "0.10"
byteorder = "1.2"
# For Windows USB support
[target.'cfg(windows)'.dependencies]
windows = { version = "0.48", features = [
"Win32_Devices_HumanInterfaceDevice",
] }

View file

@ -0,0 +1,343 @@
use std::fs;
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use bao1x_api::signatures::SignatureInFlash;
use base64::{Engine as _, engine::general_purpose};
use clap::{ArgGroup, Parser};
use ctap_hid_fido2::fidokey::get_assertion::get_assertion_params::Assertion;
use ctap_hid_fido2::{Cfg, FidoKeyHidFactory, fidokey::GetAssertionArgsBuilder};
use digest::Digest;
use serde::{Deserialize, Serialize};
use sha2::Sha512;
/// FIDO Signer - Sign messages or files using FIDO credentials
#[derive(Parser, Debug)]
#[command(
name = "fido-signer",
author = "bunnie",
about = "Sign messages and bao1x image files with a FIDO token"
)]
#[command(version, long_about = None)]
#[command(group(
ArgGroup::new("input")
.required(true)
.args(["message", "file"])
))]
struct Args {
/// Path to the credential file (JSON format)
#[arg(short = 'c', long, value_name = "FILE")]
credential_file: PathBuf,
/// Message to sign (base64 encoded)
#[arg(short = 'm', long, value_name = "BASE64_MESSAGE", conflicts_with = "file")]
message: Option<String>,
/// File to sign
#[arg(short = 'f', long, value_name = "FILE", conflicts_with = "message")]
file: Option<PathBuf>,
/// Function code e.g. partition - if provided, creates a uf2 file
#[arg(short = 'p', long = "function-code", value_name = "CODE")]
function_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
struct Credentials {
credential_id: String, // Base64 encoded, will be decoded to Vec<u8>
pin: String, // UTF-8 string
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Ed25519 Signing with FIDO2 Token");
println!("================================\n");
// Parse command line arguments
let args = Args::parse();
// Load and parse the credential file
let credential_data = fs::read_to_string(&args.credential_file)
.map_err(|e| format!("Failed to read credential file: {}", e))?;
let credentials: Credentials = serde_json::from_str(&credential_data)
.map_err(|e| format!("Failed to parse credential JSON: {}", e))?;
// Decode the credential_id from base64
let credential_id: Vec<u8> = general_purpose::STANDARD
.decode(&credentials.credential_id)
.map_err(|e| format!("Failed to decode credential_id: {}", e))?;
// Get the PIN as a string (already UTF-8)
let pin: String = credentials.pin;
// Determine what to sign
let mut is_bao1x = false;
let mut offset = 0;
let data_to_sign: Vec<u8> = if let Some(message_b64) = args.message {
// Decode message from base64 - used for testing signing operations with small pieces of temporary
// data
general_purpose::STANDARD
.decode(&message_b64)
.map_err(|e| format!("Failed to decode message: {}", e))?
} else if let Some(ref file_path) = args.file {
// Read file contents.
let file = fs::read(&file_path)
.map_err(|e| format!("Failed to read file '{}': {}", file_path.display(), e))?;
if let Some(ref code) = args.function_code {
// swap is a special case, its signature header is shifted in the image due to the presence
// of the swap metadata header
if code == "swap" {
offset = bao1x_api::offsets::baosec::SWAP_HEADER_LEN - bao1x_api::signatures::SIGBLOCK_LEN;
}
}
// Check to see if this is a signed bao1x binary, by looking at the magic number.
let mut sig = SignatureInFlash::default();
sig.as_mut().copy_from_slice(&file[offset..offset + size_of::<SignatureInFlash>()]);
if sig.sealed_data.magic == bao1x_api::signatures::MAGIC_NUMBER {
is_bao1x = true;
let mut h: Sha512 = Sha512::new();
// hash the sealed region
h.update(&file[offset + SignatureInFlash::sealed_data_offset()..]);
// finalize it and send it on for signing
h.finalize().as_slice().to_vec()
} else {
file
}
} else {
// This shouldn't happen due to clap's ArgGroup, but handle it just in case
return Err("Either --message or --file must be provided".into());
};
println!("Credential file: {:?}", args.credential_file);
println!("Credential ID (decoded): {} bytes", credential_id.len());
println!("PIN: [REDACTED]"); // Don't print the actual PIN
println!("Data to sign: {} bytes", data_to_sign.len());
// Sign the hash
// println!("Signing {:x?}", data_to_sign);
// let mut h_debug = sha2::Sha256::new();
// h_debug.update(&data_to_sign);
// let h_debug_final = h_debug.finalize();
// println!("hashed hash: {:x?}", h_debug_final.as_slice());
let assertion = sign_ed25519_hash(&credential_id, &data_to_sign, &pin)?;
println!("\n* Signing successful!");
println!("Signature length: {} bytes", assertion.signature.len());
if assertion.signature.len() == 64 {
println!("* Valid Ed25519 signature");
// Ed25519 signature components
let (r, s) = assertion.signature.split_at(32);
println!(" R (hex): {}", hex::encode(r));
println!(" S (hex): {}", hex::encode(s));
println!(" auth_data (hex): {}", hex::encode(&assertion.auth_data));
println!(" signature (b64): {}", general_purpose::STANDARD.encode(&assertion.signature));
println!(" auth_data (b64): {}", general_purpose::STANDARD.encode(&assertion.auth_data));
}
if is_bao1x {
if let Some(ref file_path) = args.file {
println!("Patching image file with signature...");
patch_signature_in_file(&file_path, &assertion.signature, &assertion.auth_data, offset)?;
}
if let Some(function_code) = args.function_code {
if let Some(input) = args.file {
let output = input.with_extension("uf2");
println!("Building image file for partition {}, writing to {:?}...", function_code, output);
convert_to_uf2(&input, &output, Some(&function_code), None)?
}
}
}
Ok(())
}
// Using the ctap-hid crate (Pure Rust, no C dependencies)
// #[cfg(feature = "pure-rust")]
fn sign_ed25519_hash(
credential_id: &[u8],
hash: &[u8],
pin: &str,
) -> Result<Assertion, Box<dyn std::error::Error>> {
let cfg = Cfg::init();
let mut devices = ctap_hid_fido2::get_fidokey_devices();
if devices.is_empty() {
return Err("No FIDO2 devices found".into());
}
let device = devices.pop().unwrap();
let fidokey = FidoKeyHidFactory::create_by_params(&[device.param], &cfg).unwrap();
// println!("Using key {:?}", fidokey.get_info().unwrap());
let assertion = GetAssertionArgsBuilder::new("ssh:", hash).pin(pin).credential_id(credential_id).build();
match fidokey.get_assertion_with_args(&assertion) {
Ok(mut a) => {
println!("Key used {} times", a[0].sign_count);
Ok(a.pop().unwrap())
}
Err(e) => Err(e.try_into().unwrap()),
}
}
fn patch_signature_in_file(
file_path: &PathBuf,
signature: &Vec<u8>,
auth_data: &Vec<u8>,
offset: usize,
) -> Result<(), Box<dyn std::error::Error>> {
// Open file with read and write permissions
let mut file = OpenOptions::new().read(true).write(true).open(file_path)?;
let mut signature_struct = read_header_from_file(&mut file, offset)?;
signature_struct.signature.copy_from_slice(&signature);
if auth_data.len() > signature_struct.aad.len() {
println!(
"Auth data returned by key is {} bytes and exceeds the capacity {} of the signature record",
auth_data.len(),
signature_struct.aad.len()
);
return Err(String::from("Auth data exceeds capacity of the signature field").into());
}
signature_struct.aad[..auth_data.len()].copy_from_slice(&auth_data);
signature_struct.aad_len = auth_data.len() as u32;
write_header_to_file(&mut file, &signature_struct, offset)?;
Ok(())
}
fn read_header_from_file(file: &mut std::fs::File, offset: usize) -> Result<SignatureInFlash, Box<dyn std::error::Error>> {
// Ensure we're at the beginning of the file
file.seek(SeekFrom::Start(offset as u64))?;
// Create a buffer for the struct
let struct_size = mem::size_of::<SignatureInFlash>();
let mut buffer = vec![0u8; struct_size];
// Read exactly the size of the struct
file.read_exact(&mut buffer)?;
let mut signature_struct = SignatureInFlash::default();
assert!(
signature_struct.sealed_data.magic == bao1x_api::signatures::MAGIC_NUMBER,
"Magic number does not match in bao header file!"
);
signature_struct.as_mut().copy_from_slice(&buffer);
Ok(signature_struct)
}
fn write_header_to_file(
file: &mut std::fs::File,
signature: &SignatureInFlash,
offset: usize,
) -> Result<(), Box<dyn std::error::Error>> {
// Seek back to the beginning where the struct starts
file.seek(SeekFrom::Start(offset as u64))?;
// Write the bytes back to the file
file.write_all(signature.as_ref())?;
// Ensure the data is flushed to disk
file.flush()?;
Ok(())
}
// ----- code below is vendored in from tools/src/sign_image.rs. Maybe this should be a library,
// but let's see what the e2e integration looks like before we puzzle on how to librarify-this.
pub fn convert_to_uf2<S, T>(
input: &S,
output: &T,
function_code: Option<&str>,
offset: Option<usize>,
) -> Result<(), Box<dyn std::error::Error>>
where
S: AsRef<Path>,
T: AsRef<Path>,
{
let mut source = vec![];
let mut source_file = std::fs::File::open(input)?;
let mut dest_file = std::fs::File::create(output)?;
source_file.read_to_end(&mut source)?;
let app_start_addr = match function_code {
Some("boot0") => bao1x_api::BOOT0_START,
Some("boot1") => bao1x_api::BOOT1_START,
Some("loader") => bao1x_api::LOADER_START,
Some("baremetal") => bao1x_api::BAREMETAL_START,
Some("kernel") => bao1x_api::KERNEL_START,
Some("swap") => bao1x_api::SWAP_START_UF2,
Some("app") => bao1x_api::dabao::APP_RRAM_START,
_ => return Err(String::from("UF2 Image Requires a function code").into()),
};
match bin_to_uf2(
&source,
bao1x_api::BAOCHIP_1X_UF2_FAMILY,
app_start_addr as u32 + offset.unwrap_or(0) as u32,
) {
Ok(u2f_blob) => {
dest_file.write_all(&u2f_blob)?;
Ok(())
}
Err(e) => Err(e.into()),
}
}
use byteorder::{LittleEndian, WriteBytesExt};
const UF2_MAGIC_START0: u32 = 0x0A324655; // "UF2\n"
const UF2_MAGIC_START1: u32 = 0x9E5D5157; // Randomly selected
const UF2_MAGIC_END: u32 = 0x0AB16F30; // Ditto
// Vendored in from https://github.com/sajattack/uf2conv-rs/blob/master/lib/src/lib.rs
// The code is MIT-licensed, and authored by Paul Sajna
pub fn bin_to_uf2(bytes: &Vec<u8>, family_id: u32, app_start_addr: u32) -> Result<Vec<u8>, std::io::Error> {
let datapadding = [0u8; 512 - 256 - 32 - 4];
let nblocks: u32 = ((bytes.len() + 255) / 256) as u32;
let mut outp: Vec<u8> = Vec::new();
for blockno in 0..nblocks {
let ptr = 256 * blockno;
let chunk = match bytes.get(ptr as usize..ptr as usize + 256) {
Some(bytes) => bytes.to_vec(),
None => {
let mut chunk = bytes[ptr as usize..bytes.len()].to_vec();
while chunk.len() < 256 {
chunk.push(0);
}
chunk
}
};
let mut flags: u32 = 0;
if family_id != 0 {
flags |= 0x2000
}
// header
outp.write_u32::<LittleEndian>(UF2_MAGIC_START0)?;
outp.write_u32::<LittleEndian>(UF2_MAGIC_START1)?;
outp.write_u32::<LittleEndian>(flags)?;
outp.write_u32::<LittleEndian>(ptr + app_start_addr)?;
outp.write_u32::<LittleEndian>(256)?;
outp.write_u32::<LittleEndian>(blockno)?;
outp.write_u32::<LittleEndian>(nblocks)?;
outp.write_u32::<LittleEndian>(family_id)?;
// data
outp.write(&chunk)?;
outp.write(&datapadding)?;
// footer
outp.write_u32::<LittleEndian>(UF2_MAGIC_END)?;
}
Ok(outp)
}

Binary file not shown.

44
signing/test-verify.py Normal file
View file

@ -0,0 +1,44 @@
#!/usr/bin/env python3
import base64
import hashlib
import argparse
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.exceptions import InvalidSignature
def verify_signature(file_path: Path, pubkey_b64: str, sig_b64: str, authdata_b64: str):
pubkey = base64.b64decode(pubkey_b64)
signature = base64.b64decode(sig_b64)
authdata = base64.b64decode(authdata_b64)
client_data = file_path.read_bytes()
client_data_hash = hashlib.sha256(client_data).digest()
message = authdata + client_data_hash
public_key = ed25519.Ed25519PublicKey.from_public_bytes(pubkey)
try:
public_key.verify(signature, message)
print("Signature is valid.")
except InvalidSignature:
print("Signature is INVALID.")
def main():
parser = argparse.ArgumentParser(
description="Verify FIDO2 Ed25519-SK signature for a given clientDataJSON file."
)
parser.add_argument("file", type=Path, help="Path to clientDataJSON file")
parser.add_argument("pubkey_b64", help="Base64-encoded 32-byte Ed25519 public key")
parser.add_argument("sig_b64", help="Base64-encoded 64-byte signature")
parser.add_argument("authdata_b64", help="Base64-encoded 37-byte authenticator data")
args = parser.parse_args()
verify_signature(args.file, args.pubkey_b64, args.sig_b64, args.authdata_b64)
if __name__ == "__main__":
main()
# test data is 64 bytes of 0, signed with beta-key
#
# pubkey gJeZKe3QTkASS1LK6a5Uskvf9yp7igBMQQZb0UAgeKc=
# authdata 4wYQ6KFiEVlg/h7CI+ZSnJ9LboAgDcteXDIcivHisb8FAAACDw==
# signature uYiL6JV0h4LcZ95F3i4o09Lf29zI7PAM11LGfIolkOiJooeOUDm2tOIk2u/OuaiZgN62UZ4a6coNSwZkV9UxCg==

View file

@ -2,7 +2,7 @@ use std::io::{Read, Write};
use std::path::Path;
use bao1x_api::signatures::{
FunctionCode, PADDING_LEN, PUBLIC_KEY_LENGTH, SIGBLOCK_LEN, SealedFields, UNSIGNED_LEN,
FunctionCode, PADDING_LEN, SIGBLOCK_LEN, SealedFields, SignatureInFlash, UNSIGNED_LEN,
};
use ed25519_dalek::{DigestSigner, SigningKey};
use pkcs8::PrivateKeyInfo;
@ -196,9 +196,13 @@ pub fn sign_image(
// Now we can use the private key data.
let signing_key = SigningKey::from_bytes(&secbytes);
// derive a private key
let sk = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents)
.map_err(|e| format!("{}", e))?;
// This is handy code to remember - a quick way to get the public key from the private key. Just
// in case I need this in the future to sanity check some values.
/*
let sk = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents)
.map_err(|e| format!("{}", e))?;
let pubkey = sk.public_key();
*/
let function_code = match function_code {
Some("boot0") => FunctionCode::Boot0,
@ -209,24 +213,23 @@ pub fn sign_image(
Some("swap") => FunctionCode::Swap,
_ => FunctionCode::Developer,
};
let mut sealed_fields = SealedFields {
version: version as u32,
signed_len: (source.len() + SIGBLOCK_LEN - UNSIGNED_LEN) as u32,
function_code: function_code as u32,
reserved: 0,
min_semver: minver_bytes,
semver,
pubkeys: [
[0u8; PUBLIC_KEY_LENGTH],
[0u8; PUBLIC_KEY_LENGTH],
[0u8; PUBLIC_KEY_LENGTH],
[0u8; PUBLIC_KEY_LENGTH],
],
};
sealed_fields.pubkeys[3].copy_from_slice(sk.public_key().as_ref());
let mut header = SignatureInFlash::default();
header.sealed_data.version = version as u32;
header.sealed_data.signed_len = (source.len() + SIGBLOCK_LEN - UNSIGNED_LEN) as u32;
header.sealed_data.function_code = function_code as u32;
header.sealed_data.reserved = 0;
header.sealed_data.min_semver = minver_bytes;
header.sealed_data.semver = semver;
// whack in all the public keys, defined in the bao1x-api crate
for (dst, src) in
header.sealed_data.pubkeys.iter_mut().zip(bao1x_api::pubkeys::PUBKEY_HEADER.iter())
{
dst.populate_from(src);
}
let mut protected = Vec::new();
protected.extend_from_slice(sealed_fields.as_ref());
protected.extend_from_slice(header.sealed_data.as_ref());
protected.resize(protected.len() + PADDING_LEN, 0);
protected.extend_from_slice(&source);
@ -235,12 +238,14 @@ pub fn sign_image(
h.update(&protected);
let sig = signing_key.sign_digest(h.clone()).to_bytes();
header._jal_instruction = generate_jal_x0(SIGBLOCK_LEN as isize)?;
header.signature.copy_from_slice(&sig);
// no AAD on this type of signature
header.aad_len = 0;
let jal = generate_jal_x0(length as isize)?;
dest_file.write_all(&jal.to_le_bytes())?;
// Write the signature data
dest_file.write_all(&sig)?;
// Write the header
dest_file.write_all(&header.as_ref()[..UNSIGNED_LEN])?;
println!("dest_file wrote {}, {}", dest_file.len(), UNSIGNED_LEN);
if defile {
println!(
@ -305,6 +310,12 @@ where
let mut dest_file = std::fs::File::create(output)?;
source_file.read_to_end(&mut source)?;
// maintenance note: there is a mirror of this code in signing/fido-signer/src/main.rs
// if you're editing this, maybe consider also trying to librarify these routines?
// the key challenge is that fido-signer has to be out of workspace because it relies
// on cryptographic primitives that are pinned to versions that are not compatible
// with the baochip hardware, e.g. the FIDO2 libraries pin to an incompatible version
// with xous-core, so it's a little awkward spanning/sharing crates this way.
let app_start_addr = match function_code {
Some("boot0") => bao1x_api::BOOT0_START,
Some("boot1") => bao1x_api::BOOT1_START,

View file

@ -10,16 +10,9 @@ use chrono::Local;
pub(crate) fn generate_version(add_timestamp: bool) {
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", "git describe --tags --long"])
.output()
.expect("failed to execute process")
Command::new("cmd").args(["/C", "git describe --long"]).output().expect("failed to execute process")
} else {
Command::new("sh")
.arg("-c")
.arg("git describe --tags --long")
.output()
.expect("failed to execute process")
Command::new("sh").arg("-c").arg("git describe --long").output().expect("failed to execute process")
};
let gitver = output.stdout;
let semver = String::from_utf8_lossy(&gitver);