test_helpers.rs 20 KB

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