initial infrastructure for running backups

code to serialize/deserialize and encrypt/decrypt the backup
block.

now filling in the UX flow around this.
This commit is contained in:
bunnie 2022-07-12 03:32:33 +08:00
parent 941d72f3c5
commit 09e1b99315
8 changed files with 370 additions and 2 deletions

2
Cargo.lock generated
View file

@ -2863,6 +2863,7 @@ name = "root-keys"
version = "0.1.0"
dependencies = [
"aes",
"aes-gcm-siv",
"blowfish 0.8.0",
"byteorder",
"cipher 0.4.3",
@ -2885,6 +2886,7 @@ dependencies = [
"rkyv",
"sha2",
"spinor",
"subtle",
"susres",
"ticktimer-server",
"trng",

View file

@ -44,6 +44,11 @@ jtag = {path = "../jtag"}
# for text to speech support
tts-frontend = {path="../tts"}
# backups
# aes-gcm-siv = {version = "0.11.0-pre", default-features = false, features = ["alloc"]}
aes-gcm-siv = {git="https://github.com/RustCrypto/AEADs.git", branch="master"}
subtle = {version = "2.4.1", default-features = false}
# private keys
#sha2 = {version = "0.9.5", default-features = false, features = []}
sha2 = {path = "../engine-sha512"}

View file

@ -206,9 +206,15 @@
"rootkeys.get_update_password": {
"en": "⚠ Critical password request ⚠\nEnter the 'SYSTEM UPDATE' passphrase. This authorizes a system update.",
"ja": "重要なパスワード要求\nSYSTEM UPDATEのパスフレーズを入力してください。これでシステムアップデートが許可されます。",
"zh": "输入密码 软件更新 安全含义:至关重要 ",
"zh": "⚠ 关键密码请求⚠\n输入“系统更新”密码。 这将授权系统更新。",
"en-tts": "Enter update password, in order to authorize a gateware update."
},
"rootkeys.get_update_password_backup": {
"en": "⚠ Critical password request ⚠\nEnter the 'SYSTEM UPDATE' passphrase. This authorizes a backup to be created.",
"ja": "重要なパスワード要求\nSYSTEM UPDATEのパスフレーズを入力してください。これにより、バックアップの作成が許可されます。",
"zh": "⚠ 关键密码请求⚠\n输入“系统更新”密码。 这将授权创建备份。",
"en-tts": "Enter update password, in order to authorize a backup."
},
"rootkeys.gwup.finished": {
"en": "Gateware update finished.\n\nReboot by inserting a paperclip into the small hole on the lower right at your earliest convenience.",
"ja": "ゲートウェアアップデートが終了しました。ご都合の良い時に再起動してください。",

View file

@ -82,6 +82,14 @@ pub(crate) enum Opcode {
ShouldPromptForUpdate = 37,
/// Set the "don't bother me again for an update"
SetPromptForUpdate = 38,
/// Create a backup block (including UX flow that discloses our AES key!)
CreateBackup = 39,
UxCreateBackupPwReturn = 40,
/// Query if a backup exists to be restored
ShouldRestore = 41,
UxShouldRestorePwReturn = 42,
/// Perform the restore operation (including UX to acquire the AES key)
DoRestore = 43,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, Eq)]
@ -195,6 +203,8 @@ use std::error::Error;
impl Error for KeywrapError {}
use std::fmt;
use crate::backups;
impl fmt::Display for KeywrapError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
@ -219,4 +229,17 @@ pub (crate) struct KeyWrapper {
pub result: Option<KeywrapError>,
// used by the unwrap side
pub expected_len: u32,
}
// the BackupHeader type is serialized into u8 before going through rkyv.
// a bit inefficient but convenient, because we need an Option<> of the
// BackupHeader and not the header itself.
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub (crate) struct BackupHeaderIpc {
pub data: Option<[u8; core::mem::size_of::<backups::BackupHeader>()]>,
}
impl Default for BackupHeaderIpc {
fn default() -> Self {
BackupHeaderIpc { data: None::<[u8; core::mem::size_of::<backups::BackupHeader>()]> }
}
}

View file

@ -0,0 +1,253 @@
use zeroize::Zeroize;
use core::mem::size_of;
use core::ops::{Deref, DerefMut};
use aes_gcm_siv::{AesGcmSiv, Nonce, Key, Tag};
use aes_gcm_siv::aead::{Aead, NewAead, Payload};
use aes::Aes256;
use subtle::ConstantTimeEq;
pub const BACKUP_VERSION: u32 = 0x00_01_00_00;
const BACKUP_AAD: &'static str = "PDDB backup v0.1.0";
#[derive(Zeroize, Default)]
#[zeroize(drop)]
pub(crate) struct BackupKey([u8;32]);
#[derive(Zeroize)]
#[zeroize(drop)]
pub(crate) struct KeyRomExport([u32; 256]);
#[repr(u32)]
pub enum BackupOp {
/// backup and restore can be manipulated by the OS without updating the ciphertext
Backup,
Restore,
/// This is the value that's kept inside the BackupDataPt
Archive,
}
#[repr(C, align(8))]
pub struct BackupHeader {
pub version: u32,
// the `ver`s are all serialized SemVers. To be done by the caller.
pub xous_ver: [u8; 16],
pub soc_ver: [u8; 16],
pub ec_ver: [u8; 16],
pub wf200_ver: [u8; 16],
pub timestamp: u64,
pub _reserved: [u8; 64],
pub op: BackupOp,
}
impl Default for BackupHeader {
fn default() -> Self {
BackupHeader {
version: BACKUP_VERSION,
xous_ver: [0u8; 16],
soc_ver: [0u8; 16],
ec_ver: [0u8; 16],
wf200_ver: [0u8; 16],
timestamp: 0,
_reserved: [0u8; 64],
op: BackupOp::Archive,
}
}
}
impl Deref for BackupHeader {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(self as *const BackupHeader as *const u8, size_of::<BackupHeader>())
as &[u8]
}
}
}
impl DerefMut for BackupHeader {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(self as *mut BackupHeader as *mut u8, size_of::<BackupHeader>())
as &mut [u8]
}
}
}
#[derive(Zeroize)]
#[zeroize(drop)]
#[repr(C, align(8))]
pub(crate) struct BackupDataPt {
/// A sealed copy of the plaintext header, for validation purposes (plaintext can be tampered with)
/// Note: the `op` field is allowed to be manipulated
pub header: BackupHeader, // 144 bytes => 9 aes blocks
/// exact copy of the KEYROM structure
pub keyrom: [u32; 256], // 1024 bytes
/// some reserved space for future things
pub _reserved: [u8; 64],
}
impl Default for BackupDataPt {
fn default() -> Self {
BackupDataPt {
header: BackupHeader::default(),
keyrom: [0u32; 256],
_reserved: [0u8; 64],
}
}
}
impl Deref for BackupDataPt {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(self as *const BackupDataPt as *const u8, size_of::<BackupDataPt>())
as &[u8]
}
}
}
impl DerefMut for BackupDataPt {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(self as *mut BackupDataPt as *mut u8, size_of::<BackupDataPt>())
as &mut [u8]
}
}
}
#[repr(C, align(8))]
pub(crate) struct BackupDataCt {
pub nonce: [u8; 12],
pub ct_plus_mac: [u8; size_of::<BackupDataPt>() + size_of::<Tag>()], // should be 1232 + 16
pub commit_nonce: [u8; 32],
pub commitment: [u8; 32],
}
impl Default for BackupDataCt {
fn default() -> Self {
BackupDataCt {
nonce: [0u8; 12],
ct_plus_mac: [0u8; size_of::<BackupDataPt>() + size_of::<Tag>()],
commit_nonce: [0u8; 32],
commitment: [0u8; 32],
}
}
}
impl Deref for BackupDataCt {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(self as *const BackupDataCt as *const u8, size_of::<BackupDataCt>())
as &[u8]
}
}
}
impl DerefMut for BackupDataCt {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(self as *mut BackupDataCt as *mut u8, size_of::<BackupDataCt>())
as &mut [u8]
}
}
}
/// Derive a key commitment. This takes in a base `key`, which is 256 bits;
/// a `nonce` which is the 96-bit nonce used in the AES-GCM-SIV for a given block;
/// and `nonce_com` which is the commitment nonce, set at 256 bits.
/// The result is two tuples, (kenc, kcom).
fn kcom_func(
key: &[u8; 32],
nonce_com: &[u8; 32]
) -> (BackupKey, BackupKey) {
use sha2::{FallbackStrategy, Sha512Trunc256};
use digest::Digest;
let mut h_enc = Sha512Trunc256::new_with_strategy(FallbackStrategy::SoftwareOnly);
h_enc.update(key);
// per https://eprint.iacr.org/2020/1456.pdf Table 4 on page 13 Type I Lenc
h_enc.update([0x43, 0x6f, 0x6, 0xd6, 0xd, 0x69, 0x74, 0x01, 0x01]);
h_enc.update(nonce_com);
let k_enc = h_enc.finalize();
let mut h_com = Sha512Trunc256::new_with_strategy(FallbackStrategy::SoftwareOnly);
h_com.update(key);
// per https://eprint.iacr.org/2020/1456.pdf Table 4 on page 13 Type I Lcom. Note one-bit difference in last byte.
h_com.update([0x43, 0x6f, 0x6, 0xd6, 0xd, 0x69, 0x74, 0x01, 0x02]);
h_com.update(nonce_com);
let k_com = h_com.finalize();
let mut kenc = BackupKey::default();
let mut kcom = BackupKey::default();
kenc.0.copy_from_slice(k_enc.as_slice());
kcom.0.copy_from_slice(k_com.as_slice());
(kenc, kcom)
}
pub(crate) fn create_backup(
key: BackupKey,
header: BackupHeader,
keyrom: KeyRomExport,
) -> BackupDataCt {
let xns = xous_names::XousNames::new().unwrap();
let mut trng = trng::Trng::new(&xns).unwrap();
// AES-GCM-SIV nonce
let mut nonce: [u8; size_of::<Nonce>()] = [0; size_of::<Nonce>()];
trng.fill_bytes(&mut nonce);
// key commitment nonce
let mut kcom_nonce = [0u8; 32];
trng.fill_bytes(&mut kcom_nonce);
let (kenc, kcom) = kcom_func(&key.0, &kcom_nonce);
let cipher = AesGcmSiv::<Aes256>::new(Key::from_slice(&kenc.0));
// the backup data
let mut backup_data_pt = BackupDataPt::default();
backup_data_pt.header.deref_mut().copy_from_slice(header.deref());
backup_data_pt.header.op = BackupOp::Archive;
backup_data_pt.keyrom.copy_from_slice(&keyrom.0);
// encrypt the backup data
let ciphertext = cipher.encrypt(
&nonce.into(),
Payload {
aad: BACKUP_AAD.as_bytes(),
msg: backup_data_pt.deref(),
}
).expect("couldn't encrypt data");
// copy to a ciphertext record
let mut backup_ct = BackupDataCt::default();
backup_ct.nonce.copy_from_slice(&nonce);
backup_ct.ct_plus_mac.copy_from_slice(&ciphertext); // this will panic if we have the wrong CT size, and that's exactly what we want.
backup_ct.commit_nonce.copy_from_slice(&kcom_nonce);
backup_ct.commitment.copy_from_slice(&kcom.0);
backup_ct
}
/// Returns `None` if the MAC or key commitment fail.
/// It is up to the caller to validate if the plaintext header matches the decrypted
/// version embedded in the return data.
pub(crate) fn restore_backup(
key: BackupKey,
backup: BackupDataCt
) -> Option<BackupDataPt> {
let (kenc, kcom) = kcom_func(&key.0, &backup.commit_nonce);
let cipher = AesGcmSiv::<Aes256>::new(Key::from_slice(&kenc.0));
// Attempt decryption. This is None on failure
let plaintext = cipher.decrypt(
Nonce::from_slice(&backup.nonce),
Payload {
aad: BACKUP_AAD.as_bytes(),
msg: &backup.ct_plus_mac,
}
).ok();
if kcom.0.ct_eq(&backup.commitment).into() {
if let Some(p) = plaintext {
let mut pt = BackupDataPt::default();
pt.deref_mut().copy_from_slice(&p); // panics if pt is the wrong length. we want that.
Some(pt)
} else {
None
}
} else {
None
}
}

View file

@ -5,7 +5,8 @@ use keywrap::*;
pub use oracle::FpgaKeySource;
use utralib::generated::*;
use crate::api::*;
use xous::BACKUP_OFFSET;
use crate::{api::*, backups};
use core::num::NonZeroUsize;
use num_traits::*;
@ -2332,4 +2333,15 @@ impl<'a> RootKeys {
self.gateware().len() as u32 - 4
).expect("couldn't patch update prompt");
}
pub fn read_backup_header(&mut self) -> Option<backups::BackupHeader> {
let kernel = self.kernel();
let backup = &kernel[BACKUP_OFFSET as usize..BACKUP_OFFSET as usize + size_of::<backups::BackupHeader>()];
let mut header = backups::BackupHeader::default();
header.as_mut().copy_from_slice(backup);
if header.version == backups::BACKUP_VERSION {
Some(header)
} else {
None
}
}
}

View file

@ -3,6 +3,7 @@
pub mod api;
use api::*;
pub mod backups;
pub mod key2bits;
@ -101,6 +102,34 @@ impl RootKeys {
).expect("couldn't send message to root keys");
}
pub fn do_create_backup_ux_flow(&self) {
send_message(self.conn,
Message::new_scalar(Opcode::CreateBackup.to_usize().unwrap(),
0, 0, 0, 0)
).expect("couldn't send message to root keys");
}
pub fn do_restore_backup_ux_flow(&self) {
send_message(self.conn,
Message::new_scalar(Opcode::DoRestore.to_usize().unwrap(),
0, 0, 0, 0)
).expect("couldn't send message to root keys");
}
/// Returns the raw, unchecked restore header. Further checking may be done at the restore point,
/// but the purpose of this is to just decide if we should even try to initiate a restore.
pub fn get_restore_header(&self) -> Result<Option<backups::BackupHeader>, xous::Error> {
let alloc = BackupHeaderIpc::default();
let mut buf = Buffer::into_buf(alloc).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::ShouldRestore.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let ret = buf.to_original::<BackupHeaderIpc, _>().unwrap();
if let Some(d) = ret.data {
let mut header = backups::BackupHeader::default();
header.copy_from_slice(&d);
Ok(Some(header))
} else {
Ok(None)
}
}
/// this will return the version number, but always report the commit as None.
/// The 32-bit commit ref isn't useful in version comparisons, it's more to assist
/// maintainer debug. Including this would convert this from a scalar message to

View file

@ -3,6 +3,8 @@
mod api;
use api::*;
mod backups;
use xous::{msg_scalar_unpack, send_message, msg_blocking_scalar_unpack};
#[cfg(feature = "policy-menu")]
use xous_ipc::String;
@ -1198,6 +1200,42 @@ fn main() -> ! {
Some(Opcode::SetPromptForUpdate) => msg_scalar_unpack!(msg, state, _, _, _, {
keys.set_prompt_for_update(if state == 1 {true} else {false});
}),
Some(Opcode::ShouldRestore) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let maybe_header = keys.read_backup_header();
let mut ret = BackupHeaderIpc::default();
if let Some(header) = maybe_header {
let mut data = [0u8; core::mem::size_of::<backups::BackupHeader>()];
data.copy_from_slice(header.as_ref());
ret.data = Some(data);
}
buf.replace(ret).unwrap();
}
Some(Opcode::CreateBackup) => {
keys.set_ux_password_type(Some(PasswordType::Update));
password_action.set_action_opcode(Opcode::UxCreateBackupPwReturn.to_u32().unwrap());
rootkeys_modal.modify(
Some(ActionType::TextEntry(password_action.clone())),
Some(t!("rootkeys.get_update_password_backup", xous::LANG)), false,
None, true, None
);
#[cfg(feature="tts")]
tts.tts_blocking(t!("rootkeys.get_update_password_backup", xous::LANG)).unwrap();
log::info!("{}ROOTKEY.UPDPW,{}", xous::BOOKEND_START, xous::BOOKEND_END);
rootkeys_modal.activate();
}
Some(Opcode::UxUpdateGwPasswordReturn) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let plaintext_pw = buf.to_original::<gam::modal::TextEntryPayloads, _>().unwrap();
keys.hash_and_save_password(plaintext_pw.first().as_str());
plaintext_pw.first().volatile_clear(); // ensure the data is destroyed after sending to the keys enclave
buf.volatile_clear();
keys.set_ux_password_type(None);
// check if the entered password is valid.
}
Some(Opcode::TestUx) => msg_blocking_scalar_unpack!(msg, _arg, _, _, _, {
// dummy test for now
xous::return_scalar(msg.sender, 1234).unwrap();