upgrade signature check to handle domain separation data

this is needed to handle the fido2/webauthn style signatures
This commit is contained in:
bunnie 2025-10-06 03:49:11 +08:00
parent fc3b226414
commit 69d81042b9
3 changed files with 127 additions and 45 deletions

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

@ -1,11 +1,27 @@
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
/// 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 = size_of::<u32>() + SIGNATURE_LENGTH;
// 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.
/// 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 "];
/// These are notional and subject to change
#[repr(u32)]
#[derive(PartialEq, Eq, Clone, Copy)]
@ -74,6 +90,27 @@ impl Default for SignatureInFlash {
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Pubkey {
pub pk: [u8; PUBLIC_KEY_LENGTH],
pub tag: u32,
/// `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, and can be much
/// larger if optional extentions are enabled. 59 bytes are made available since this
/// pads nicely into the record format, and gives us some wiggle room for compatibility
pub aad_len: u8,
pub aad: [u8; 59],
}
unsafe impl Zeroable for Pubkey {}
unsafe impl Pod for Pubkey {}
impl Default for Pubkey {
fn default() -> Self { Self { pk: [0u8; PUBLIC_KEY_LENGTH], tag: 0, aad_len: 0, aad: [0u8; 59] } }
}
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub struct SealedFields {
@ -106,7 +143,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 {
@ -121,7 +158,7 @@ impl Default for SealedFields {
reserved: 0,
min_semver: [0u8; 16],
semver: [0u8; 16],
pubkeys: [[0u8; PUBLIC_KEY_LENGTH]; 4],
pubkeys: [Pubkey::default(); 4],
}
}
}

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, u32), String> {
// Copy the signature into a structure so we can unpack it.
let mut sig = SignatureInFlash::default();
if let Some(ref mut spim) = spim {
@ -81,7 +82,7 @@ pub fn validate_image(
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 == 0 {
continue;
}
let revocation_value = one_way_counters.get(revocation_offset + i).expect("internal error");
@ -90,47 +91,91 @@ 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.
// ASSUME: the SPIM driver has allocated a read buffer that is actually PAGE_SIZE. If the SPIM
// driver has a smaller buffer, reads get less efficient.
let end = img_offset as usize + UNSIGNED_LEN + signed_len as usize;
for offset in ((img_offset as usize + UNSIGNED_LEN)..end).step_by(PAGE_SIZE) {
let mut buf = [0u8; PAGE_SIZE];
spim.mem_read(offset as u32, &mut buf, false);
let valid_length = if offset + PAGE_SIZE < end { PAGE_SIZE } else { end - offset };
h.update(&buf[..valid_length]);
if key.aad_len == 0 {
let mut h: Sha512 = Sha512::new();
// this code has to be implemented *twice* because we can't make `h` a generic trait due
// to the type bounds reasonably imposed by `verify_prehashed`.
if let Some(ref mut spim) = spim {
// need to read the data out page by page and hash it.
// ASSUME: the SPIM driver has allocated a read buffer that is actually PAGE_SIZE. If the SPIM
// driver has a smaller buffer, reads get less efficient.
let end = img_offset as usize + UNSIGNED_LEN + signed_len as usize;
for offset in ((img_offset as usize + UNSIGNED_LEN)..end).step_by(PAGE_SIZE) {
let mut buf = [0u8; PAGE_SIZE];
spim.mem_read(offset as u32, &mut buf, false);
let valid_length = if offset + PAGE_SIZE < end { PAGE_SIZE } else { end - offset };
h.update(&buf[..valid_length]);
}
} else {
// easy peasy
let image: &[u8] = unsafe {
core::slice::from_raw_parts(
(img_offset as usize + UNSIGNED_LEN) as *const u8,
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;
}
}
_ => {}
}
} else {
// easy peasy
let image: &[u8] = unsafe {
core::slice::from_raw_parts(
(img_offset as usize + UNSIGNED_LEN) as *const u8,
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;
let mut h: Sha256 = Sha256::new();
// this code has to be implemented *twice* because we can't make `h` a generic trait due
// to the type bounds reasonably imposed by `verify_prehashed`.
if let Some(ref mut spim) = spim {
let end = img_offset as usize + UNSIGNED_LEN + signed_len as usize;
for offset in ((img_offset as usize + UNSIGNED_LEN)..end).step_by(PAGE_SIZE) {
let mut buf = [0u8; PAGE_SIZE];
spim.mem_read(offset as u32, &mut buf, false);
let valid_length = if offset + PAGE_SIZE < end { PAGE_SIZE } else { end - offset };
h.update(&buf[..valid_length]);
}
} else {
let image: &[u8] = unsafe {
core::slice::from_raw_parts(
(img_offset as usize + UNSIGNED_LEN) as *const u8,
signed_len as usize,
)
};
h.update(&image);
}
let mut msg: Vec<u8> = Vec::new();
msg.extend_from_slice(&key.aad[..key.aad_len as usize]);
msg.extend_from_slice(h.finalize().as_slice());
match verifying_key.verify_strict(&msg, &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;
}
}
_ => {}
}
_ => {}
}
}
@ -141,7 +186,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"))
}