/// Test data and functions to help with testing. use super::*; use btserde::{Error, Result}; use crypto::{self, *}; use nix::{ sys::signal::{self, Signal}, unistd::Pid, }; use std::{ cell::RefCell, fmt::Write as FmtWrite, fs::File, io::{Cursor, Write}, path::PathBuf, process::{Command, ExitStatus}, str::FromStr, sync::atomic::{AtomicU16, Ordering}, }; use tempdir::TempDir; use tss_esapi::{ tcti_ldr::{NetworkTPMConfig, TctiNameConf}, Context, }; pub const PRINCIPAL: [u8; 32] = [ 0x75, 0x28, 0xA9, 0xE0, 0x9D, 0x24, 0xBA, 0xB3, 0x79, 0x56, 0x15, 0x68, 0xFD, 0xA4, 0xE2, 0xA4, 0xCF, 0xB2, 0xC0, 0xE3, 0x96, 0xAE, 0xA2, 0x6E, 0x45, 0x15, 0x50, 0xED, 0xA6, 0xBE, 0x6D, 0xEC, ]; pub const PRINCIPAL2: [u8; 32] = [ 0x6E, 0x8A, 0x76, 0x1D, 0xC7, 0x3B, 0x50, 0x90, 0x51, 0x9E, 0x73, 0x9B, 0xEE, 0x7B, 0x02, 0xF9, 0xB9, 0x17, 0x7C, 0xF6, 0xBB, 0xC8, 0xD5, 0x30, 0xBF, 0x2A, 0xB4, 0xDE, 0x1B, 0x38, 0xCC, 0xF6, ]; pub const PAYLOAD: [u8; 128] = [ 0x39, 0x79, 0x1A, 0x0D, 0x8E, 0x6C, 0xF5, 0x4B, 0xF3, 0xA4, 0x75, 0xC4, 0x44, 0x73, 0x58, 0x58, 0x97, 0x14, 0x64, 0xE0, 0xC6, 0xFE, 0xCB, 0xCF, 0xBE, 0x67, 0x49, 0x49, 0x40, 0xAE, 0x71, 0x5A, 0x94, 0x7E, 0x6C, 0x4B, 0xDE, 0x33, 0x22, 0x75, 0xD8, 0x54, 0x23, 0x37, 0xFD, 0x1A, 0x68, 0x4A, 0x5F, 0xB5, 0xB3, 0xC9, 0x9A, 0x72, 0x7C, 0xF4, 0x3C, 0xAB, 0xED, 0x97, 0x87, 0x63, 0xBB, 0xD9, 0x8B, 0x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xD9, 0xC7, 0x0C, 0x2C, 0xF8, 0x80, 0xCB, 0xF2, 0x3E, 0x1A, 0xE9, 0x43, 0x23, 0xAF, 0x62, 0x57, 0xD1, 0x4C, 0xFD, 0x05, 0xB6, 0xB6, 0x86, 0xB9, 0x86, 0x40, 0xC2, 0x56, 0x45, 0x52, 0xE2, 0x93, 0x62, 0x65, 0x23, 0xE7, 0x1D, 0x89, 0xCA, 0x40, 0x23, 0x44, 0xDB, 0x56, 0x90, 0x4A, 0x0E, 0xB1, 0xB1, 0xE1, 0x9B, 0x5A, 0x5D, 0x53, 0xEF, 0x4E, 0xE1, 0x0E, 0x12, 0xA9, 0x7C, 0x11, 0x0B, 0x6A, 0x4C, 0x3A, 0x8F, 0x2B, 0x9F, 0xC6, 0x42, 0xD7, 0xFE, 0x7D, 0x10, 0x02, 0xBD, 0x31, 0x21, 0xCD, 0xD1, 0x32, 0x04, 0x22, 0xE2, 0x36, ]; pub(crate) static BLOCK_KEY: SymKey = { const KEY: [u8; 32] = [ 0xB2, 0xB3, 0xDA, 0x5A, 0x1A, 0xF6, 0xB3, 0x78, 0x30, 0xAB, 0x1D, 0x33, 0x33, 0xE7, 0xE3, 0x5B, 0xBB, 0xF9, 0xFE, 0xD0, 0xC1, 0xF7, 0x90, 0x34, 0x69, 0xB7, 0xE7, 0xC6, 0x1C, 0x46, 0x85, 0x48, ]; const IV: [u8; 16] = [ 0xEC, 0x19, 0x59, 0x3A, 0x1D, 0x1E, 0x4A, 0x58, 0x66, 0xC1, 0xD1, 0x9A, 0x61, 0x6E, 0xBA, 0x16, ]; SymKey::Aes256Cbc { key: KEY, iv: IV } }; lazy_static! { pub static ref ROOT_CREDS: ConcreteCreds = ConcreteCreds::generate().expect("root cred generation failed"); pub static ref NODE_CREDS: ConcreteCreds = ConcreteCreds::generate().expect("node cred generation failed"); } /// Converts the given error to a serde_block_tree error by turning it into a message. fn convert_err(err: E) -> Error { Error::Message(err.to_string()) } pub(crate) fn make_principal() -> Principal { Principal(Hash::Sha2_256(PRINCIPAL)) } pub(crate) fn make_path_with_owner(owner: Principal, rel_components: Vec<&str>) -> Path { let mut components = Vec::with_capacity(rel_components.len() + 1); components.push(owner.0.to_string()); for component in rel_components { components.push(component.to_string()); } Path { owner, components } } pub(crate) fn make_path(rel_components: Vec<&str>) -> Path { make_path_with_owner(make_principal(), rel_components) } pub(crate) fn make_writecap_and_creds(rel_components: Vec<&str>) -> (Writecap, impl Creds) { let (root_writecap, root_key) = make_self_signed_writecap(); let issued_to = Principal(Hash::Sha2_256(PRINCIPAL)); ( make_writecap_trusted_by(root_writecap, &root_key, issued_to, rel_components), root_key, ) } pub(crate) fn make_writecap(rel_components: Vec<&str>) -> Writecap { let (writecap, ..) = make_writecap_and_creds(rel_components); writecap } pub(crate) fn make_writecap_trusted_by( next: Writecap, trusting_creds: &C, issued_to: Principal, path_components: Vec<&str>, ) -> Writecap { let hour_hence = Epoch::now() + Duration::from_secs(3600); let mut writecap = Writecap { issued_to, path: make_path_with_owner(next.path.owner.clone(), path_components), expires: hour_hence, signing_key: trusting_creds.public_sign().clone(), signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256), next: Some(Box::from(next)), }; crypto::sign_writecap(&mut writecap, trusting_creds) .map_err(convert_err) .expect("failed to sign writecap"); writecap } pub(crate) fn make_key_pair() -> impl Creds { ROOT_CREDS.clone() } pub(crate) fn make_self_signed_writecap() -> (Writecap, impl Creds) { let key = make_key_pair(); (make_self_signed_writecap_with(&key), key) } pub(crate) fn make_self_signed_writecap_with(key: &C) -> Writecap { let root_principal = key.owner(); let hour_hence = Epoch::now() + Duration::from_secs(3600); let mut writecap = Writecap { issued_to: root_principal.clone(), path: make_path_with_owner(root_principal, vec![]), expires: hour_hence, signing_key: key.public_sign().clone(), signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256), next: None, }; crypto::sign_writecap(&mut writecap, key) .map_err(convert_err) .expect("failed to sign writecap"); writecap } pub(crate) fn make_readcap() -> Readcap { make_readcap_for(&*ROOT_CREDS) } pub(crate) fn make_readcap_for(creds: &C) -> Readcap { Readcap { issued_to: creds.owner(), key: crypto::encrypt(&BLOCK_KEY, creds).expect("failed to encrypt block key"), } } pub(crate) fn make_block() -> Box { make_block_with(make_readcap()) } pub(crate) fn make_block_with(readcap: Readcap) -> Box { let mut readcaps = HashMap::new(); readcaps.insert(readcap.issued_to, readcap.key); // Notice that the writecap path contains the block path. If this were not the case, the block // would be invalid. let (writecap, creds) = make_writecap_and_creds(vec!["apps"]); let root_writecap = writecap.next.as_ref().unwrap(); let header = Header { path: make_path_with_owner(root_writecap.issued_to.clone(), vec!["apps", "verse"]), readcaps, writecap: Some(writecap), integrity: Some(Hash::Sha2_256([0u8; HashKind::Sha2_256.len()])), }; let sig = Signature::copy_from(Sign::RSA_PSS_3072_SHA_256, &SIGNATURE); let mut stream = BlockStream::new(BtCursor::new(Vec::new()), creds).expect("create block stream failed"); stream.trailer.header = header; stream.trailer.sig = sig; let block_key = stream.block_key().expect("get block key failed"); let stream = MerkleStream::new(stream).expect("create merkle stream failed"); let stream = SecretStream::new(block_key) .try_compose(stream) .expect("create secret stream failed"); let stream = SectoredBuf::new() .try_compose(stream) .expect("create sectored buf failed"); Box::new(stream) } /// This function can be run as a test to write a new RSA key pair, as two Rust arrays, /// out to a file. fn write_test_keys() -> Result<()> { write_rsa_keys_to_file("test_keys.rs") } struct NamedSlice<'a> { name: &'a str, slice: &'a [u8], } impl<'a> NamedSlice<'a> { fn new(name: &'a str, slice: &'a [u8]) -> NamedSlice<'a> { NamedSlice { name, slice } } } fn write_rsa_keys_to_file(path: &str) -> Result<()> { use openssl::rsa::Rsa; let rsa = Rsa::generate(3072).map_err(convert_err)?; let public_der = rsa.public_key_to_der().map_err(convert_err)?; let private_der = rsa.private_key_to_der().map_err(convert_err)?; let slices = [ NamedSlice::new("PUBLIC", public_der.as_slice()), NamedSlice::new("PRIVATE", private_der.as_slice()), ]; write_to_file(path, slices.into_iter()) } fn write_to_file<'a, I: Iterator>>(path: &str, slices: I) -> Result<()> { let path = std::path::Path::new(path); let mut file = File::create(path).map_err(Error::Io)?; for NamedSlice { name, slice } in slices { write_slice(&mut file, name, slice)?; } Ok(()) } fn write_slice(output: &mut W, name: &str, slice: &[u8]) -> Result<()> { const LINE_LEN: usize = 100; let mut line = String::with_capacity(LINE_LEN); write!(line, " ").map_err(Error::Format)?; writeln!(output, "pub const {}: [u8; {}] = [", name, slice.len()).map_err(Error::Io)?; for byte in slice { if line.len() + 6 > LINE_LEN { writeln!(output, "{}", line).map_err(Error::Io)?; line.clear(); write!(line, " ").map_err(Error::Format)?; } write!(line, "0x{:02X?}, ", byte).map_err(Error::Format)?; } writeln!(output, "{}", line).map_err(Error::Io)?; writeln!(output, "];").map_err(Error::Io)?; writeln!(output).map_err(Error::Io)?; Ok(()) } /// A naive randomizer implementation that is intended only for testing. pub struct Randomizer { state: [u8; Self::HASH.len()], buf: [u8; Self::HASH.len()], } impl Randomizer { pub const HASH: HashKind = HashKind::Sha2_256; pub fn new(seed: [u8; Self::HASH.len()]) -> Randomizer { Randomizer { state: seed, buf: [0u8; Self::HASH.len()], } } } impl Iterator for Randomizer { type Item = usize; fn next(&mut self) -> Option { const BYTES: usize = usize::BITS as usize / 8; Self::HASH .digest(&mut self.buf, std::iter::once(self.state.as_slice())) .expect("digest failed"); self.state.copy_from_slice(&self.buf); let int_bytes = self.buf.as_slice()[..BYTES] .try_into() .expect("failed to convert array"); Some(usize::from_ne_bytes(int_bytes)) } } pub fn make_sector(mut buf: &mut [u8], sect_index: usize) { let data = (sect_index + 1).to_ne_bytes(); for chunk in std::iter::repeat(data).take(buf.len() / data.len()) { (&mut buf[..chunk.len()]).copy_from_slice(chunk.as_slice()); buf = &mut buf[chunk.len()..]; } } pub fn write_fill(mut write: W, sect_sz: usize, sect_ct: usize) { let mut buf = vec![0u8; sect_sz]; for sect_index in 0..sect_ct { make_sector(&mut buf, sect_index); write.write_all(&mut buf).expect("write failed"); } write.flush().expect("flush failed"); } pub fn read_check(mut read: R, sect_sz: usize, sect_ct: usize) { let mut actual = vec![0u8; sect_sz]; let mut expected = vec![0u8; sect_sz]; for sect_index in 0..sect_ct { make_sector(&mut expected, sect_index); read.read_exact(&mut actual).expect("read failed"); assert_eq!(expected, actual); } } /// Trait for types which can be referenced as slices and which support conversion from `Vec`. pub trait FromVec: AsRef<[u8]> { fn from_vec(vec: Vec) -> Self; } impl FromVec for Vec { fn from_vec(vec: Vec) -> Self { vec } } impl FromVec for [u8; N] { fn from_vec(vec: Vec) -> Self { assert_eq!(N, vec.len()); let mut buf = [0u8; N]; buf.copy_from_slice(&vec); buf } } /// Module containing functions for serializing and deserializing buffers in `SectoredCursor`. mod serde_cursor { use super::FromVec; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::{ cell::RefCell, io::{Cursor, Read}, result::Result, }; pub fn serialize, S: Serializer>( cursor: &RefCell>, ser: S, ) -> Result { let mut cursor = cursor.borrow_mut(); let pos = cursor.position(); cursor.set_position(0); let mut data = Vec::new(); cursor .read_to_end(&mut data) .expect("reading from cursor failed"); cursor.set_position(pos); data.serialize(ser) } pub fn deserialize<'de, T: FromVec, D: Deserializer<'de>>( de: D, ) -> Result>, D::Error> { let data = Vec::::deserialize(de)?; Ok(RefCell::new(Cursor::new(T::from_vec(data)))) } } /// A wrapper for `Cursor` which implements additional traits. #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct BtCursor { #[serde(with = "serde_cursor")] cursor: RefCell>, } impl BtCursor { pub(crate) fn new(inner: T) -> BtCursor { BtCursor { cursor: RefCell::new(Cursor::new(inner)), } } } impl Write for BtCursor> { fn write(&mut self, buf: &[u8]) -> io::Result { self.cursor.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor.get_mut().flush() } } impl Write for BtCursor<[u8; N]> { fn write(&mut self, buf: &[u8]) -> io::Result { self.cursor.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor.get_mut().flush() } } impl Read for BtCursor { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.cursor.get_mut().read(buf) } } impl Seek for BtCursor { fn seek(&mut self, pos: SeekFrom) -> io::Result { self.cursor.get_mut().seek(pos) } } impl WriteInteg for BtCursor> { fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> { Ok(()) } } impl WriteInteg for BtCursor<[u8; N]> { fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> { Ok(()) } } #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct SectoredCursor { cursor: BtCursor, sect_sz: usize, } impl SectoredCursor { pub fn new(inner: T, sect_sz: usize) -> SectoredCursor { SectoredCursor { cursor: BtCursor::new(inner), sect_sz, } } } impl Sectored for SectoredCursor { fn sector_sz(&self) -> usize { self.sect_sz } } impl Write for SectoredCursor> { fn write(&mut self, buf: &[u8]) -> io::Result { self.assert_sector_sz(buf.len())?; self.cursor.write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor.flush() } } impl Write for SectoredCursor<[u8; N]> { fn write(&mut self, buf: &[u8]) -> io::Result { self.assert_sector_sz(buf.len())?; self.cursor.write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor.flush() } } impl Read for SectoredCursor { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.assert_sector_sz(buf.len())?; self.cursor.read(buf) } } impl Seek for SectoredCursor { fn seek(&mut self, pos: SeekFrom) -> io::Result { self.cursor.seek(pos) } } trait ExitStatusExt { fn success_or_err(&self) -> Result<()>; } impl ExitStatusExt for ExitStatus { fn success_or_err(&self) -> btserde::Result<()> { match self.code() { Some(0) => Ok(()), Some(code) => Err(btserde::Error::Message(format!( "ExitCode was non-zero: {}", code ))), None => Err(btserde::Error::Message("ExitCode was None.".to_string())), } } } pub(crate) struct SwtpmHarness { dir: TempDir, port: u16, state_path: PathBuf, pid_path: PathBuf, } impl SwtpmHarness { const HOST: &'static str = "127.0.0.1"; pub(crate) fn new() -> crypto::Result { static PORT: AtomicU16 = AtomicU16::new(21901); let port = PORT.fetch_add(2, Ordering::SeqCst); let ctrl_port = port + 1; let dir = TempDir::new(format!("swtpm_harness.{port}").as_str())?; let dir_path = dir.path(); let dir_path_display = dir_path.display(); let conf_path = dir_path.join("swtpm_setup.conf"); let state_path = dir_path.join("state.bt"); let pid_path = dir_path.join("swtpm.pid"); let addr = Self::HOST; std::fs::write( &conf_path, r#"# Program invoked for creating certificates #create_certs_tool= /usr/bin/swtpm_localca # Comma-separated list (no spaces) of PCR banks to activate by default active_pcr_banks = sha256 "#, )?; Command::new("swtpm_setup") .args([ "--tpm2", "--config", conf_path.to_str().unwrap(), "--tpm-state", format!("{dir_path_display}").as_str(), ]) .status()? .success_or_err()?; Command::new("swtpm") .args([ "socket", "--daemon", "--tpm2", "--server", format!("type=tcp,port={port},bindaddr={addr}").as_str(), "--ctrl", format!("type=tcp,port={ctrl_port},bindaddr={addr}").as_str(), "--log", format!("file={dir_path_display}/log.txt,level=5").as_str(), "--flags", "not-need-init,startup-clear", "--tpmstate", format!("dir={dir_path_display}").as_str(), "--pid", format!("file={}", pid_path.display()).as_str(), ]) .status()? .success_or_err()?; Ok(SwtpmHarness { dir, port, state_path, pid_path, }) } pub(crate) fn context(&self) -> crypto::Result { let config_string = format!("host={},port={}", Self::HOST, self.port); let config = NetworkTPMConfig::from_str(config_string.as_str())?; Ok(Context::new(TctiNameConf::Swtpm(config))?) } pub(crate) fn dir_path(&self) -> &std::path::Path { self.dir.path() } pub(crate) fn state_path(&self) -> &std::path::Path { &self.state_path } } impl Drop for SwtpmHarness { fn drop(&mut self) { let pid_str = std::fs::read_to_string(&self.pid_path).unwrap(); let pid_int = pid_str.parse::().unwrap(); let pid = Pid::from_raw(pid_int); signal::kill(pid, Signal::SIGKILL).unwrap(); } }