123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611 |
- /// 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, 0x11, 0xD3, 0xC1, 0x4C, 0x9A, 0x09, 0x0E, 0x7C, 0x10, 0x65, 0x9B, 0x8F, 0x35, 0xEB, 0x51,
- 0x19, 0xD7, 0x6E, 0xA3, 0xC9, 0x64, 0xE2, 0x54, 0x84, 0x5F, 0xA1, 0x8B, 0x63, 0x0C, 0xC3, 0x9D,
- 0xBE, 0xBB, 0x7F, 0x31, 0x1D, 0x59, 0xE2, 0x68, 0xC4, 0x5B, 0x37, 0x77, 0x04, 0xAD, 0x44, 0x75,
- 0xEE, 0x1F, 0x84, 0x17, 0xA2, 0x74, 0xC3, 0xC3, 0xD5, 0x2F, 0x70, 0x74, 0xFE, 0xD8, 0x2C, 0x29,
- ];
- pub const SIGNATURE: [u8; 384] = [
- 0x12, 0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7C, 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<E: Display>(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<C: Creds>(
- 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<C: Creds>(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<C: Encrypter + Owned>(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<dyn Block> {
- make_block_with(make_readcap())
- }
- pub(crate) fn make_block_with(readcap: Readcap) -> Box<dyn Block> {
- 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<Item = NamedSlice<'a>>>(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<W: Write>(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<Self::Item> {
- 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<W: Write>(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<R: Read>(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<u8>`.
- pub trait FromVec: AsRef<[u8]> {
- fn from_vec(vec: Vec<u8>) -> Self;
- }
- impl FromVec for Vec<u8> {
- fn from_vec(vec: Vec<u8>) -> Self {
- vec
- }
- }
- impl<const N: usize> FromVec for [u8; N] {
- fn from_vec(vec: Vec<u8>) -> 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<T>`.
- mod serde_cursor {
- use super::FromVec;
- use serde::{Deserialize, Deserializer, Serialize, Serializer};
- use std::{
- cell::RefCell,
- io::{Cursor, Read},
- result::Result,
- };
- pub fn serialize<T: AsRef<[u8]>, S: Serializer>(
- cursor: &RefCell<Cursor<T>>,
- ser: S,
- ) -> Result<S::Ok, S::Error> {
- 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<RefCell<Cursor<T>>, D::Error> {
- let data = Vec::<u8>::deserialize(de)?;
- Ok(RefCell::new(Cursor::new(T::from_vec(data))))
- }
- }
- /// A wrapper for `Cursor<T>` which implements additional traits.
- #[derive(Debug, PartialEq, Serialize, Deserialize)]
- pub struct BtCursor<T: FromVec> {
- #[serde(with = "serde_cursor")]
- cursor: RefCell<Cursor<T>>,
- }
- impl<T: FromVec> BtCursor<T> {
- pub(crate) fn new(inner: T) -> BtCursor<T> {
- BtCursor {
- cursor: RefCell::new(Cursor::new(inner)),
- }
- }
- }
- impl Write for BtCursor<Vec<u8>> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.cursor.get_mut().write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.cursor.get_mut().flush()
- }
- }
- impl<const N: usize> Write for BtCursor<[u8; N]> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.cursor.get_mut().write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.cursor.get_mut().flush()
- }
- }
- impl<T: FromVec> Read for BtCursor<T> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- self.cursor.get_mut().read(buf)
- }
- }
- impl<T: FromVec> Seek for BtCursor<T> {
- fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
- self.cursor.get_mut().seek(pos)
- }
- }
- impl WriteInteg for BtCursor<Vec<u8>> {
- fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> {
- Ok(())
- }
- }
- impl<const N: usize> WriteInteg for BtCursor<[u8; N]> {
- fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> {
- Ok(())
- }
- }
- #[derive(Debug, PartialEq, Serialize, Deserialize)]
- pub struct SectoredCursor<T: FromVec> {
- cursor: BtCursor<T>,
- sect_sz: usize,
- }
- impl<T: FromVec> SectoredCursor<T> {
- pub fn new(inner: T, sect_sz: usize) -> SectoredCursor<T> {
- SectoredCursor {
- cursor: BtCursor::new(inner),
- sect_sz,
- }
- }
- }
- impl<T: FromVec> Sectored for SectoredCursor<T> {
- fn sector_sz(&self) -> usize {
- self.sect_sz
- }
- }
- impl Write for SectoredCursor<Vec<u8>> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.assert_sector_sz(buf.len())?;
- self.cursor.write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.cursor.flush()
- }
- }
- impl<const N: usize> Write for SectoredCursor<[u8; N]> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.assert_sector_sz(buf.len())?;
- self.cursor.write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.cursor.flush()
- }
- }
- impl<T: FromVec> Read for SectoredCursor<T> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- self.assert_sector_sz(buf.len())?;
- self.cursor.read(buf)
- }
- }
- impl<T: FromVec> Seek for SectoredCursor<T> {
- fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
- 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<SwtpmHarness> {
- 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<Context> {
- 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::<i32>().unwrap();
- let pid = Pid::from_raw(pid_int);
- signal::kill(pid, Signal::SIGKILL).unwrap();
- }
- }
|