test_helpers.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. /// Test data and functions to help with testing.
  2. use super::*;
  3. use btserde::{Error, Result};
  4. use crypto::{self, *};
  5. use nix::{
  6. sys::signal::{self, Signal},
  7. unistd::Pid,
  8. };
  9. use std::{
  10. cell::RefCell,
  11. fmt::Write as FmtWrite,
  12. fs::File,
  13. io::{Cursor, Write},
  14. path::PathBuf,
  15. process::{Child, Command, ExitStatus, Stdio},
  16. str::FromStr,
  17. sync::{
  18. atomic::{AtomicU16, Ordering},
  19. mpsc::{channel, Receiver, TryRecvError},
  20. },
  21. };
  22. use tempdir::TempDir;
  23. use tss_esapi::{
  24. tcti_ldr::{TabrmdConfig, TctiNameConf},
  25. Context,
  26. };
  27. pub const PRINCIPAL: [u8; 32] = [
  28. 0x75, 0x28, 0xA9, 0xE0, 0x9D, 0x24, 0xBA, 0xB3, 0x79, 0x56, 0x15, 0x68, 0xFD, 0xA4, 0xE2, 0xA4,
  29. 0xCF, 0xB2, 0xC0, 0xE3, 0x96, 0xAE, 0xA2, 0x6E, 0x45, 0x15, 0x50, 0xED, 0xA6, 0xBE, 0x6D, 0xEC,
  30. ];
  31. pub const PRINCIPAL2: [u8; 32] = [
  32. 0x6E, 0x8A, 0x76, 0x1D, 0xC7, 0x3B, 0x50, 0x90, 0x51, 0x9E, 0x73, 0x9B, 0xEE, 0x7B, 0x02, 0xF9,
  33. 0xB9, 0x17, 0x7C, 0xF6, 0xBB, 0xC8, 0xD5, 0x30, 0xBF, 0x2A, 0xB4, 0xDE, 0x1B, 0x38, 0xCC, 0xF6,
  34. ];
  35. pub const SIGNATURE: [u8; 384] = [
  36. 0x12, 0xB1, 0x09, 0x2F, 0x2B, 0x3C, 0x53, 0xE8, 0x1B, 0x2B, 0x6A, 0xE7, 0x97, 0x42, 0x9D, 0x83,
  37. 0x71, 0x75, 0x65, 0x25, 0xFD, 0xB0, 0x0E, 0x2F, 0xAB, 0x53, 0xB7, 0x03, 0x03, 0x39, 0xEE, 0xE9,
  38. 0x15, 0x19, 0xAB, 0x1A, 0xF1, 0x2C, 0x3C, 0xAB, 0x5C, 0x02, 0xEA, 0xD6, 0xF6, 0x94, 0x36, 0x80,
  39. 0x5F, 0xD1, 0x8E, 0xC4, 0xB9, 0xB5, 0x04, 0x73, 0xBB, 0x77, 0x2C, 0x9C, 0xAF, 0xE6, 0x38, 0xB7,
  40. 0xD8, 0xC1, 0xA3, 0x1B, 0xAD, 0xFB, 0xB2, 0x5E, 0x77, 0xBD, 0x79, 0xDC, 0x4E, 0xEC, 0xEA, 0xFA,
  41. 0x80, 0x9F, 0x12, 0x60, 0xC4, 0xB3, 0x71, 0xAF, 0x1C, 0x28, 0xEE, 0x91, 0x1D, 0x6A, 0x69, 0x31,
  42. 0xA4, 0x5A, 0xAA, 0xBE, 0x0B, 0x20, 0x6A, 0xE1, 0x61, 0x0E, 0x0B, 0x9F, 0x60, 0x73, 0xBE, 0x29,
  43. 0x1F, 0x11, 0x0A, 0x8F, 0x42, 0x8F, 0x80, 0xC1, 0x06, 0x40, 0x29, 0xE9, 0xF1, 0x74, 0x44, 0x69,
  44. 0xCC, 0xD3, 0x05, 0x22, 0x24, 0x87, 0x94, 0x49, 0x4B, 0x5B, 0x62, 0x48, 0x01, 0x7B, 0x05, 0x28,
  45. 0xBE, 0x4D, 0x50, 0x06, 0xE5, 0x67, 0xA8, 0xFB, 0x9A, 0x19, 0x52, 0x57, 0x4B, 0xC4, 0xBB, 0x6A,
  46. 0xF5, 0x0D, 0x67, 0xD0, 0x08, 0x93, 0x81, 0xD2, 0x9E, 0xE2, 0xC8, 0xFA, 0x25, 0xEE, 0x9D, 0xC5,
  47. 0xD8, 0xF4, 0xD5, 0x17, 0xE4, 0xEF, 0xFC, 0x09, 0xB0, 0x09, 0xCA, 0xCA, 0x71, 0x36, 0x61, 0xBE,
  48. 0xC1, 0xD0, 0x53, 0x6D, 0x0C, 0x0A, 0x4D, 0xF1, 0xE0, 0xAB, 0x2C, 0x89, 0x98, 0x81, 0xED, 0x25,
  49. 0xF8, 0x81, 0x8E, 0x2C, 0x46, 0x74, 0x57, 0xCF, 0x5B, 0xE2, 0x14, 0xA5, 0xBF, 0x56, 0xED, 0xD3,
  50. 0x11, 0xE7, 0xB4, 0x8D, 0x89, 0x3A, 0xB2, 0x78, 0xF1, 0xA9, 0x82, 0x9D, 0x3B, 0xE5, 0x6B, 0xD2,
  51. 0xA5, 0xB6, 0xFB, 0x71, 0x0F, 0x98, 0x52, 0x54, 0x1E, 0x98, 0xD2, 0x3B, 0x78, 0x51, 0xD1, 0xE2,
  52. 0x57, 0xAE, 0xB3, 0x34, 0x0E, 0x20, 0x26, 0xCF, 0x4B, 0x1F, 0x12, 0xCA, 0xB1, 0xD5, 0x67, 0x55,
  53. 0xF9, 0xE2, 0xA9, 0x7B, 0xAE, 0x35, 0x35, 0x67, 0xA3, 0xCA, 0xBD, 0xF2, 0x41, 0x4E, 0x3F, 0x7E,
  54. 0x20, 0x72, 0xC2, 0xCC, 0xE4, 0x90, 0x00, 0x04, 0x5D, 0xF7, 0xD9, 0xC7, 0x0C, 0x2C, 0xF8, 0x80,
  55. 0xCB, 0xF2, 0x3E, 0x1A, 0xE9, 0x43, 0x23, 0xAF, 0x62, 0x57, 0xD1, 0x4C, 0xFD, 0x05, 0xB6, 0xB6,
  56. 0x86, 0xB9, 0x86, 0x40, 0xC2, 0x56, 0x45, 0x52, 0xE2, 0x93, 0x62, 0x65, 0x23, 0xE7, 0x1D, 0x89,
  57. 0xCA, 0x40, 0x23, 0x44, 0xDB, 0x56, 0x90, 0x4A, 0x0E, 0xB1, 0xB1, 0xE1, 0x9B, 0x5A, 0x5D, 0x53,
  58. 0xEF, 0x4E, 0xE1, 0x0E, 0x12, 0xA9, 0x7C, 0x11, 0x0B, 0x6A, 0x4C, 0x3A, 0x8F, 0x2B, 0x9F, 0xC6,
  59. 0x42, 0xD7, 0xFE, 0x7D, 0x10, 0x02, 0xBD, 0x31, 0x21, 0xCD, 0xD1, 0x32, 0x04, 0x22, 0xE2, 0x36,
  60. ];
  61. /// The key of the parent of test blocks.
  62. pub(crate) static PARENT_KEY: SymKey = {
  63. let key = [
  64. 0x35, 0x3D, 0x8C, 0x95, 0x6C, 0x8D, 0xE6, 0xC0, 0xB0, 0xD5, 0x1C, 0xE9, 0x94, 0xB0, 0x58,
  65. 0xD3, 0x80, 0x46, 0x12, 0x1C, 0xF3, 0x9B, 0x8A, 0xEC, 0x38, 0xD5, 0x8B, 0x05, 0x92, 0x8D,
  66. 0xA1, 0x18,
  67. ];
  68. let iv = [
  69. 0xDA, 0x96, 0x0E, 0xF5, 0x00, 0xDB, 0xC8, 0x4E, 0xFB, 0x83, 0x59, 0x99, 0x6C, 0x18, 0xD1,
  70. 0x27,
  71. ];
  72. SymKey::Aes256Cbc { key, iv }
  73. };
  74. lazy_static! {
  75. static ref INHERIT: Ciphertext<SymKey> = PARENT_KEY
  76. .ser_encrypt(&BLOCK_KEY)
  77. .expect("failed to encrypt block key");
  78. }
  79. /// The key used to encrypt test blocks.
  80. pub(crate) static BLOCK_KEY: SymKey = {
  81. let key = [
  82. 0xB2, 0xB3, 0xDA, 0x5A, 0x1A, 0xF6, 0xB3, 0x78, 0x30, 0xAB, 0x1D, 0x33, 0x33, 0xE7, 0xE3,
  83. 0x5B, 0xBB, 0xF9, 0xFE, 0xD0, 0xC1, 0xF7, 0x90, 0x34, 0x69, 0xB7, 0xE7, 0xC6, 0x1C, 0x46,
  84. 0x85, 0x48,
  85. ];
  86. let iv = [
  87. 0xEC, 0x19, 0x59, 0x3A, 0x1D, 0x1E, 0x4A, 0x58, 0x66, 0xC1, 0xD1, 0x9A, 0x61, 0x6E, 0xBA,
  88. 0x16,
  89. ];
  90. SymKey::Aes256Cbc { key, iv }
  91. };
  92. lazy_static! {
  93. pub static ref ROOT_CREDS: ConcreteCreds =
  94. ConcreteCreds::generate().expect("root cred generation failed");
  95. pub static ref NODE_CREDS: ConcreteCreds =
  96. ConcreteCreds::generate().expect("node cred generation failed");
  97. }
  98. /// Converts the given error to a serde_block_tree error by turning it into a message.
  99. fn convert_err<E: Display>(err: E) -> Error {
  100. Error::Message(err.to_string())
  101. }
  102. pub(crate) fn make_principal() -> Principal {
  103. Principal(Hash::Sha2_256(PRINCIPAL))
  104. }
  105. pub(crate) fn make_path_with_root(root: Principal, rel_components: Vec<&str>) -> BlockPath {
  106. let mut components = Vec::with_capacity(rel_components.len() + 1);
  107. components.push(root.0.to_string());
  108. for component in rel_components {
  109. components.push(component.to_string());
  110. }
  111. BlockPath::new(root, components)
  112. }
  113. pub(crate) fn make_path(rel_components: Vec<&str>) -> BlockPath {
  114. make_path_with_root(make_principal(), rel_components)
  115. }
  116. pub(crate) fn make_writecap_and_creds(rel_components: Vec<&str>) -> (Writecap, impl Creds) {
  117. let (root_writecap, root_key) = make_self_signed_writecap();
  118. let issued_to = Principal(Hash::Sha2_256(PRINCIPAL));
  119. (
  120. make_writecap_trusted_by(root_writecap, &root_key, issued_to, rel_components),
  121. root_key,
  122. )
  123. }
  124. pub(crate) fn make_writecap(rel_components: Vec<&str>) -> Writecap {
  125. let (writecap, ..) = make_writecap_and_creds(rel_components);
  126. writecap
  127. }
  128. pub(crate) fn make_writecap_trusted_by<C: Creds>(
  129. next: Writecap,
  130. trusting_creds: &C,
  131. issued_to: Principal,
  132. path_components: Vec<&str>,
  133. ) -> Writecap {
  134. let hour_hence = Epoch::now() + Duration::from_secs(3600);
  135. let mut writecap = Writecap {
  136. body: WritecapBody {
  137. issued_to,
  138. path: make_path_with_root(next.body.path.root().clone(), path_components),
  139. expires: hour_hence,
  140. signing_key: trusting_creds.public_sign().clone(),
  141. },
  142. signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256),
  143. next: Some(Box::from(next)),
  144. };
  145. trusting_creds
  146. .sign_writecap(&mut writecap)
  147. .map_err(convert_err)
  148. .expect("failed to sign writecap");
  149. writecap
  150. }
  151. pub(crate) fn make_key_pair() -> impl Creds {
  152. ROOT_CREDS.clone()
  153. }
  154. pub(crate) fn make_self_signed_writecap() -> (Writecap, impl Creds) {
  155. let key = make_key_pair();
  156. (make_self_signed_writecap_with(&key), key)
  157. }
  158. pub(crate) fn make_self_signed_writecap_with<C: Creds>(key: &C) -> Writecap {
  159. let root_principal = key.principal();
  160. let hour_hence = Epoch::now() + Duration::from_secs(3600);
  161. let mut writecap = Writecap {
  162. body: WritecapBody {
  163. issued_to: root_principal.clone(),
  164. path: make_path_with_root(root_principal, vec![]),
  165. expires: hour_hence,
  166. signing_key: key.public_sign().clone(),
  167. },
  168. signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256),
  169. next: None,
  170. };
  171. key.sign_writecap(&mut writecap)
  172. .map_err(convert_err)
  173. .expect("failed to sign writecap");
  174. writecap
  175. }
  176. pub(crate) fn make_readcap_for<C: Encrypter + Principaled>(creds: &C) -> Readcap {
  177. Readcap {
  178. issued_to: creds.principal(),
  179. key: creds
  180. .ser_encrypt(&BLOCK_KEY)
  181. .expect("failed to encrypt block key"),
  182. }
  183. }
  184. pub(crate) fn make_block_with(readcap: Readcap) -> Box<dyn Block> {
  185. let mut readcaps = BTreeMap::new();
  186. readcaps.insert(readcap.issued_to, readcap.key);
  187. // Notice that the writecap path contains the block path. If this were not the case, the block
  188. // would be invalid.
  189. let (writecap, creds) = make_writecap_and_creds(vec!["apps"]);
  190. let root_writecap = writecap.next.as_ref().unwrap();
  191. let header = BlockMetaBody {
  192. path: make_path_with_root(root_writecap.body.issued_to.clone(), vec!["apps", "verse"]),
  193. inherit: Some(INHERIT.clone()),
  194. readcaps,
  195. writecap: Some(writecap),
  196. integrity: Some(Hash::Sha2_256([0u8; HashKind::Sha2_256.len()])),
  197. signing_key: creds.public_sign().to_owned(),
  198. };
  199. let sig = Signature::copy_from(Sign::RSA_PSS_3072_SHA_256, &SIGNATURE);
  200. let mut stream =
  201. BlockStream::new(BtCursor::new(Vec::new()), creds).expect("create block stream failed");
  202. stream.meta.body = header;
  203. stream.meta.sig = sig;
  204. let block_key = stream.block_key().expect("get block key failed");
  205. let stream = MerkleStream::new(stream).expect("create merkle stream failed");
  206. let stream = SecretStream::new(block_key)
  207. .try_compose(stream)
  208. .expect("create secret stream failed");
  209. let stream = SectoredBuf::new()
  210. .try_compose(stream)
  211. .expect("create sectored buf failed");
  212. Box::new(stream)
  213. }
  214. /// This function can be run as a test to write a new RSA key pair, as two Rust arrays,
  215. /// out to a file.
  216. #[allow(dead_code)]
  217. fn write_test_keys() -> Result<()> {
  218. write_rsa_keys_to_file("test_keys.rs")
  219. }
  220. struct NamedSlice<'a> {
  221. name: &'a str,
  222. slice: &'a [u8],
  223. }
  224. impl<'a> NamedSlice<'a> {
  225. fn new(name: &'a str, slice: &'a [u8]) -> NamedSlice<'a> {
  226. NamedSlice { name, slice }
  227. }
  228. }
  229. fn write_rsa_keys_to_file(path: &str) -> Result<()> {
  230. use openssl::rsa::Rsa;
  231. let rsa = Rsa::generate(3072).map_err(convert_err)?;
  232. let public_der = rsa.public_key_to_der().map_err(convert_err)?;
  233. let private_der = rsa.private_key_to_der().map_err(convert_err)?;
  234. let slices = [
  235. NamedSlice::new("PUBLIC", public_der.as_slice()),
  236. NamedSlice::new("PRIVATE", private_der.as_slice()),
  237. ];
  238. write_to_file(path, slices.into_iter())
  239. }
  240. fn write_to_file<'a, I: Iterator<Item = NamedSlice<'a>>>(path: &str, slices: I) -> Result<()> {
  241. let path = std::path::Path::new(path);
  242. let mut file = File::create(path).map_err(Error::Io)?;
  243. for NamedSlice { name, slice } in slices {
  244. write_slice(&mut file, name, slice)?;
  245. }
  246. Ok(())
  247. }
  248. fn write_slice<W: Write>(output: &mut W, name: &str, slice: &[u8]) -> Result<()> {
  249. const LINE_LEN: usize = 100;
  250. let mut line = String::with_capacity(LINE_LEN);
  251. write!(line, " ").map_err(Error::Format)?;
  252. writeln!(output, "pub const {}: [u8; {}] = [", name, slice.len()).map_err(Error::Io)?;
  253. for byte in slice {
  254. if line.len() + 6 > LINE_LEN {
  255. writeln!(output, "{}", line).map_err(Error::Io)?;
  256. line.clear();
  257. write!(line, " ").map_err(Error::Format)?;
  258. }
  259. write!(line, "0x{:02X?}, ", byte).map_err(Error::Format)?;
  260. }
  261. writeln!(output, "{}", line).map_err(Error::Io)?;
  262. writeln!(output, "];").map_err(Error::Io)?;
  263. writeln!(output).map_err(Error::Io)?;
  264. Ok(())
  265. }
  266. /// A naive randomizer implementation that is intended only for testing.
  267. pub struct Randomizer {
  268. state: [u8; Self::HASH.len()],
  269. buf: [u8; Self::HASH.len()],
  270. }
  271. impl Randomizer {
  272. pub const HASH: HashKind = HashKind::Sha2_256;
  273. pub fn new(seed: [u8; Self::HASH.len()]) -> Randomizer {
  274. Randomizer {
  275. state: seed,
  276. buf: [0u8; Self::HASH.len()],
  277. }
  278. }
  279. }
  280. impl Iterator for Randomizer {
  281. type Item = usize;
  282. fn next(&mut self) -> Option<Self::Item> {
  283. const BYTES: usize = usize::BITS as usize / 8;
  284. Self::HASH
  285. .digest(&mut self.buf, std::iter::once(self.state.as_slice()))
  286. .expect("digest failed");
  287. self.state.copy_from_slice(&self.buf);
  288. let int_bytes = self.buf.as_slice()[..BYTES]
  289. .try_into()
  290. .expect("failed to convert array");
  291. Some(usize::from_ne_bytes(int_bytes))
  292. }
  293. }
  294. pub fn make_sector(mut buf: &mut [u8], sect_index: usize) {
  295. let data = (sect_index + 1).to_ne_bytes();
  296. for chunk in std::iter::repeat(data).take(buf.len() / data.len()) {
  297. (&mut buf[..chunk.len()]).copy_from_slice(chunk.as_slice());
  298. buf = &mut buf[chunk.len()..];
  299. }
  300. }
  301. pub fn write_fill<W: Write>(mut write: W, sect_sz: usize, sect_ct: usize) {
  302. let mut buf = vec![0u8; sect_sz];
  303. for sect_index in 0..sect_ct {
  304. make_sector(&mut buf, sect_index);
  305. write.write_all(&mut buf).expect("write failed");
  306. }
  307. write.flush().expect("flush failed");
  308. }
  309. pub fn read_check<R: Read>(mut read: R, sect_sz: usize, sect_ct: usize) {
  310. let mut actual = vec![0u8; sect_sz];
  311. let mut expected = vec![0u8; sect_sz];
  312. for sect_index in 0..sect_ct {
  313. make_sector(&mut expected, sect_index);
  314. read.read_exact(&mut actual).expect("read failed");
  315. assert_eq!(expected, actual);
  316. }
  317. }
  318. /// Trait for types which can be referenced as slices and which support conversion from `Vec<u8>`.
  319. pub trait FromVec: AsRef<[u8]> {
  320. fn from_vec(vec: Vec<u8>) -> Self;
  321. }
  322. impl FromVec for Vec<u8> {
  323. fn from_vec(vec: Vec<u8>) -> Self {
  324. vec
  325. }
  326. }
  327. impl<const N: usize> FromVec for [u8; N] {
  328. fn from_vec(vec: Vec<u8>) -> Self {
  329. assert_eq!(N, vec.len());
  330. let mut buf = [0u8; N];
  331. buf.copy_from_slice(&vec);
  332. buf
  333. }
  334. }
  335. /// Module containing functions for serializing and deserializing buffers in `SectoredCursor<T>`.
  336. mod serde_cursor {
  337. use super::FromVec;
  338. use serde::{Deserialize, Deserializer, Serialize, Serializer};
  339. use std::{
  340. cell::RefCell,
  341. io::{Cursor, Read},
  342. result::Result,
  343. };
  344. pub fn serialize<T: AsRef<[u8]>, S: Serializer>(
  345. cursor: &RefCell<Cursor<T>>,
  346. ser: S,
  347. ) -> Result<S::Ok, S::Error> {
  348. let mut cursor = cursor.borrow_mut();
  349. let pos = cursor.position();
  350. cursor.set_position(0);
  351. let mut data = Vec::new();
  352. cursor
  353. .read_to_end(&mut data)
  354. .expect("reading from cursor failed");
  355. cursor.set_position(pos);
  356. data.serialize(ser)
  357. }
  358. pub fn deserialize<'de, T: FromVec, D: Deserializer<'de>>(
  359. de: D,
  360. ) -> Result<RefCell<Cursor<T>>, D::Error> {
  361. let data = Vec::<u8>::deserialize(de)?;
  362. Ok(RefCell::new(Cursor::new(T::from_vec(data))))
  363. }
  364. }
  365. /// A wrapper for `Cursor<T>` which implements additional traits.
  366. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  367. pub struct BtCursor<T: FromVec> {
  368. #[serde(with = "serde_cursor")]
  369. cursor: RefCell<Cursor<T>>,
  370. }
  371. impl<T: FromVec> BtCursor<T> {
  372. pub(crate) fn new(inner: T) -> BtCursor<T> {
  373. BtCursor {
  374. cursor: RefCell::new(Cursor::new(inner)),
  375. }
  376. }
  377. }
  378. impl Write for BtCursor<Vec<u8>> {
  379. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  380. self.cursor.get_mut().write(buf)
  381. }
  382. fn flush(&mut self) -> io::Result<()> {
  383. self.cursor.get_mut().flush()
  384. }
  385. }
  386. impl<const N: usize> Write for BtCursor<[u8; N]> {
  387. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  388. self.cursor.get_mut().write(buf)
  389. }
  390. fn flush(&mut self) -> io::Result<()> {
  391. self.cursor.get_mut().flush()
  392. }
  393. }
  394. impl<T: FromVec> Read for BtCursor<T> {
  395. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  396. self.cursor.get_mut().read(buf)
  397. }
  398. }
  399. impl<T: FromVec> Seek for BtCursor<T> {
  400. fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
  401. self.cursor.get_mut().seek(pos)
  402. }
  403. }
  404. impl WriteInteg for BtCursor<Vec<u8>> {
  405. fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> {
  406. Ok(())
  407. }
  408. }
  409. impl<const N: usize> WriteInteg for BtCursor<[u8; N]> {
  410. fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> {
  411. Ok(())
  412. }
  413. }
  414. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  415. pub struct SectoredCursor<T: FromVec> {
  416. cursor: BtCursor<T>,
  417. sect_sz: usize,
  418. }
  419. impl<T: FromVec> SectoredCursor<T> {
  420. pub fn new(inner: T, sect_sz: usize) -> SectoredCursor<T> {
  421. SectoredCursor {
  422. cursor: BtCursor::new(inner),
  423. sect_sz,
  424. }
  425. }
  426. }
  427. impl<T: FromVec> Sectored for SectoredCursor<T> {
  428. fn sector_sz(&self) -> usize {
  429. self.sect_sz
  430. }
  431. }
  432. impl Write for SectoredCursor<Vec<u8>> {
  433. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  434. self.assert_sector_sz(buf.len())?;
  435. self.cursor.write(buf)
  436. }
  437. fn flush(&mut self) -> io::Result<()> {
  438. self.cursor.flush()
  439. }
  440. }
  441. impl<const N: usize> Write for SectoredCursor<[u8; N]> {
  442. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  443. self.assert_sector_sz(buf.len())?;
  444. self.cursor.write(buf)
  445. }
  446. fn flush(&mut self) -> io::Result<()> {
  447. self.cursor.flush()
  448. }
  449. }
  450. impl<T: FromVec> Read for SectoredCursor<T> {
  451. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  452. self.assert_sector_sz(buf.len())?;
  453. self.cursor.read(buf)
  454. }
  455. }
  456. impl<T: FromVec> Seek for SectoredCursor<T> {
  457. fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
  458. self.cursor.seek(pos)
  459. }
  460. }
  461. trait ExitStatusExt {
  462. fn success_or_err(&self) -> Result<()>;
  463. }
  464. impl ExitStatusExt for ExitStatus {
  465. fn success_or_err(&self) -> btserde::Result<()> {
  466. match self.code() {
  467. Some(0) => Ok(()),
  468. Some(code) => Err(btserde::Error::Message(format!(
  469. "ExitCode was non-zero: {}",
  470. code
  471. ))),
  472. None => Err(btserde::Error::Message("ExitCode was None.".to_string())),
  473. }
  474. }
  475. }
  476. /// A DBus message which is sent when the ownership of a name changes.
  477. struct NameOwnerChanged {
  478. name: String,
  479. old_owner: String,
  480. new_owner: String,
  481. }
  482. impl dbus::arg::AppendAll for NameOwnerChanged {
  483. fn append(&self, iter: &mut dbus::arg::IterAppend) {
  484. dbus::arg::RefArg::append(&self.name, iter);
  485. dbus::arg::RefArg::append(&self.old_owner, iter);
  486. dbus::arg::RefArg::append(&self.new_owner, iter);
  487. }
  488. }
  489. impl dbus::arg::ReadAll for NameOwnerChanged {
  490. fn read(iter: &mut dbus::arg::Iter) -> std::result::Result<Self, dbus::arg::TypeMismatchError> {
  491. Ok(NameOwnerChanged {
  492. name: iter.read()?,
  493. old_owner: iter.read()?,
  494. new_owner: iter.read()?,
  495. })
  496. }
  497. }
  498. impl dbus::message::SignalArgs for NameOwnerChanged {
  499. const NAME: &'static str = "NameOwnerChanged";
  500. const INTERFACE: &'static str = "org.freedesktop.DBus";
  501. }
  502. /// A struct used to block until a specific name appears on DBus.
  503. struct DbusBlocker {
  504. receiver: Receiver<()>,
  505. conn: dbus::blocking::Connection,
  506. }
  507. impl DbusBlocker {
  508. fn new_session(name: String) -> Result<DbusBlocker> {
  509. use dbus::{blocking::Connection, Message};
  510. const DEST: &str = "org.freedesktop.DBus";
  511. let (sender, receiver) = channel();
  512. let conn = Connection::new_session().map_err(Error::custom)?;
  513. let proxy = conn.with_proxy(DEST, "/org/freedesktop/DBus", Duration::from_secs(1));
  514. let _ = proxy.match_signal(move |h: NameOwnerChanged, _: &Connection, _: &Message| {
  515. let name_appeared = h.name == name;
  516. if name_appeared {
  517. if let Err(err) = sender.send(()) {
  518. error!("failed to send unblocking signal: {err}");
  519. }
  520. }
  521. let remove_match = !name_appeared;
  522. remove_match
  523. });
  524. Ok(DbusBlocker { receiver, conn })
  525. }
  526. fn block(&mut self, timeout: Duration) -> Result<()> {
  527. let time_limit = SystemTime::now() + timeout;
  528. loop {
  529. self.conn
  530. .process(Duration::from_millis(100))
  531. .map_err(Error::custom)?;
  532. match self.receiver.try_recv() {
  533. Ok(_) => break,
  534. Err(err) => match err {
  535. TryRecvError::Empty => (),
  536. _ => return Err(Error::custom(err)),
  537. },
  538. }
  539. if SystemTime::now() > time_limit {
  540. return Err(Error::custom("timed out"));
  541. }
  542. }
  543. Ok(())
  544. }
  545. }
  546. pub(crate) struct SwtpmHarness {
  547. dir: TempDir,
  548. port: u16,
  549. state_path: PathBuf,
  550. pid_path: PathBuf,
  551. tabrmd: Child,
  552. }
  553. impl SwtpmHarness {
  554. const HOST: &'static str = "127.0.0.1";
  555. fn dbus_name(port: u16) -> String {
  556. let port_str: String = port
  557. .to_string()
  558. .chars()
  559. // Shifting each code point by 17 makes the digits into capital letters.
  560. .map(|e| ((e as u8) + 17) as char)
  561. .collect();
  562. format!("com.intel.tss2.Tabrmd.{port_str}")
  563. }
  564. pub(crate) fn new() -> crypto::Result<SwtpmHarness> {
  565. static PORT: AtomicU16 = AtomicU16::new(21901);
  566. let port = PORT.fetch_add(2, Ordering::SeqCst);
  567. let ctrl_port = port + 1;
  568. let dir = TempDir::new(format!("swtpm_harness.{port}").as_str())?;
  569. let dir_path = dir.path();
  570. let dir_path_display = dir_path.display();
  571. let conf_path = dir_path.join("swtpm_setup.conf");
  572. let state_path = dir_path.join("state.bt");
  573. let pid_path = dir_path.join("swtpm.pid");
  574. let dbus_name = Self::dbus_name(port);
  575. let addr = Self::HOST;
  576. std::fs::write(
  577. &conf_path,
  578. r#"# Program invoked for creating certificates
  579. #create_certs_tool= /usr/bin/swtpm_localca
  580. # Comma-separated list (no spaces) of PCR banks to activate by default
  581. active_pcr_banks = sha256
  582. "#,
  583. )?;
  584. Command::new("swtpm_setup")
  585. .stdout(Stdio::null())
  586. .args([
  587. "--tpm2",
  588. "--config",
  589. conf_path.to_str().unwrap(),
  590. "--tpm-state",
  591. format!("{dir_path_display}").as_str(),
  592. ])
  593. .status()?
  594. .success_or_err()?;
  595. Command::new("swtpm")
  596. .args([
  597. "socket",
  598. "--daemon",
  599. "--tpm2",
  600. "--server",
  601. format!("type=tcp,port={port},bindaddr={addr}").as_str(),
  602. "--ctrl",
  603. format!("type=tcp,port={ctrl_port},bindaddr={addr}").as_str(),
  604. "--log",
  605. format!("file={dir_path_display}/log.txt,level=5").as_str(),
  606. "--flags",
  607. "not-need-init,startup-clear",
  608. "--tpmstate",
  609. format!("dir={dir_path_display}").as_str(),
  610. "--pid",
  611. format!("file={}", pid_path.display()).as_str(),
  612. ])
  613. .status()?
  614. .success_or_err()?;
  615. let mut blocker = DbusBlocker::new_session(dbus_name.clone())?;
  616. let tabrmd = Command::new("tpm2-abrmd")
  617. .args([
  618. format!("--tcti=swtpm:host=127.0.0.1,port={port}").as_str(),
  619. "--dbus-name",
  620. dbus_name.as_str(),
  621. "--session",
  622. ])
  623. .spawn()?;
  624. blocker.block(Duration::from_secs(5))?;
  625. Ok(SwtpmHarness {
  626. dir,
  627. port,
  628. state_path,
  629. pid_path,
  630. tabrmd,
  631. })
  632. }
  633. pub(crate) fn context(&self) -> crypto::Result<Context> {
  634. let config_string = format!("bus_name={},bus_type=session", Self::dbus_name(self.port));
  635. let config = TabrmdConfig::from_str(config_string.as_str())?;
  636. Ok(Context::new(TctiNameConf::Tabrmd(config))?)
  637. }
  638. pub(crate) fn dir_path(&self) -> &std::path::Path {
  639. self.dir.path()
  640. }
  641. pub(crate) fn state_path(&self) -> &std::path::Path {
  642. &self.state_path
  643. }
  644. }
  645. impl Drop for SwtpmHarness {
  646. fn drop(&mut self) {
  647. if let Err(err) = self.tabrmd.kill() {
  648. error!("failed to kill tpm2-abrmd: {err}");
  649. }
  650. let pid_str = std::fs::read_to_string(&self.pid_path).unwrap();
  651. let pid_int = pid_str.parse::<i32>().unwrap();
  652. let pid = Pid::from_raw(pid_int);
  653. signal::kill(pid, Signal::SIGKILL).unwrap();
  654. }
  655. }