implement keystore calls needed for pddb compatibility

This commit is contained in:
bunnie 2025-11-08 03:52:20 +08:00
parent 99769d4622
commit 792de177b0
4 changed files with 120 additions and 172 deletions

View file

@ -2,7 +2,7 @@
name = "keystore"
version = "0.1.0"
authors = ["bunnie <bunnie@kosagi.com>"]
edition = "2018"
edition = "2021"
description = "Keystore server for compact devices"
# Dependency versions enforced by Cargo.lock.

View file

@ -4,7 +4,7 @@ pub use cipher::{
};
use keystore_api::*;
use num_traits::*;
use xous::{CID, Message, send_message};
use xous::CID;
use xous_ipc::Buffer;
pub(crate) type BatchBlocks = GenericArray<Block, U16>;
use std::convert::TryInto;
@ -28,29 +28,10 @@ impl Keystore {
Self { conn, domain: Some(key_type.to_owned()) }
}
pub fn clear_password(&self) {
match send_message(
self.conn,
Message::new_blocking_scalar(Opcode::ClearPasswordCacheEntry.to_usize().unwrap(), 0, 0, 0, 0),
) {
// it's a blocking scalar just to ensure that the password *has* cleared
// any error in this routine should rightfully be a panic.
Ok(xous::Result::Scalar5(_, _, _, _, _)) => (),
_ => panic!("clear_password() failed with internal error"),
}
}
pub fn get_dna(&self) -> u64 {
let response = send_message(
self.conn,
Message::new_blocking_scalar(Opcode::GetDna.to_usize().unwrap(), 0, 0, 0, 0),
)
.unwrap();
if let xous::Result::Scalar5(_, val1, val2, _, _) = response {
(val1 as u64) | ((val2 as u64) << 32)
} else {
panic!("get_dna() failed with internal error");
}
let (_, value) =
std::env::vars().find(|(key, _value)| key == "UUID").expect("Fatal: No UUID in env!");
u64::from_ne_bytes(hex::decode(value).expect("Couldn't decode UUID")[..8].try_into().unwrap())
}
/// This routine confirms that the keystore has all the user secrets necessary to decrypt
@ -60,24 +41,10 @@ impl Keystore {
/// which is a shallow layer of security on top of the key store. The exact behavior of what
/// this call entails is up to the keystore implementation.
///
/// On Baosec, it's envisioned that there is a user setting which specifies three possible behaviors:
/// - None -- the master key is ready to use without any further derivation
/// - PIN -- Requires a 4-6 digit code to unlock the device; retry limits, time-outs and self-wipes may
/// also be configured
/// - QR -- Requires a high-strength 256-bit password from a scanned QR code as a strong additional
/// layer of security in case the device is lost or stolen.
pub fn ensure_password(&self) -> PasswordState {
match send_message(
self.conn,
Message::new_blocking_scalar(Opcode::EnsurePassword.to_usize().unwrap(), 0, 0, 0, 0),
) {
Ok(xous::Result::Scalar5(_arg0, arg1, arg2, arg3, _arg4)) => {
log::info!("got {:x}, {:x}, {:x}", arg1, arg2, arg3);
(arg1, arg2, arg3).into()
}
_ => panic!("ensure_password() failed with internal error"),
}
}
/// On Baosec, the root password is available on boot. There is only one supplemental
/// password possible, and this is the one which unlocks an additional secret basis into
/// which secrets are stored.
pub fn ensure_password(&self) -> PasswordState { PasswordState::Correct }
pub fn wrap_key(&self, input: &[u8]) -> Result<Vec<u8>, KeywrapError> {
if input.len() > MAX_WRAP_DATA {

View file

@ -1,23 +1,14 @@
use std::convert::TryInto;
use aes::Aes256;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use bao1x_hal::rram::Reram;
use hkdf::Hkdf;
use keystore_api::*;
use sha2::Sha256;
use xous::SID;
use xous_ipc::Buffer;
use crate::platform::KeyStore;
/// Any old key for the hosted mode testing. 0 is as good a number as any other.
const WELL_KNOWN_KEY: &'static str = "0000000000000000000000000000000000000000000000000000000000000000";
pub fn keystore(sid: SID) -> ! {
let hal = bao1x_hal_service::Hal::new();
let mut rram = Reram::new();
let storage = KeyStore::init_from_hw(&mut rram);
let mut store = KeyStore::init_from_hw(&mut rram);
let mut msg_opt = None;
@ -34,134 +25,16 @@ pub fn keystore(sid: SID) -> ! {
unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
// as_flat saves a copy step, but we have to deserialize some enums manually
let mut aes_op = buffer.to_original::<AesOp, _>().unwrap();
let op = match aes_op.aes_op {
// seems stupid, but we have to do this because we want to have zeroize on the AesOp
// record, and it means we can't have Copy on this.
AesOpType::Decrypt => AesOpType::Decrypt,
AesOpType::Encrypt => AesOpType::Encrypt,
};
let mut ikm = [0u8; 32];
ikm.copy_from_slice(&hex::decode(WELL_KNOWN_KEY).unwrap());
let hk = Hkdf::<Sha256>::new(None, &ikm);
let mut okm = [0u8; 32];
hk.expand(&aes_op.domain.as_bytes(), &mut okm)
.expect("32 is a valid length for Sha256 to output");
let cipher = Aes256::new(GenericArray::from_slice(&okm));
// deserialize the specifier
match aes_op.block {
AesBlockType::SingleBlock(b) => {
match op {
AesOpType::Decrypt => cipher.decrypt_block(&mut b.try_into().unwrap()),
AesOpType::Encrypt => cipher.encrypt_block(&mut b.try_into().unwrap()),
}
aes_op.block = AesBlockType::SingleBlock(b);
}
AesBlockType::ParBlock(mut pb) => {
match op {
AesOpType::Decrypt => {
for block in pb.iter_mut() {
cipher.decrypt_block(block.try_into().unwrap());
}
}
AesOpType::Encrypt => {
for block in pb.iter_mut() {
cipher.encrypt_block(block.try_into().unwrap());
}
}
}
aes_op.block = AesBlockType::ParBlock(pb);
}
};
store.aes_op(&mut aes_op).expect("couldn't perform AES op");
buffer.replace(aes_op).unwrap();
}
Opcode::AesKwp => {
let mut ikm = [0u8; 32];
ikm.copy_from_slice(&hex::decode(WELL_KNOWN_KEY).unwrap());
let mut buffer =
unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut kwp = buffer.to_original::<KeyWrapper, _>().unwrap();
use aes_kw::Kek;
use aes_kw::KekAes256;
let keywrapper: KekAes256 = Kek::from(ikm);
match kwp.op {
KeyWrapOp::Wrap => {
match keywrapper.wrap_with_padding_vec(&kwp.data[..kwp.len as usize]) {
Ok(wrapped) => {
for (&src, dst) in wrapped.iter().zip(kwp.data.iter_mut()) {
*dst = src;
}
kwp.len = wrapped.len() as u32;
kwp.result = None;
// this is an un-used field but...why not?
kwp.expected_len = wrapped.len() as u32;
}
Err(e) => {
kwp.result = Some(match e {
aes_kw::Error::IntegrityCheckFailed => KeywrapError::IntegrityCheckFailed,
aes_kw::Error::InvalidDataSize => KeywrapError::InvalidDataSize,
aes_kw::Error::InvalidKekSize { size } => {
log::info!("invalid size {}", size); // weird. can't name this _size
KeywrapError::InvalidKekSize
}
aes_kw::Error::InvalidOutputSize { expected } => {
log::info!("invalid output size {}", expected);
KeywrapError::InvalidOutputSize
}
});
}
}
}
KeyWrapOp::Unwrap => {
match keywrapper.unwrap_with_padding_vec(&kwp.data[..kwp.len as usize]) {
Ok(wrapped) => {
for (&src, dst) in wrapped.iter().zip(kwp.data.iter_mut()) {
*dst = src;
}
kwp.len = wrapped.len() as u32;
kwp.result = None;
// this is an un-used field but...why not?
kwp.expected_len = wrapped.len() as u32;
}
Err(e) => {
kwp.result = Some(match e {
aes_kw::Error::IntegrityCheckFailed => KeywrapError::IntegrityCheckFailed,
aes_kw::Error::InvalidDataSize => KeywrapError::InvalidDataSize,
aes_kw::Error::InvalidKekSize { size } => {
log::info!("invalid size {}", size); // weird. can't name this _size
KeywrapError::InvalidKekSize
}
aes_kw::Error::InvalidOutputSize { expected } => {
log::info!("invalid output size {}", expected);
KeywrapError::InvalidOutputSize
}
});
}
}
}
}
store.aes_kwp(&mut kwp).expect("couldn't wrap key");
buffer.replace(kwp).unwrap();
}
Opcode::ClearPasswordCacheEntry => {
if let Some(scalar) = msg.body.scalar_message_mut() {
// no passwords, nothing to clear: always return success
scalar.arg1 = 1;
}
}
Opcode::EnsurePassword => {
if let Some(scalar) = msg.body.scalar_message_mut() {
let pws: PasswordState = PasswordState::Correct;
(scalar.arg1, scalar.arg2, scalar.arg3) = pws.into();
log::info!("Password is always ensured in hosted mode");
}
}
Opcode::GetDna => {
// dummy DNA value
if let Some(scalar) = msg.body.scalar_message_mut() {
scalar.arg1 = 0;
scalar.arg2 = 0;
}
}
Opcode::InvalidCall => {
log::error!("Invalid call in keystore: {:?}", opcode);
}

View file

@ -1,3 +1,5 @@
use aes::Aes256;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use bao1x_api::{BOOT0_PUBKEY_FAIL, CP_ID, DEVELOPER_MODE, OEM_MODE, UUID};
use bao1x_hal::{
acram::{OneWayCounter, SlotManager},
@ -5,9 +7,12 @@ use bao1x_hal::{
rram::Reram,
};
use hkdf::Hkdf;
use keystore_api::KeyWrapper;
use rand::prelude::*;
use sha2::Sha256;
use crate::*;
const KEY_LEN: usize = bao1x_api::SLOT_ELEMENT_LEN_BYTES;
pub struct KeyStore {
@ -150,4 +155,107 @@ impl KeyStore {
Self { slot_mgr, owc, master_key }
}
pub fn aes_kwp(&self, kwp: &mut KeyWrapper) -> Result<(), xous::Error> {
use aes_kw::Kek;
use aes_kw::KekAes256;
let keywrapper: KekAes256 = Kek::from(self.master_key);
match kwp.op {
KeyWrapOp::Wrap => {
match keywrapper.wrap_with_padding_vec(&kwp.data[..kwp.len as usize]) {
Ok(wrapped) => {
for (&src, dst) in wrapped.iter().zip(kwp.data.iter_mut()) {
*dst = src;
}
kwp.len = wrapped.len() as u32;
kwp.result = None;
// this is an un-used field but...why not?
kwp.expected_len = wrapped.len() as u32;
}
Err(e) => {
kwp.result = Some(match e {
aes_kw::Error::IntegrityCheckFailed => KeywrapError::IntegrityCheckFailed,
aes_kw::Error::InvalidDataSize => KeywrapError::InvalidDataSize,
aes_kw::Error::InvalidKekSize { size } => {
log::info!("invalid size {}", size); // weird. can't name this _size
KeywrapError::InvalidKekSize
}
aes_kw::Error::InvalidOutputSize { expected } => {
log::info!("invalid output size {}", expected);
KeywrapError::InvalidOutputSize
}
});
}
}
}
KeyWrapOp::Unwrap => {
match keywrapper.unwrap_with_padding_vec(&kwp.data[..kwp.len as usize]) {
Ok(wrapped) => {
for (&src, dst) in wrapped.iter().zip(kwp.data.iter_mut()) {
*dst = src;
}
kwp.len = wrapped.len() as u32;
kwp.result = None;
// this is an un-used field but...why not?
kwp.expected_len = wrapped.len() as u32;
}
Err(e) => {
kwp.result = Some(match e {
aes_kw::Error::IntegrityCheckFailed => KeywrapError::IntegrityCheckFailed,
aes_kw::Error::InvalidDataSize => KeywrapError::InvalidDataSize,
aes_kw::Error::InvalidKekSize { size } => {
log::info!("invalid size {}", size); // weird. can't name this _size
KeywrapError::InvalidKekSize
}
aes_kw::Error::InvalidOutputSize { expected } => {
log::info!("invalid output size {}", expected);
KeywrapError::InvalidOutputSize
}
});
}
}
}
}
Ok(())
}
pub fn aes_op(&mut self, aes_op: &mut AesOp) -> Result<(), xous::Error> {
let op = match aes_op.aes_op {
// seems stupid, but we have to do this because we want to have zeroize on the AesOp
// record, and it means we can't have Copy on this.
AesOpType::Decrypt => AesOpType::Decrypt,
AesOpType::Encrypt => AesOpType::Encrypt,
};
let hk = Hkdf::<Sha256>::new(None, &self.master_key);
let mut okm = [0u8; 32];
hk.expand(&aes_op.domain.as_bytes(), &mut okm).expect("32 is a valid length for Sha256 to output");
let cipher = Aes256::new(GenericArray::from_slice(&okm));
// deserialize the specifier
match aes_op.block {
AesBlockType::SingleBlock(b) => {
match op {
AesOpType::Decrypt => cipher.decrypt_block(&mut b.try_into().unwrap()),
AesOpType::Encrypt => cipher.encrypt_block(&mut b.try_into().unwrap()),
}
aes_op.block = AesBlockType::SingleBlock(b);
}
AesBlockType::ParBlock(mut pb) => {
match op {
AesOpType::Decrypt => {
for block in pb.iter_mut() {
cipher.decrypt_block(block.try_into().unwrap());
}
}
AesOpType::Encrypt => {
for block in pb.iter_mut() {
cipher.encrypt_block(block.try_into().unwrap());
}
}
}
aes_op.block = AesBlockType::ParBlock(pb);
}
};
Ok(())
}
}