add signature patching to fido-signer

fido-signer now automatically recognizes xous images and
patches the signature with the updated signature record,
as well as re-generating the corresponding .uf2 file.
This commit is contained in:
bunnie 2025-10-06 23:31:41 +08:00
parent 3b4e035a4f
commit e254700cf9
No known key found for this signature in database
4 changed files with 336 additions and 14 deletions

View file

@ -69,6 +69,12 @@ version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
[[package]]
name = "arbitrary-int"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "825297538d77367557b912770ca3083f778a196054b3ee63b22673c4a3cae0a5"
[[package]]
name = "asn1-rs"
version = "0.7.1"
@ -112,12 +118,16 @@ dependencies = [
name = "auth-sign-test"
version = "0.1.0"
dependencies = [
"bao1x-api",
"base64",
"byteorder",
"clap",
"ctap-hid-fido2",
"digest",
"hex",
"serde",
"serde_json",
"sha2",
"windows",
]
@ -127,12 +137,44 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "bao1x-api"
version = "0.1.0"
dependencies = [
"bitbybit",
"bytemuck",
"num-derive",
"num-traits",
"xous",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitbybit"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec187a89ab07e209270175faf9e07ceb2755d984954e58a2296e325ddece2762"
dependencies = [
"arbitrary-int",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "block-padding"
version = "0.3.3"
@ -142,6 +184,26 @@ dependencies = [
"generic-array",
]
[[package]]
name = "bytemuck"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "byteorder"
version = "1.5.0"
@ -333,6 +395,16 @@ dependencies = [
"powerfmt",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "displaydoc"
version = "0.2.5"
@ -513,6 +585,17 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "num-integer"
version = "0.1.46"
@ -723,6 +806,17 @@ dependencies = [
"serde_core",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "1.3.0"
@ -1137,6 +1231,15 @@ dependencies = [
"time",
]
[[package]]
name = "xous"
version = "0.9.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb2954670da82bb4be335f2f576d48d33475145d9d0c83c725f395cf3284a12"
dependencies = [
"lazy_static",
]
[[package]]
name = "zerocopy"
version = "0.8.27"

View file

@ -12,6 +12,10 @@ 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]

View file

@ -1,17 +1,27 @@
use std::fs;
use std::io::{self, Write};
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")]
#[command(author, version, about, long_about = None)]
#[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)
@ -29,6 +39,10 @@ struct Args {
/// 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)]
@ -60,14 +74,40 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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
// 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(file_path) = args.file {
// Read file contents
fs::read(&file_path).map_err(|e| format!("Failed to read file '{}': {}", file_path.display(), 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());
@ -79,21 +119,40 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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!("\n* Signing successful!");
println!("Signature length: {} bytes", assertion.signature.len());
if assertion.signature.len() == 64 {
println!("✓ Valid Ed25519 signature");
println!("* Valid Ed25519 signature");
// Ed25519 signature components
let (r, s) = assertion.signature.split_at(32);
println!(" R: {}", hex::encode(r));
println!(" S: {}", hex::encode(s));
println!(" auth_data: {}", hex::encode(&assertion.auth_data));
println!(" R (hex): {}", hex::encode(r));
println!(" S (hex): {}", hex::encode(s));
println!(" auth_data (hex): {}", hex::encode(&assertion.auth_data));
println!(" signature: {}", general_purpose::STANDARD.encode(assertion.signature));
println!(" auth_data: {}", general_purpose::STANDARD.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(())
@ -126,3 +185,159 @@ fn sign_ed25519_hash(
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.