use NIST SP800-38F (AES-KWP) to wrap the system key for the PDDB

this is instead of our lolfail ECB-based method with a check block.
This commit is contained in:
bunnie 2022-02-03 18:24:06 +08:00
parent b7c0387186
commit b498669003
11 changed files with 540 additions and 115 deletions

5
Cargo.lock generated
View file

@ -274,9 +274,9 @@ checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631"
[[package]]
name = "byteorder"
version = "1.4.2"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae44d1a3d5a19df61dd0c8beb138458ac2a53a7ac09eba97d55592540004306b"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "bzip2"
@ -1880,6 +1880,7 @@ version = "0.1.0"
dependencies = [
"aes",
"blowfish",
"byteorder",
"cipher",
"com",
"curve25519-dalek",

View file

@ -1,3 +1,5 @@
#![allow(dead_code)] // because hosted mode doesn't use mappings
#![allow(unused_imports)]
mod qwerty;
pub (crate) use qwerty::*;
mod qwertz;

View file

@ -33,14 +33,25 @@ pub const PAGE_SIZE: usize = spinor::SPINOR_ERASE_SIZE as usize;
/// size of a virtual page -- after the AES encryption and journaling overhead is subtracted
pub const VPAGE_SIZE: usize = PAGE_SIZE - size_of::<Nonce>() - size_of::<Tag>() - size_of::<JournalType>();
const WRAPPED_AES_KEYSIZE: usize = AES_KEYSIZE + 8;
const SCD_VERSION: u32 = 1;
#[repr(C)] // this can map directly into Flash
pub(crate) struct StaticCryptoData {
/// aes-256 key of the system basis, encrypted with the User0 root key
pub(crate) system_key: [u8; AES_KEYSIZE],
/// check data to confirm the password was entered correctly; it is the encryption of the first 128 bits of the salt below.
pub(crate) check_data: [u8; BLOCK_SIZE],
/// a pool of fixed data used to pick salts, based on a hash of the basis name
pub(crate) salt_base: [u8; 4048],
/// a version number for the block
pub(crate) version: u32,
/// aes-256 key of the system basis, encrypted with the User0 root key, and wrapped using NIST SP800-38F
pub(crate) system_key: [u8; WRAPPED_AES_KEYSIZE],
/// a pool of fixed data used as a salt
pub(crate) salt_base: [u8; 4096 - WRAPPED_AES_KEYSIZE - size_of::<u32>()],
}
impl StaticCryptoData {
pub fn default() -> StaticCryptoData {
StaticCryptoData {
version: SCD_VERSION,
system_key: [0u8; WRAPPED_AES_KEYSIZE],
salt_base: [0u8; 4096 - WRAPPED_AES_KEYSIZE - size_of::<u32>()],
}
}
}
impl Deref for StaticCryptoData {
type Target = [u8];
@ -79,6 +90,7 @@ pub(crate) struct PddbOs {
/// free space circular buffer base -- location in FLASH, offset from physical bottom of pddb_mr
fscb_phys_base: PageAlignedPa,
data_phys_base: PageAlignedPa,
/// We keep a copy of the raw key around because we have to combine this with the AAD of a block to derive the AES-GCM-SIV cipher.
system_basis_key: Option<[u8; AES_KEYSIZE]>,
/// derived cipher for handling fastspace -- cache it, so we can save the time cost of constructing the cipher key schedule
cipher_ecb: Option<Aes256>,
@ -452,69 +464,43 @@ impl PddbOs {
pub(crate) fn clear_password(&self) {
self.rootkeys.clear_password(AesRootkeyType::User0);
}
pub (crate) fn try_login(&mut self) -> bool {
pub (crate) fn try_login(&mut self) -> PasswordState {
if self.system_basis_key.is_none() || self.cipher_ecb.is_none() {
let scd = self.static_crypto_data_get();
let mut system_key: [u8; AES_KEYSIZE] = [0; AES_KEYSIZE];
let mut blank = true;
for (&src, dst) in scd.system_key.iter().zip(system_key.iter_mut()) {
*dst = src;
if src != 0xFF {
blank = false;
}
if scd.version == 0xFFFF_FFFF { // system is in the blank state
return PasswordState::Uninit
}
for block in system_key.chunks_mut(aes::BLOCK_SIZE) {
self.rootkeys.decrypt_block(block.try_into().unwrap());
if scd.version != SCD_VERSION {
log::error!("Version mismatch for keystore, declaring database as uninitialized");
return PasswordState::Uninit;
}
if !blank {
// form the ECB cipher and check the check data
let cipher = Aes256::new(GenericArray::from_slice(&system_key));
let mut block = [0u8; BLOCK_SIZE];
for (&src, dst) in scd.check_data[0..BLOCK_SIZE].iter().zip(block.iter_mut()) {
*dst = src;
}
let ga = GenericArray::from_mut_slice(&mut block);
//log::info!("test block before: {:x?}", ga);
cipher.decrypt_block(ga);
//log::info!("test block after check: {:x?}", ga);
let mut success = true;
let mut checkedlen = 0;
for (&a, &b) in scd.salt_base[0..BLOCK_SIZE].iter().zip(ga.iter()) {
if a != b {
success = false;
}
checkedlen += 1;
}
if checkedlen != BLOCK_SIZE {
success = false;
}
if success {
match self.rootkeys.unwrap_key(&scd.system_key, AES_KEYSIZE) {
Ok(mut syskey) => {
let cipher = Aes256::new(GenericArray::from_slice(&syskey));
self.cipher_ecb = Some(cipher);
let mut system_key: [u8; AES_KEYSIZE] = [0; AES_KEYSIZE];
for (&src, dst) in scd.system_key.iter().zip(system_key.iter_mut()) {
for (&src, dst) in syskey.iter().zip(system_key.iter_mut()) {
*dst = src;
}
for block in system_key.chunks_mut(aes::BLOCK_SIZE) {
self.rootkeys.decrypt_block(block.try_into().unwrap());
}
self.system_basis_key = Some(system_key);
self.cipher_ecb = Some(cipher);
// erase the old vector completely
let nuke = syskey.as_mut_ptr();
for i in 0..syskey.len() {
unsafe{nuke.add(i).write_volatile(0)};
}
PasswordState::Correct
}
Err(e) => {
log::error!("Couldn't unwrap our system key: {:?}", e);
PasswordState::Incorrect
}
success
} else {
// the system is in a blank state -- use the bogus key so that the later test for
// mounting the PDDB doesn't fail on account of a lack of key matter. We'll deal
// with setting the key correctly later.
self.system_basis_key = Some(system_key);
let cipher = Aes256::new(GenericArray::from_slice(&system_key));
self.cipher_ecb = Some(cipher);
true
}
} else {
true
PasswordState::Correct
}
}
fn syskey_ensure(&mut self) {
while !self.try_login() {
while self.try_login() != PasswordState::Correct {
self.clear_password(); // clear the bad password entry
let xns = xous_names::XousNames::new().unwrap();
let modals = modals::Modals::new(&xns).expect("can't connect to Modals server");
@ -1202,6 +1188,10 @@ impl PddbOs {
if let Some(modals) = progress {
let mut success = false;
while !success {
// the "same password check" is accomplished by just encrypting the all-zeros block twice
// with the cipher after clearing the password and re-entering it, and then comparing that
// the results are identical. The test blocks are never committed or stored anywhere.
// The actual creation of the "real" key material is done in step 3.
let mut checkblock_a = [0u8; BLOCK_SIZE];
self.rootkeys.decrypt_block(GenericArray::from_mut_slice(&mut checkblock_a));
@ -1301,40 +1291,27 @@ impl PddbOs {
assert!(size_of::<StaticCryptoData>() == PAGE_SIZE, "StaticCryptoData structure is not correctly sized");
let mut system_basis_key: [u8; AES_KEYSIZE] = [0; AES_KEYSIZE];
self.entropy.borrow_mut().get_slice(&mut system_basis_key);
let mut basis_key_aes: [u8; AES_KEYSIZE] = system_basis_key.clone();
self.cipher_ecb = Some(Aes256::new(GenericArray::from_slice(&basis_key_aes))); // build the ECB cipher for page table entries
let cipher = Aes256::new(GenericArray::from_slice(&basis_key_aes));
self.system_basis_key = Some(system_basis_key); // causes system_basis_key to be owned by self
for block in basis_key_aes.chunks_mut(aes::BLOCK_SIZE) {
self.rootkeys.encrypt_block(block.try_into().unwrap());
}
let mut crypto_keys = StaticCryptoData {
system_key: [0; AES_KEYSIZE],
check_data: [0; BLOCK_SIZE],
salt_base: [0; 4048],
};
// build the ECB cipher for page table entries
self.cipher_ecb = Some(Aes256::new(GenericArray::from_slice(&system_basis_key)));
let cipher_ecb = Aes256::new(GenericArray::from_slice(&system_basis_key)); // a second copy for patching the page table later in this routine interior mutability blah blah work around oops
// now wrap the key for storage
let wrapped_key = self.rootkeys.wrap_key(&system_basis_key).expect("Internal error wrapping our encryption key");
self.system_basis_key = Some(system_basis_key); // this causes system_basis_key to be owned by self and go out of scope
let mut crypto_keys = StaticCryptoData::default();
crypto_keys.version = SCD_VERSION; // should already be set by `default()` but let's be sure.
if let Some(modals) = progress {
modals.update_progress(50).expect("couldn't update progress bar");
self.tt.sleep_ms(100).unwrap();
}
// copy the encrypted key into the data structure for commit to Flash
for (&src, dst) in basis_key_aes.iter().zip(crypto_keys.system_key.iter_mut()) {
// the wrapped key should have a well-defined length of 40 bytes
assert!(wrapped_key.len() == 40, "wrapped key did not have the expected length");
for (&src, dst) in wrapped_key.iter().zip(crypto_keys.system_key.iter_mut()) {
*dst = src;
}
// initialize the salt
self.entropy.borrow_mut().get_slice(&mut crypto_keys.salt_base);
let cipher_ecb = self.cipher_ecb.as_ref().unwrap();
let mut block = [0u8; BLOCK_SIZE];
// the test data is just the first 128 bits of the salt base
for (&src, dst) in crypto_keys.salt_base[0..BLOCK_SIZE].iter().zip(block.iter_mut()) {
*dst = src;
}
let ga = GenericArray::from_mut_slice(&mut block);
log::info!("test block before: {:x?}", ga);
cipher_ecb.encrypt_block(ga);
for (&src, dst) in ga.iter().zip(crypto_keys.check_data.iter_mut()) {
*dst = src;
}
log::info!("test block after: {:x?}", crypto_keys.check_data);
// commit keys
self.patch_keys(crypto_keys.deref(), 0);
if let Some(modals) = progress {
modals.update_progress(100).expect("couldn't update progress bar");
@ -1484,7 +1461,7 @@ impl PddbOs {
// step 9. generate & write initial page table entries
for (&virt, phys) in basis_v2p_map.iter_mut() {
self.pt_patch_mapping(virt, phys.page_number(), &cipher);
self.pt_patch_mapping(virt, phys.page_number(), &cipher_ecb);
// mark the entry as clean, as it has been sync'd to disk
phys.set_clean(true);
}

View file

@ -396,6 +396,12 @@ pub(crate) struct BasisRequestPassword {
db_name: xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>,
plaintext_pw: Option<xous_ipc::String::<{crate::api::PASSWORD_LEN}>>,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum PasswordState {
Correct,
Incorrect,
Uninit,
}
struct TokenRecord {
pub dict: String,
@ -466,8 +472,14 @@ fn xmain() -> ! {
#[cfg(not(any(windows, unix)))] // skip this step if running in hosted mode, for now...
if pddb_os.rootkeys_initialized() {
tt.sleep_ms(1000).unwrap(); // wait 1 second after boot before attempting to mount, to let the boot screen finish redrawing (cometic issue).
if ensure_password(&modals, &mut pddb_os) {
try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache);
match ensure_password(&modals, &mut pddb_os) {
PasswordState::Correct => {
try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache, PasswordState::Correct);
},
PasswordState::Uninit => {
try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache, PasswordState::Uninit);
},
_ => (), // continue without mounting if the user opts out
}
}
// main server loop
@ -502,8 +514,8 @@ fn xmain() -> ! {
// can't mount if we have no root keys
xous::return_scalar(msg.sender, 0).expect("could't return scalar");
} else {
if ensure_password(&modals, &mut pddb_os) {
if try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache) {
if ensure_password(&modals, &mut pddb_os) == PasswordState::Correct {
if try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache, PasswordState::Correct) {
xous::return_scalar(msg.sender, 1).expect("couldn't return scalar");
} else {
xous::return_scalar(msg.sender, 0).expect("couldn't return scalar");
@ -1055,40 +1067,48 @@ fn xmain() -> ! {
xous::terminate_process(0)
}
fn ensure_password(modals: &modals::Modals, pddb_os: &mut PddbOs) -> bool {
fn ensure_password(modals: &modals::Modals, pddb_os: &mut PddbOs) -> PasswordState {
log::info!("Requesting login password");
let mut done = false;
let mut skip = false;
while !done {
done = pddb_os.try_login();
if !done {
pddb_os.clear_password(); // clear the bad password entry
modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list");
modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list");
match modals.get_radiobutton(t!("pddb.badpass", xous::LANG)) {
Ok(response) => {
if response.as_str() == t!("pddb.yes", xous::LANG) {
done = false;
} else if response.as_str() == t!("pddb.no", xous::LANG) {
done = true;
skip = true;
} else {
panic!("Got unexpected return from radiobutton");
loop {
match pddb_os.try_login() {
PasswordState::Correct => {
return PasswordState::Correct
}
PasswordState::Incorrect => {
pddb_os.clear_password(); // clear the bad password entry
// check if the user wants to re-try or not.
modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list");
modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list");
match modals.get_radiobutton(t!("pddb.badpass", xous::LANG)) {
Ok(response) => {
if response.as_str() == t!("pddb.yes", xous::LANG) {
continue;
} else if response.as_str() == t!("pddb.no", xous::LANG) {
return PasswordState::Incorrect;
} else {
panic!("Got unexpected return from radiobutton");
}
}
_ => panic!("get_radiobutton failed"),
}
_ => panic!("get_radiobutton failed"),
}
PasswordState::Uninit => {
return PasswordState::Uninit;
}
}
}
!skip
}
fn try_mount_or_format(modals: &modals::Modals, pddb_os: &mut PddbOs, basis_cache: &mut BasisCache) -> bool {
fn try_mount_or_format(modals: &modals::Modals, pddb_os: &mut PddbOs, basis_cache: &mut BasisCache, pw_state: PasswordState) -> bool {
log::info!("Attempting to mount the PDDB");
if let Some(sys_basis) = pddb_os.pddb_mount() {
log::info!("PDDB mount operation finished successfully");
basis_cache.basis_add(sys_basis);
true
} else {
if pw_state == PasswordState::Correct {
if let Some(sys_basis) = pddb_os.pddb_mount() {
log::info!("PDDB mount operation finished successfully");
basis_cache.basis_add(sys_basis);
return true
}
}
// correct password but no mount -> offer to format; uninit -> offer to format
if pw_state == PasswordState::Correct || pw_state == PasswordState::Uninit {
#[cfg(any(target_os = "none", target_os = "xous"))]
{
log::debug!("PDDB did not mount; requesting format");
@ -1162,6 +1182,9 @@ fn try_mount_or_format(modals: &modals::Modals, pddb_os: &mut PddbOs, basis_cach
false
}
}
} else {
// password was incorrect, don't try anything just return false
false
}
}

View file

@ -46,6 +46,7 @@ sha2 = {path = "../engine-sha512"}
digest = "0.9.0"
aes={path="../aes"}
engine-25519 = {path="../engine-25519"}
byteorder = "1.4.3" # used by keywrap
# hardware acceleration adaptations are inserted into a fork of the main branch.
rand_core = "0.5.1"
hex = {version = "0.4.3", default-features = false, features = []}

View file

@ -15,6 +15,8 @@ pub(crate) enum Opcode {
IsJtagWorking,
/// initiate an AES oracle operation
AesOracle,
/// initiate key wrapper operation
AesKwp,
/// create new FPGA keys; provisioning requires a slave device to be connected that can run the JTAG sequence
BbramProvision,
/// clear a cached password
@ -151,4 +153,53 @@ impl AesOp {
}
}
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Zeroize, Eq, PartialEq, Copy, Clone)]
pub enum KeywrapError {
/// Input is too big.
TooBig,
/// Input is too small.
TooSmall,
/// Ciphertext has invalid padding.
Unpadded,
/// The ciphertext is not valid for the expected length.
InvalidExpectedLen,
/// The ciphertext couldn't be authenticated.
AuthenticationFailed,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Zeroize, Eq, PartialEq)]
pub enum KeyWrapOp {
Wrap,
Unwrap,
}
use std::error::Error;
impl Error for KeywrapError {}
use std::fmt;
impl fmt::Display for KeywrapError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
KeywrapError::TooBig => f.write_str("Input too big"),
KeywrapError::TooSmall => f.write_str("Input too small"),
KeywrapError::Unpadded => f.write_str("Padding error"),
KeywrapError::InvalidExpectedLen => f.write_str("Invalid expected lengthr"),
KeywrapError::AuthenticationFailed => f.write_str("Authentication failed"),
}
}
}
pub(crate) const MAX_WRAP_DATA: usize = 2048;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Zeroize)]
#[zeroize(drop)]
pub (crate) struct KeyWrapper {
pub data: [u8; MAX_WRAP_DATA + 8],
// used to specify the length of the data used in the fixed-length array above
pub len: u32,
pub key_index: u8,
pub op: KeyWrapOp,
pub result: Option<KeywrapError>,
// used by the unwrap side
pub expected_len: u32,
}

View file

@ -1,5 +1,7 @@
mod oracle;
use oracle::*;
mod keywrap;
use keywrap::*;
pub use oracle::FpgaKeySource;
use utralib::generated::*;
@ -349,6 +351,63 @@ impl<'a> RootKeys {
}
}
}
pub fn kwp_op(&mut self, kwp: &mut KeyWrapper) {
let key = match kwp.key_index {
KeyRomLocs::USER_KEY => {
let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY);
let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)};
if pcache.hashed_boot_pw_valid == 0 {
self.purge_password(PasswordType::Boot);
log::warn!("boot password isn't valid! Returning bogus results.");
}
for (key, &pw) in
key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) {
*key = *key ^ pw;
}
if self.boot_password_policy == PasswordRetentionPolicy::AlwaysPurge {
self.purge_password(PasswordType::Boot);
}
key_enc
},
_ => {
self.fake_key[0] = kwp.key_index;
self.fake_key
}
};
let keywrapper = Aes256KeyWrap::new(&key);
match kwp.op {
KeyWrapOp::Wrap => {
match keywrapper.encapsulate(&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(e);
}
}
}
KeyWrapOp::Unwrap => {
match keywrapper.decapsulate(&kwp.data[..kwp.len as usize], kwp.expected_len as usize) {
Ok(unwrapped) => {
for (&src, dst) in unwrapped.iter().zip(kwp.data.iter_mut()) {
*dst = src;
}
kwp.len = unwrapped.len() as u32;
kwp.result = None;
}
Err(e) => {
kwp.result = Some(e);
}
}
}
}
}
/// returns None if there is an obvious problem with the JTAG interface
/// otherwise returns the result. "secured" would be the most paranoid setting

View file

@ -0,0 +1,180 @@
#![forbid(unsafe_code)]
/// this code is vendored in from https://github.com/jedisct1/rust-aes-keywrap
/// From its original README:
/// AES Key Wrap for Rust
///
/// AES Key Wrap is a construction to encrypt secret keys using a master key.
///
/// This is an AES-KWP (NIST SP800-38F) implementation for Rust.
///
/// It is essentially a 5 round Feistel network using AES as the core function.
/// One half of each AES block is used to encrypt the key, and the second half
/// of the last permutation is used to compute a 64-bit MAC.
///
/// It doesn't require nonces, but still allows key reuse.
///
/// This is a NIST-blessed construction. Other than that, AES Key Wrap is inefficient
/// and is generally not very useful.
use aes::cipher::generic_array::GenericArray;
use aes::Aes256;
use aes::{BlockDecrypt, BlockEncrypt, NewBlockCipher};
use byteorder::{BigEndian, ByteOrder};
use crate::api::KeywrapError;
const FEISTEL_ROUNDS: usize = 5;
#[derive(Debug)]
pub struct Aes256KeyWrap {
aes: Aes256,
}
impl Aes256KeyWrap {
pub const KEY_BYTES: usize = 32;
pub const MAC_BYTES: usize = 8;
pub fn new(key: &[u8; Self::KEY_BYTES]) -> Self {
Aes256KeyWrap {
aes: Aes256::new(key.into()),
}
}
pub fn encapsulate(&self, input: &[u8]) -> Result<Vec<u8>, KeywrapError> {
if input.len() > std::u32::MAX as usize
|| input.len() as u64 >= std::u64::MAX / FEISTEL_ROUNDS as u64
{
return Err(KeywrapError::TooBig);
}
let mut aiv: [u8; 8] = [0xa6u8, 0x59, 0x59, 0xa6, 0, 0, 0, 0];
BigEndian::write_u32(&mut aiv[4..8], input.len() as u32);
let mut block = [0u8; 16];
let mut block = GenericArray::from_mut_slice(&mut block);
block[0..8].copy_from_slice(&aiv);
if input.len() == 8 {
block[8..16].copy_from_slice(input);
self.aes.encrypt_block(&mut block);
return Ok(block.to_vec());
}
let mut counter = 0u64;
let mut counter_bin = [0u8; 8];
let mut output = vec![0u8; ((input.len() + 7) & !7) + Self::MAC_BYTES];
output[8..][..input.len()].copy_from_slice(input);
for _ in 0..FEISTEL_ROUNDS {
let mut i = 8;
while i <= (input.len() + 7) & !7 {
block[8..16].copy_from_slice(&output[i..][0..8]);
self.aes.encrypt_block(&mut block);
counter += 1;
BigEndian::write_u64(&mut counter_bin, counter);
block[8..16]
.iter_mut()
.zip(counter_bin.iter())
.for_each(|(a, b)| *a ^= b);
output[i..i + 8].copy_from_slice(&block[8..16]);
i += 8;
}
}
output[0..8].copy_from_slice(&block[0..8]);
Ok(output)
}
pub fn decapsulate(&self, input: &[u8], expected_len: usize) -> Result<Vec<u8>, KeywrapError> {
if input.len() % 8 != 0 {
return Err(KeywrapError::Unpadded);
}
let output_len = input
.len()
.checked_sub(Self::MAC_BYTES)
.ok_or(KeywrapError::TooSmall)?;
if output_len > std::u32::MAX as usize
|| output_len as u64 >= std::u64::MAX / FEISTEL_ROUNDS as u64
{
return Err(KeywrapError::TooBig);
}
if expected_len > output_len || (expected_len & !7) > output_len {
return Err(KeywrapError::InvalidExpectedLen);
}
let mut output = vec![0u8; output_len];
let mut aiv: [u8; 8] = [0xa6u8, 0x59, 0x59, 0xa6, 0, 0, 0, 0];
BigEndian::write_u32(&mut aiv[4..8], expected_len as u32);
let mut block = [0u8; 16];
let mut block = GenericArray::from_mut_slice(&mut block);
if output.len() == 8 {
block.copy_from_slice(input);
self.aes.decrypt_block(&mut block);
let c = block[0..8]
.iter()
.zip(aiv.iter())
.fold(0, |acc, (a, b)| acc | (a ^ b));
if c != 0 {
return Err(KeywrapError::AuthenticationFailed);
}
output[0..8].copy_from_slice(&block[8..16]);
return Ok(output);
}
output.copy_from_slice(&input[8..]);
block[0..8].copy_from_slice(&input[0..8]);
let mut counter = (FEISTEL_ROUNDS * output.len() / 8) as u64;
let mut counter_bin = [0u8; 8];
for _ in 0..FEISTEL_ROUNDS {
let mut i = output.len();
while i >= 8 {
i -= 8;
block[8..16].copy_from_slice(&output[i..][0..8]);
BigEndian::write_u64(&mut counter_bin, counter);
counter -= 1;
block[8..16]
.iter_mut()
.zip(counter_bin.iter())
.for_each(|(a, b)| *a ^= b);
self.aes.decrypt_block(&mut block);
output[i..][0..8].copy_from_slice(&block[8..16]);
}
}
let c = block[0..8]
.iter()
.zip(aiv.iter())
.fold(0, |acc, (a, b)| acc | (a ^ b));
if c != 0 {
return Err(KeywrapError::AuthenticationFailed);
}
Ok(output)
}
}
#[test]
fn aligned() {
let secret = b"1234567812345678";
let key = [42u8; 32];
let kw = Aes256KeyWrap::new(&key);
let wrapped = kw.encapsulate(secret).unwrap();
let unwrapped = kw.decapsulate(&wrapped, secret.len()).unwrap();
assert_eq!(secret, unwrapped.as_slice());
}
#[test]
fn not_aligned() {
let secret = b"1234567812345";
let key = [42u8; 32];
let kw = Aes256KeyWrap::new(&key);
let wrapped = kw.encapsulate(secret).unwrap();
let unwrapped = kw.decapsulate(&wrapped, secret.len()).unwrap();
assert_eq!(secret, &unwrapped.as_slice()[..secret.len()]);
}
#[test]
fn singleblock() {
let secret = b"12345678";
let key = [42u8; 32];
let kw = Aes256KeyWrap::new(&key);
let wrapped = kw.encapsulate(secret).unwrap();
let unwrapped = kw.decapsulate(&wrapped, secret.len()).unwrap();
assert_eq!(secret, unwrapped.as_slice());
}

View file

@ -168,6 +168,93 @@ impl RootKeys {
pass_type.to_usize().unwrap(), 0, 0, 0)
).expect("couldn't send bbram provision message");
}
pub fn wrap_key(&self, input: &[u8]) -> Result<Vec<u8>, KeywrapError> {
if input.len() > api::MAX_WRAP_DATA {
// of course, the underlying crypto can handle a much larger piece of data,
// but the intention of this API is to wrap crypto keys -- not bulk data. So for simplicity
// we're going to limit the size of wrapped data to 2kiB (typically it's envisioned you're
// wrapping data on the order of 32-512 bytes)
return Err(KeywrapError::TooBig)
}
if !self.ensure_aes_password() {
return Err(KeywrapError::AuthenticationFailed);
}
let mut alloc = KeyWrapper {
data: [0u8; MAX_WRAP_DATA + 8],
len: input.len() as u32,
key_index: self.key_index.to_u8().unwrap(),
op: KeyWrapOp::Wrap,
result: Some(KeywrapError::AuthenticationFailed), // initialize to a default value that throws an error if it wasn't modified by the recipient
// this field is ignored on the Wrap side
expected_len: 0,
};
for (&src, dst) in input.iter().zip(alloc.data.iter_mut()) {
*dst = src;
}
let mut buf = Buffer::into_buf(alloc).or(Err(KeywrapError::AuthenticationFailed))?;
buf.lend_mut(self.conn, Opcode::AesKwp.to_u32().unwrap()).or(Err(KeywrapError::AuthenticationFailed))?;
let ret = buf.to_original::<KeyWrapper, _>().unwrap();
match ret.result {
None => { // no error, proceed
Ok(ret.data[..ret.len as usize].to_vec(),)
}
Some(err) => {
Err(err)
}
}
}
pub fn unwrap_key(&self, wrapped: &[u8], expected_len: usize) -> Result<Vec<u8>, KeywrapError> {
if wrapped.len() > api::MAX_WRAP_DATA + 8 {
return Err(KeywrapError::TooBig)
}
if !self.ensure_aes_password() {
return Err(KeywrapError::AuthenticationFailed);
}
let mut alloc = KeyWrapper {
data: [0u8; MAX_WRAP_DATA + 8],
len: wrapped.len() as u32,
key_index: self.key_index.to_u8().unwrap(),
op: KeyWrapOp::Unwrap,
result: Some(KeywrapError::AuthenticationFailed), // initialize to a default value that throws an error if it wasn't modified by the recipient
expected_len: expected_len as u32,
};
for (&src, dst) in wrapped.iter().zip(alloc.data.iter_mut()) {
*dst = src;
}
let mut buf = Buffer::into_buf(alloc).or(Err(KeywrapError::AuthenticationFailed))?;
buf.lend_mut(self.conn, Opcode::AesKwp.to_u32().unwrap()).or(Err(KeywrapError::AuthenticationFailed))?;
let ret = buf.to_original::<KeyWrapper, _>().unwrap();
match ret.result {
None => { // no error, proceed
if ret.len as usize != expected_len {
// The key wrapper will return a vector that is rounded to the nearest 8-bytes, with
// a zero-pad on the excess data. Ensure that the zero-pad is intact before lopping it off.
if (ret.len as usize) < expected_len {
Err(KeywrapError::InvalidExpectedLen)
} else {
let mut all_zeroes = true;
for &d in ret.data[expected_len..ret.len as usize].iter() {
if d != 0 {
all_zeroes = false;
break;
}
}
if all_zeroes {
Ok(ret.data[..expected_len as usize].to_vec(),)
} else {
Err(KeywrapError::InvalidExpectedLen)
}
}
} else {
Ok(ret.data[..expected_len as usize].to_vec(),)
}
}
Some(err) => {
Err(err)
}
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -80,6 +80,8 @@ pub struct MetadataInFlash {
// a stub to try to avoid breaking hosted mode for as long as possible.
#[cfg(not(any(target_os = "none", target_os = "xous")))]
mod implementation {
mod keywrap;
use keywrap::*;
use crate::PasswordRetentionPolicy;
use crate::PasswordType;
use gam::modal::{Modal, Slider};
@ -99,7 +101,7 @@ mod implementation {
Efuse,
}
#[allow(dead_code)]
pub struct RootKeys {
pub(crate) struct RootKeys {
password_type: Option<PasswordType>,
jtag: jtag::Jtag,
xns: xous_names::XousNames,
@ -252,6 +254,41 @@ mod implementation {
}
}
}
pub fn kwp_op(&mut self, kwp: &mut KeyWrapper) {
let keywrapper = Aes256KeyWrap::new(&[0u8; 32]);
match kwp.op {
KeyWrapOp::Wrap => {
match keywrapper.encapsulate(&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(e);
}
}
}
KeyWrapOp::Unwrap => {
match keywrapper.decapsulate(&kwp.data[..kwp.len as usize], kwp.expected_len as usize) {
Ok(unwrapped) => {
for (&src, dst) in unwrapped.iter().zip(kwp.data.iter_mut()) {
*dst = src;
}
kwp.len = unwrapped.len() as u32;
kwp.result = None;
}
Err(e) => {
kwp.result = Some(e);
}
}
}
}
}
}
}
@ -914,6 +951,12 @@ fn xmain() -> ! {
};
buffer.replace(aes_op).unwrap();
},
Some(Opcode::AesKwp) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut kwp = buffer.to_original::<KeyWrapper, _>().unwrap();
keys.kwp_op(&mut kwp);
buffer.replace(kwp).unwrap();
}
Some(Opcode::BbramProvision) => {
modals.show_notification(t!("rootkeys.bbram.confirm", xous::LANG)).expect("modals error");

View file

@ -351,6 +351,7 @@ Various debug configurations:
wycheproof-import generate binary test vectors for engine-25519 from whycheproof-import/x25519.json
pddb-dev PDDB testing only for live hardware
pddb-hosted PDDB testing in a hosted environment
pddb-ci PDDB config for CI testing (eg: TRNG->deterministic for reproducible errors)
"
)