test_helpers.rs 24 KB

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