tpm.rs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. use super::*;
  2. use btserde::read_from;
  3. use log::error;
  4. use openssl::{
  5. bn::{BigNum, BigNumRef},
  6. nid::Nid,
  7. pkcs5::pbkdf2_hmac,
  8. };
  9. use serde::ser;
  10. use std::{
  11. ffi::CStr,
  12. fs::OpenOptions,
  13. io::{BufReader, BufWriter, Read, Write},
  14. mem::size_of,
  15. ops::Deref,
  16. os::{raw::c_char, unix::fs::PermissionsExt},
  17. path::{Path, PathBuf},
  18. sync::{Arc, RwLock, RwLockWriteGuard},
  19. time::Duration,
  20. };
  21. use tss_esapi::{
  22. attributes::{object::ObjectAttributes, SessionAttributesBuilder},
  23. constants::{
  24. response_code::Tss2ResponseCode,
  25. session_type::SessionType,
  26. tss::{TPM2_PERSISTENT_FIRST, TPM2_RH_NULL},
  27. CapabilityType, CommandCode, Tss2ResponseCodeKind,
  28. },
  29. handles::{KeyHandle, ObjectHandle, PersistentTpmHandle, TpmHandle},
  30. interface_types::{
  31. algorithm::HashingAlgorithm,
  32. dynamic_handles::Persistent,
  33. key_bits::RsaKeyBits,
  34. resource_handles::{Hierarchy, Provision},
  35. session_handles::{AuthSession, PolicySession},
  36. },
  37. structures::{
  38. Auth, CapabilityData, Data, Digest, EncryptedSecret, HashScheme, HashcheckTicket, Private,
  39. Public, PublicKeyRsa, PublicRsaParameters, RsaDecryptionScheme, RsaScheme, SignatureScheme,
  40. SymmetricDefinition, SymmetricDefinitionObject, Ticket,
  41. },
  42. tcti_ldr::{TabrmdConfig, TctiNameConf},
  43. traits::{Marshall, UnMarshall},
  44. Context,
  45. };
  46. use tss_esapi_sys::{TPM2_CAP, TPM2_HANDLE, TPM2_MAX_CAP_BUFFER, TPMT_TK_HASHCHECK, TSS2_RC};
  47. use zeroize::Zeroizing;
  48. impl From<tss_esapi::Error> for Error {
  49. fn from(err: tss_esapi::Error) -> Self {
  50. match err {
  51. tss_esapi::Error::WrapperError(err) => Error::custom(err),
  52. tss_esapi::Error::Tss2Error(err) => {
  53. let rc = err.tss2_rc();
  54. let text = tss2_rc_decode(err);
  55. let string = format!("response code: {rc}, response text: {text}");
  56. Error::custom(string)
  57. }
  58. }
  59. }
  60. }
  61. impl<Guard> From<std::sync::PoisonError<Guard>> for Error {
  62. fn from(error: std::sync::PoisonError<Guard>) -> Self {
  63. Error::custom(error.to_string())
  64. }
  65. }
  66. /// Trait which extends the `tss_esapi::Context`.
  67. trait ContextExt {
  68. fn persistent_handles(&mut self) -> Result<Vec<PersistentTpmHandle>>;
  69. /// Returns the first free persistent handle available in the TPM.
  70. fn unused_persistent_primary_key(&mut self) -> Result<Persistent>;
  71. fn persist_key(&mut self, key_handle: KeyHandle) -> Result<TPM2_HANDLE>;
  72. fn evict_key(&mut self, tpm_handle: TPM2_HANDLE, key_handle: Option<KeyHandle>) -> Result<()>;
  73. fn key_handle(&mut self, tpm_handle: TpmHandle) -> Result<KeyHandle>;
  74. fn set_encrypt_decrypt(&mut self, session: AuthSession) -> Result<()>;
  75. fn start_default_auth_session(&mut self) -> Result<AuthSession>;
  76. fn start_policy_session(&mut self, is_trial: IsTrial) -> Result<PolicySession>;
  77. fn dup_with_password_policy(&mut self) -> Result<Digest>;
  78. fn export_key<S: Scheme>(
  79. &mut self,
  80. key_pair: &KeyPair<S>,
  81. new_parent: KeyHandle,
  82. key_auth: Auth,
  83. policy_session: PolicySession,
  84. encryption_key: &AeadKey,
  85. ) -> Result<ExportedKeyPair<S>>;
  86. fn import_key<S: Scheme>(
  87. &mut self,
  88. exported: ExportedKeyPair<S>,
  89. new_parent: KeyHandle,
  90. auth: Auth,
  91. encryption_key: &AeadKey,
  92. ) -> Result<KeyPair<S>>;
  93. fn set_auth(&mut self, cred_data: &CredData, password: &str) -> Result<()>;
  94. }
  95. impl ContextExt for Context {
  96. fn persistent_handles(&mut self) -> Result<Vec<PersistentTpmHandle>> {
  97. let capability = CapabilityType::Handles;
  98. let property = TPM2_PERSISTENT_FIRST;
  99. let max = usize::try_from(TPM2_MAX_CAP_BUFFER).unwrap();
  100. // This calculation was copied from tpm2_getcap.
  101. let count = (max - size_of::<TPM2_CAP>() - size_of::<u32>()) / size_of::<TPM2_HANDLE>();
  102. let property_count = u32::try_from(count).unwrap();
  103. let mut all_handles = Vec::new();
  104. let more = false;
  105. for _ in 0..255 {
  106. let (handles, more) = self.get_capability(capability, property, property_count)?;
  107. let list = match handles {
  108. CapabilityData::Handles(list) => list.into_inner(),
  109. _ => {
  110. return Err(Error::custom(format!(
  111. "Unexpected capability type returned by TPM: {:?}",
  112. handles
  113. )))
  114. }
  115. };
  116. all_handles.reserve(list.len());
  117. for handle in list {
  118. all_handles.push(PersistentTpmHandle::try_from(handle)?);
  119. }
  120. if !more {
  121. break;
  122. }
  123. }
  124. if more {
  125. return Err(Error::custom(
  126. "hit iteration limit before retrieving all persistent handles from the TPM",
  127. ));
  128. }
  129. all_handles.sort_unstable_by_key(|handle| TPM2_HANDLE::from(*handle));
  130. Ok(all_handles)
  131. }
  132. fn unused_persistent_primary_key(&mut self) -> Result<Persistent> {
  133. let mut used_handles = self.persistent_handles()?.into_iter();
  134. // These address regions are defined in Registry of Reserved TPM 2.0 Handles and Localities
  135. // The first regions for both are for primary keys and the second is marked as "Available".
  136. let storage = (0x81_00_00_00..0x81_00_01_00u32).chain(0x81_00_80_00..0x81_01_00_00u32);
  137. let endorsement = (0x81_01_00_00..0x81_01_01_00u32).chain(0x81_01_80_00..0x81_02_00_00u32);
  138. let possible_handles = storage
  139. .chain(endorsement)
  140. .map(|handle| PersistentTpmHandle::new(handle).unwrap());
  141. let mut unused: Option<PersistentTpmHandle> = None;
  142. // We simultaneously iterate over the possible handles and the used handles, breaking when
  143. // we find a handle which is not equal to the current used handle, or when
  144. // there are no more used handles. This works because both `used_handles` and
  145. // `possible_handles` are sorted.
  146. for handle in possible_handles {
  147. let used = match used_handles.next() {
  148. Some(used) => used,
  149. None => {
  150. unused = Some(handle);
  151. break;
  152. }
  153. };
  154. if used != handle {
  155. unused = Some(handle);
  156. break;
  157. }
  158. }
  159. match unused {
  160. Some(unused) => Ok(Persistent::Persistent(unused)),
  161. None => Err(Error::custom("failed to find an unused persistent handle")),
  162. }
  163. }
  164. fn persist_key(&mut self, key_handle: KeyHandle) -> Result<TPM2_HANDLE> {
  165. let mut persistent: Option<Persistent> = None;
  166. for _ in 0..255 {
  167. let handle =
  168. self.execute_with_session(None, |ctx| ctx.unused_persistent_primary_key())?;
  169. match self.evict_control(Provision::Owner, key_handle.into(), handle) {
  170. Ok(_) => {
  171. persistent = Some(handle);
  172. break;
  173. }
  174. Err(error) => {
  175. if let tss_esapi::Error::Tss2Error(rc) = error {
  176. if Some(Tss2ResponseCodeKind::NvDefined) == rc.kind() {
  177. // This type of error occurs if another application used the persistent
  178. // handle we found before we could, so we try again with a different
  179. // handle.
  180. continue;
  181. }
  182. }
  183. return Err(error.into());
  184. }
  185. }
  186. }
  187. match persistent {
  188. Some(Persistent::Persistent(inner)) => Ok(inner.into()),
  189. None => Err(Error::custom("retry limit reached")),
  190. }
  191. }
  192. fn evict_key(&mut self, persistent: TPM2_HANDLE, key_handle: Option<KeyHandle>) -> Result<()> {
  193. let tpm_handle = TpmHandle::try_from(persistent)?;
  194. let key_handle = match key_handle {
  195. Some(key_handle) => key_handle,
  196. None => self.tr_from_tpm_public(tpm_handle)?.into(),
  197. };
  198. let persistent = Persistent::Persistent(tpm_handle.try_into()?);
  199. self.evict_control(Provision::Owner, key_handle.into(), persistent)?;
  200. Ok(())
  201. }
  202. fn set_encrypt_decrypt(&mut self, session: AuthSession) -> Result<()> {
  203. let (attributes, mask) = SessionAttributesBuilder::new()
  204. .with_decrypt(true)
  205. .with_encrypt(true)
  206. .build();
  207. self.tr_sess_set_attributes(session, attributes, mask)?;
  208. Ok(())
  209. }
  210. fn start_default_auth_session(&mut self) -> Result<AuthSession> {
  211. let session = self
  212. .start_auth_session(
  213. None,
  214. None,
  215. None,
  216. SessionType::Hmac,
  217. SymmetricDefinition::AES_256_CFB,
  218. HashingAlgorithm::Sha256,
  219. )?
  220. .ok_or_else(|| Error::custom("empty session handle received from TPM"))?;
  221. self.set_encrypt_decrypt(session)?;
  222. Ok(session)
  223. }
  224. fn start_policy_session(&mut self, is_trial: IsTrial) -> Result<PolicySession> {
  225. let session = self
  226. .start_auth_session(
  227. None,
  228. None,
  229. None,
  230. is_trial.into(),
  231. SymmetricDefinition::AES_256_CFB,
  232. HashingAlgorithm::Sha256,
  233. )?
  234. .ok_or_else(|| Error::custom("empty session handle received from TPM"))?;
  235. self.set_encrypt_decrypt(session)?;
  236. Ok(session.try_into()?)
  237. }
  238. /// Loads the public information from the persistent object stored in the TPM referred to by
  239. /// `tpm_handle` and returns the `KeyHandle` for this object. If the TPM handle refers to an
  240. /// object which is not actually a key, then an error is returned.
  241. fn key_handle(&mut self, tpm_handle: TpmHandle) -> Result<KeyHandle> {
  242. let obj_handle =
  243. self.execute_with_session(None, |ctx| ctx.tr_from_tpm_public(tpm_handle))?;
  244. Ok(obj_handle.into())
  245. }
  246. /// Returns the digest for the policy which allows a key to be duplicated provided that the
  247. /// caller supplies the correct password (authValue) for the key being duplicated.
  248. fn dup_with_password_policy(&mut self) -> Result<Digest> {
  249. let policy_session = self.start_policy_session(IsTrial::True)?;
  250. self.execute_with_session(None, |ctx| {
  251. ctx.policy_password(policy_session)?;
  252. ctx.policy_command_code(policy_session, CommandCode::Duplicate)?;
  253. Ok(ctx.policy_get_digest(policy_session)?)
  254. })
  255. }
  256. fn export_key<S: Scheme>(
  257. &mut self,
  258. key_pair: &KeyPair<S>,
  259. new_parent: KeyHandle,
  260. key_auth: Auth,
  261. policy_session: PolicySession,
  262. encryption_key: &AeadKey,
  263. ) -> Result<ExportedKeyPair<S>> {
  264. let (public, ..) = self.read_public(key_pair.private)?;
  265. let result: Result<()> = self.execute_with_session(None, |ctx| {
  266. ctx.policy_password(policy_session)?;
  267. ctx.policy_command_code(policy_session, CommandCode::Duplicate)?;
  268. Ok(())
  269. });
  270. result?;
  271. let result: Result<(tss_esapi::structures::Private, EncryptedSecret)> = self
  272. .execute_with_session(Some(policy_session.into()), |ctx| {
  273. let obj_handle = ObjectHandle::from(key_pair.private);
  274. ctx.tr_set_auth(obj_handle, key_auth)?;
  275. let (_, private, secret) = ctx.duplicate(
  276. obj_handle,
  277. new_parent.into(),
  278. None,
  279. SymmetricDefinitionObject::Null,
  280. )?;
  281. Ok((private, secret))
  282. });
  283. let (private, secret) = result?;
  284. let tagged_ct =
  285. encryption_key.encrypt(PublicWrapper(public), &TpmBlobs { private, secret })?;
  286. Ok(ExportedKeyPair {
  287. scheme: key_pair.public.scheme,
  288. tagged_ct,
  289. })
  290. }
  291. fn import_key<S: Scheme>(
  292. &mut self,
  293. exported: ExportedKeyPair<S>,
  294. new_parent: KeyHandle,
  295. auth: Auth,
  296. encryption_key: &AeadKey,
  297. ) -> Result<KeyPair<S>> {
  298. let blobs = encryption_key.decrypt(&exported.tagged_ct)?;
  299. let public = exported.tagged_ct.aad;
  300. let private = self.import(
  301. new_parent.into(),
  302. None,
  303. public.clone(),
  304. blobs.private,
  305. blobs.secret,
  306. SymmetricDefinitionObject::Null,
  307. )?;
  308. let key_handle = self.load(new_parent, private, public.clone())?;
  309. self.tr_set_auth(key_handle.into(), auth)?;
  310. let public = AsymKeyPub::try_from(public.0, exported.scheme)?;
  311. Ok(KeyPair {
  312. public,
  313. private: key_handle,
  314. })
  315. }
  316. fn set_auth(&mut self, creds: &CredData, password: &str) -> Result<()> {
  317. let auth = Auth::try_from(password.as_bytes())?;
  318. self.tr_set_auth(creds.sign.private.into(), auth.clone())?;
  319. self.tr_set_auth(creds.enc.private.into(), auth)?;
  320. Ok(())
  321. }
  322. }
  323. enum IsTrial {
  324. True,
  325. False,
  326. }
  327. impl From<IsTrial> for SessionType {
  328. fn from(is_trial: IsTrial) -> Self {
  329. match is_trial {
  330. IsTrial::True => SessionType::Trial,
  331. IsTrial::False => SessionType::Policy,
  332. }
  333. }
  334. }
  335. trait DigestExt {
  336. fn empty() -> Digest;
  337. }
  338. impl DigestExt for Digest {
  339. fn empty() -> Digest {
  340. let empty = [0u8; 0];
  341. Digest::try_from(empty.as_slice()).unwrap()
  342. }
  343. }
  344. /// An authentication cookie which grants access to a node's credentials.
  345. #[derive(Serialize, Deserialize, Clone)]
  346. struct Cookie(#[serde(with = "BigArray")] [u8; Self::LEN]);
  347. impl Cookie {
  348. const LEN: usize = TpmCredStore::SIGN_SCHEME.key_len_const() as usize;
  349. fn random() -> Result<Cookie> {
  350. Ok(Cookie(rand_array()?))
  351. }
  352. fn as_slice(&self) -> &[u8] {
  353. self.0.as_slice()
  354. }
  355. /// Returns the `Auth` value associated with this cookie.
  356. fn auth(&self) -> Auth {
  357. // This shouldn't fail because the given slice is only 64 bytes long.
  358. Auth::try_from(&self.as_slice()[..64]).unwrap()
  359. }
  360. }
  361. #[derive(Serialize, Deserialize)]
  362. struct PublicWrapper(
  363. #[serde(serialize_with = "serialize_marshall")]
  364. #[serde(deserialize_with = "deserialize_unmarshall")]
  365. Public,
  366. );
  367. impl Deref for PublicWrapper {
  368. type Target = Public;
  369. fn deref(&self) -> &Self::Target {
  370. &self.0
  371. }
  372. }
  373. fn serialize_marshall<S: Serializer, T: Marshall>(
  374. value: &T,
  375. ser: S,
  376. ) -> std::result::Result<S::Ok, S::Error> {
  377. let vec = value.marshall().map_err(ser::Error::custom)?;
  378. vec.as_slice().serialize(ser)
  379. }
  380. fn deserialize_unmarshall<'de, D: Deserializer<'de>, T: UnMarshall>(
  381. de: D,
  382. ) -> std::result::Result<T, D::Error> {
  383. let vec: Vec<u8> = Deserialize::deserialize(de)?;
  384. T::unmarshall(&vec).map_err(de::Error::custom)
  385. }
  386. #[derive(Serialize, Deserialize)]
  387. struct TpmBlobs {
  388. #[serde(serialize_with = "serialize_as_vec")]
  389. #[serde(deserialize_with = "deserialize_as_vec")]
  390. private: Private,
  391. #[serde(serialize_with = "serialize_as_vec")]
  392. #[serde(deserialize_with = "deserialize_as_vec")]
  393. secret: EncryptedSecret,
  394. }
  395. fn serialize_as_vec<S: Serializer, T: Deref<Target = Vec<u8>>>(
  396. value: &T,
  397. ser: S,
  398. ) -> std::result::Result<S::Ok, S::Error> {
  399. value.deref().serialize(ser)
  400. }
  401. fn deserialize_as_vec<'de, D: Deserializer<'de>, T: TryFrom<Vec<u8>>>(
  402. de: D,
  403. ) -> std::result::Result<T, D::Error> {
  404. T::try_from(Vec::deserialize(de)?)
  405. .map_err(|_| de::Error::custom("Unable to convert from vector"))
  406. }
  407. #[derive(Serialize, Deserialize)]
  408. pub struct ExportedKeyPair<S> {
  409. scheme: S,
  410. tagged_ct: TaggedCiphertext<TpmBlobs, PublicWrapper>,
  411. }
  412. #[derive(Serialize, Deserialize)]
  413. pub struct ExportedCreds {
  414. sign: ExportedKeyPair<Sign>,
  415. enc: ExportedKeyPair<Encrypt>,
  416. params: DerivationParams,
  417. writecap: Option<Writecap>,
  418. }
  419. /// A public/private key pair in a form which can be serialized and deserialized.
  420. #[derive(Serialize, Clone)]
  421. struct StoredKeyPair<S: Scheme> {
  422. public: AsymKeyPub<S>,
  423. private: TPM2_HANDLE,
  424. }
  425. impl<'de, S: Scheme> Deserialize<'de> for StoredKeyPair<S> {
  426. fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
  427. const FIELDS: &[&str] = &["public", "private", "writecap"];
  428. struct StructVisitor<S: Scheme>(PhantomData<S>);
  429. impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
  430. type Value = StoredKeyPair<S>;
  431. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  432. formatter.write_fmt(format_args!("struct {}", stringify!(StoredKeyPair)))
  433. }
  434. fn visit_seq<A: SeqAccess<'de>>(
  435. self,
  436. mut seq: A,
  437. ) -> std::result::Result<Self::Value, A::Error> {
  438. let public: AsymKeyPub<S> = seq
  439. .next_element()?
  440. .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
  441. let private: TPM2_HANDLE = seq
  442. .next_element()?
  443. .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
  444. let pair = StoredKeyPair { public, private };
  445. Ok(pair)
  446. }
  447. }
  448. d.deserialize_struct(
  449. stringify!(StoredKeyPair),
  450. FIELDS,
  451. StructVisitor(PhantomData),
  452. )
  453. }
  454. }
  455. /// Credentials in a form which can be serialized and deserialized.
  456. #[derive(Serialize, Deserialize, Clone)]
  457. struct StoredCredData {
  458. sign: StoredKeyPair<Sign>,
  459. enc: StoredKeyPair<Encrypt>,
  460. writecap: Option<Writecap>,
  461. }
  462. impl StoredCredData {
  463. fn to_cred_data(&self, context: &mut Context) -> Result<CredData> {
  464. let sign = KeyPair::from_stored(context, &self.sign)?;
  465. let enc = KeyPair::from_stored(context, &self.enc)?;
  466. Ok(CredData {
  467. sign,
  468. enc,
  469. writecap: self.writecap.clone(),
  470. })
  471. }
  472. }
  473. #[derive(Serialize, Deserialize)]
  474. struct Storage {
  475. cookie: Cookie,
  476. node: Option<StoredCredData>,
  477. root: Option<StoredCredData>,
  478. storage_key: Option<StoredKeyPair<Encrypt>>,
  479. }
  480. impl Storage {
  481. fn new(cookie: Cookie) -> Storage {
  482. Storage {
  483. cookie,
  484. node: None,
  485. root: None,
  486. storage_key: None,
  487. }
  488. }
  489. fn save<W: Write>(&self, to: &mut W) -> Result<()> {
  490. Ok(write_to(self, to)?)
  491. }
  492. fn load<R: Read>(from: &mut R) -> Result<Storage> {
  493. Ok(read_from(from)?)
  494. }
  495. fn init<P: AsRef<Path>>(&self, path: P) -> Result<()> {
  496. let file = OpenOptions::new()
  497. .write(true)
  498. .create_new(true)
  499. .open(&path)?;
  500. // Only allow access from the current user.
  501. let metadata = file.metadata()?;
  502. let mut permissions = metadata.permissions();
  503. permissions.set_mode(0o600);
  504. file.set_permissions(permissions)?;
  505. let mut reader = BufWriter::new(file);
  506. self.save(&mut reader)?;
  507. reader.flush()?;
  508. Ok(())
  509. }
  510. fn load_or_init<P: AsRef<Path>>(path: P) -> Result<Storage> {
  511. match OpenOptions::new().read(true).open(&path) {
  512. Ok(file) => {
  513. let mut reader = BufReader::new(file);
  514. Self::load(&mut reader)
  515. }
  516. Err(error) => {
  517. if std::io::ErrorKind::NotFound != error.kind() {
  518. return Err(error.into());
  519. }
  520. let state = Self::new(Cookie::random()?);
  521. state.init(path)?;
  522. Ok(state)
  523. }
  524. }
  525. }
  526. }
  527. impl From<HashKind> for HashingAlgorithm {
  528. fn from(kind: HashKind) -> Self {
  529. match kind {
  530. HashKind::Sha2_256 => HashingAlgorithm::Sha256,
  531. HashKind::Sha2_512 => HashingAlgorithm::Sha512,
  532. }
  533. }
  534. }
  535. impl TryInto<RsaScheme> for SchemeKind {
  536. type Error = Error;
  537. fn try_into(self) -> Result<RsaScheme> {
  538. match self {
  539. SchemeKind::Sign(sign) => match sign {
  540. Sign::RsaSsaPss(inner) => {
  541. Ok(RsaScheme::RsaPss(HashScheme::new(inner.hash_kind.into())))
  542. }
  543. },
  544. SchemeKind::Encrypt(encrypt) => match encrypt {
  545. Encrypt::RsaEsOaep(inner) => {
  546. Ok(RsaScheme::Oaep(HashScheme::new(inner.hash_kind.into())))
  547. }
  548. },
  549. }
  550. }
  551. }
  552. impl TryFrom<KeyLen> for RsaKeyBits {
  553. type Error = Error;
  554. fn try_from(len: KeyLen) -> Result<RsaKeyBits> {
  555. match len {
  556. KeyLen::Bits2048 => Ok(RsaKeyBits::Rsa2048),
  557. KeyLen::Bits3072 => Ok(RsaKeyBits::Rsa3072),
  558. KeyLen::Bits4096 => Ok(RsaKeyBits::Rsa4096),
  559. _ => Err(Error::custom(format!("unsupported key len: {len}"))),
  560. }
  561. }
  562. }
  563. enum Parent {
  564. Seed(Hierarchy),
  565. Key(KeyHandle),
  566. }
  567. struct KeyBuilder<'a, S: Scheme> {
  568. scheme: S,
  569. allow_dup: bool,
  570. unique: &'a [u8],
  571. auth_value: Option<Auth>,
  572. name_hash: HashingAlgorithm,
  573. policy_digest: Digest,
  574. parent: Parent,
  575. restricted: bool,
  576. symmetric: SymmetricDefinitionObject,
  577. rsa_exponent: u32,
  578. }
  579. impl<'a, S: Scheme> KeyBuilder<'a, S> {
  580. fn new(scheme: S, unique: &'a [u8]) -> KeyBuilder<'a, S> {
  581. KeyBuilder {
  582. scheme,
  583. allow_dup: false,
  584. unique,
  585. auth_value: None,
  586. name_hash: HashingAlgorithm::Sha256,
  587. policy_digest: Digest::empty(),
  588. parent: Parent::Seed(Hierarchy::Owner),
  589. restricted: false,
  590. symmetric: SymmetricDefinitionObject::Null,
  591. rsa_exponent: Rsa::EXP,
  592. }
  593. }
  594. fn with_allow_dup(mut self, allow_dup: bool) -> Self {
  595. self.allow_dup = allow_dup;
  596. self
  597. }
  598. fn with_auth(mut self, auth: Auth) -> Self {
  599. self.auth_value = Some(auth);
  600. self
  601. }
  602. fn with_policy_digest(mut self, policy_digest: Digest) -> Self {
  603. self.policy_digest = policy_digest;
  604. self
  605. }
  606. fn with_parent(mut self, parent: Parent) -> Self {
  607. self.parent = parent;
  608. self
  609. }
  610. fn with_restricted(mut self, restricted: bool) -> Self {
  611. self.restricted = restricted;
  612. self
  613. }
  614. fn with_symmetric(mut self, symmetric: SymmetricDefinitionObject) -> Self {
  615. self.symmetric = symmetric;
  616. self
  617. }
  618. fn with_rsa_exponent(mut self, rsa_exponent: u32) -> Self {
  619. self.rsa_exponent = rsa_exponent;
  620. self
  621. }
  622. fn rsa_template(&self) -> Result<Public> {
  623. let scheme_enum = self.scheme.as_enum();
  624. let decrypt = match scheme_enum {
  625. SchemeKind::Sign(_) => false,
  626. SchemeKind::Encrypt(_) => true,
  627. };
  628. let object_attributes = ObjectAttributes::builder()
  629. .with_fixed_tpm(!self.allow_dup)
  630. .with_fixed_parent(!self.allow_dup)
  631. .with_sensitive_data_origin(true)
  632. .with_user_with_auth(true)
  633. .with_decrypt(decrypt)
  634. .with_sign_encrypt(!decrypt)
  635. .with_restricted(self.restricted)
  636. .build()?;
  637. let name_hashing_algorithm = self.name_hash;
  638. let parameters = PublicRsaParameters::new(
  639. self.symmetric,
  640. if self.restricted {
  641. RsaScheme::Null
  642. } else {
  643. scheme_enum.try_into()?
  644. },
  645. self.scheme.key_len().try_into()?,
  646. self.rsa_exponent.try_into()?,
  647. );
  648. let unique = PublicKeyRsa::try_from(self.unique)?;
  649. let public = Public::Rsa {
  650. object_attributes,
  651. name_hashing_algorithm,
  652. auth_policy: self.policy_digest.clone(),
  653. parameters,
  654. unique,
  655. };
  656. Ok(public)
  657. }
  658. fn template(&self) -> Result<Public> {
  659. match self.scheme.as_enum() {
  660. SchemeKind::Encrypt(encrypt) => match encrypt {
  661. Encrypt::RsaEsOaep(_) => self.rsa_template(),
  662. },
  663. SchemeKind::Sign(sign) => match sign {
  664. Sign::RsaSsaPss(_) => self.rsa_template(),
  665. },
  666. }
  667. }
  668. fn build(self, context: &mut Context) -> Result<KeyPair<S>> {
  669. let (public, private) = match self.parent {
  670. Parent::Seed(hierarchy) => {
  671. let result = context.create_primary(
  672. hierarchy,
  673. self.template()?,
  674. self.auth_value,
  675. None,
  676. None,
  677. None,
  678. )?;
  679. (result.out_public, result.key_handle)
  680. }
  681. Parent::Key(parent) => {
  682. let result =
  683. context.create(parent, self.template()?, self.auth_value, None, None, None)?;
  684. let private =
  685. context.load(parent, result.out_private, result.out_public.clone())?;
  686. (result.out_public, private)
  687. }
  688. };
  689. let public = AsymKey::try_from(public, self.scheme)?;
  690. Ok(KeyPair { public, private })
  691. }
  692. }
  693. impl<'a> KeyBuilder<'a, Encrypt> {
  694. fn for_storage_key(scheme: Encrypt, unique: &'a [u8]) -> KeyBuilder<'a, Encrypt> {
  695. KeyBuilder::new(scheme, unique)
  696. .with_allow_dup(false)
  697. .with_restricted(true)
  698. .with_symmetric(SymmetricDefinitionObject::AES_128_CFB)
  699. }
  700. }
  701. /// A public/private key pair.
  702. #[derive(Clone)]
  703. struct KeyPair<S: Scheme> {
  704. public: AsymKeyPub<S>,
  705. /// A rust struct which wraps an `ESYS_TR` from the ESAPI.
  706. private: KeyHandle,
  707. }
  708. impl<S: Scheme> KeyPair<S> {
  709. fn from_stored(context: &mut Context, stored: &StoredKeyPair<S>) -> Result<KeyPair<S>> {
  710. let tpm_handle = TpmHandle::try_from(stored.private)?;
  711. let key_handle = context.key_handle(tpm_handle)?;
  712. Ok(KeyPair {
  713. public: stored.public.clone(),
  714. private: key_handle,
  715. })
  716. }
  717. fn to_stored(&self, private: TPM2_HANDLE) -> StoredKeyPair<S> {
  718. let public = self.public.clone();
  719. StoredKeyPair { public, private }
  720. }
  721. }
  722. /// Credentials which can be used for signing and encrypting.
  723. struct CredData {
  724. sign: KeyPair<Sign>,
  725. enc: KeyPair<Encrypt>,
  726. writecap: Option<Writecap>,
  727. }
  728. struct State {
  729. context: Context,
  730. storage: Storage,
  731. node_creds: Option<TpmCreds>,
  732. storage_key: Option<KeyPair<Encrypt>>,
  733. }
  734. impl State {
  735. fn new(mut context: Context, storage: Storage) -> Result<State> {
  736. let storage_key = match &storage.storage_key {
  737. Some(storage_key) => Some(KeyPair::from_stored(&mut context, storage_key)?),
  738. None => None,
  739. };
  740. Ok(State {
  741. context,
  742. storage,
  743. node_creds: None,
  744. storage_key,
  745. })
  746. }
  747. fn init_node_creds(&mut self, state: &Arc<RwLock<State>>) -> Result<()> {
  748. let tpm_handles = match &self.storage.node {
  749. Some(handles) => handles,
  750. None => return Ok(()),
  751. };
  752. let key_handles = tpm_handles.to_cred_data(&mut self.context)?;
  753. let auth = self.storage.cookie.auth();
  754. self.context
  755. .tr_set_auth(key_handles.enc.private.into(), auth.clone())?;
  756. self.context
  757. .tr_set_auth(key_handles.sign.private.into(), auth)?;
  758. self.node_creds = Some(TpmCreds::new(key_handles, state));
  759. Ok(())
  760. }
  761. }
  762. pub struct TpmCredStore {
  763. state: Arc<RwLock<State>>,
  764. storage_path: PathBuf,
  765. cookie: Cookie,
  766. }
  767. impl TpmCredStore {
  768. const SIGN_SCHEME: Sign = Sign::RSA_PSS_2048_SHA_256;
  769. const ENCRYPT_SCHEME: Encrypt = Encrypt::RSA_OAEP_2048_SHA_256;
  770. const DEFAULT_WRITECAP_EXP: Duration = Duration::from_secs(60 * 60 * 24 * 365 * 10);
  771. pub fn new<P: AsRef<Path>>(mut context: Context, state_path: P) -> Result<TpmCredStore> {
  772. let storage = Storage::load_or_init(state_path.as_ref())?;
  773. let session = context.start_default_auth_session()?;
  774. context.set_sessions((Some(session), None, None));
  775. let cookie = storage.cookie.clone();
  776. let state = Arc::new(RwLock::new(State::new(context, storage)?));
  777. {
  778. let mut guard = state.write()?;
  779. guard.init_node_creds(&state)?;
  780. }
  781. Ok(TpmCredStore {
  782. state,
  783. storage_path: state_path.as_ref().to_owned(),
  784. cookie,
  785. })
  786. }
  787. fn save_storage(&self, guard: &mut RwLockWriteGuard<State>) -> Result<()> {
  788. let file = OpenOptions::new().write(true).open(&self.storage_path)?;
  789. let mut writer = BufWriter::new(file);
  790. guard.storage.save(&mut writer)?;
  791. writer.flush()?;
  792. Ok(())
  793. }
  794. fn persist<F: FnOnce(&mut Storage, StoredCredData)>(
  795. &self,
  796. creds: &TpmCreds,
  797. update_storage: F,
  798. ) -> Result<()> {
  799. let mut guard = self.state.write()?;
  800. let sign_handle = guard.context.persist_key(creds.sign.private)?;
  801. let enc_handle = match guard.context.persist_key(creds.enc.private) {
  802. Ok(handle) => handle,
  803. Err(error) => {
  804. guard
  805. .context
  806. .evict_key(sign_handle, Some(creds.sign.private))?;
  807. return Err(error);
  808. }
  809. };
  810. let handles = StoredCredData {
  811. sign: creds.sign.to_stored(sign_handle),
  812. enc: creds.enc.to_stored(enc_handle),
  813. writecap: creds.writecap.clone(),
  814. };
  815. update_storage(&mut guard.storage, handles);
  816. match self.save_storage(&mut guard) {
  817. Ok(_) => Ok(()),
  818. Err(error) => {
  819. let result = guard
  820. .context
  821. .evict_key(sign_handle, Some(creds.sign.private));
  822. if let Err(error) = result {
  823. error!("failed to evict signing key due to error: {:?}", error)
  824. }
  825. let result = guard.context.evict_key(enc_handle, Some(creds.enc.private));
  826. if let Err(error) = result {
  827. error!("failed to evict encryption key due to error: {:?}", error)
  828. }
  829. Err(error)
  830. }
  831. }
  832. }
  833. fn get_or_init_storage_key(&self) -> Result<KeyPair<Encrypt>> {
  834. {
  835. let guard = self.state.read()?;
  836. if let Some(storage_key) = &guard.storage_key {
  837. // We take this path if the storage key was generated and loaded.
  838. return Ok(storage_key.clone());
  839. }
  840. }
  841. {
  842. let mut guard = self.state.write()?;
  843. if let Some(storage_key) = guard.storage.storage_key.take() {
  844. let result = KeyPair::from_stored(&mut guard.context, &storage_key);
  845. guard.storage.storage_key = Some(storage_key);
  846. // We take this path if the storage key was generated but not loaded.
  847. return result;
  848. }
  849. }
  850. let params = KeyBuilder::for_storage_key(Self::ENCRYPT_SCHEME, self.cookie.as_slice())
  851. .with_parent(Parent::Seed(Hierarchy::Owner))
  852. .with_auth(self.cookie.auth());
  853. let mut guard = self.state.write()?;
  854. let storage_key = params.build(&mut guard.context)?;
  855. guard.storage_key = Some(storage_key.clone());
  856. let tpm_handle = guard.context.persist_key(storage_key.private)?;
  857. guard.storage.storage_key = Some(storage_key.to_stored(tpm_handle));
  858. if let Err(err) = self.save_storage(&mut guard) {
  859. guard.storage_key = None;
  860. guard.storage.storage_key = None;
  861. guard
  862. .context
  863. .evict_key(tpm_handle, Some(storage_key.private))?;
  864. return Err(err);
  865. }
  866. Ok(storage_key)
  867. }
  868. fn gen_key<S: Scheme>(&self, params: KeyBuilder<S>) -> Result<KeyPair<S>> {
  869. let mut guard = self.state.write()?;
  870. params.build(&mut guard.context)
  871. }
  872. fn gen_node_sign_key(&self) -> Result<KeyPair<Sign>> {
  873. let params = KeyBuilder::new(Self::SIGN_SCHEME, self.cookie.as_slice())
  874. .with_parent(Parent::Seed(Hierarchy::Owner))
  875. .with_allow_dup(false)
  876. .with_auth(self.cookie.auth());
  877. self.gen_key(params)
  878. }
  879. fn gen_node_enc_key(&self) -> Result<KeyPair<Encrypt>> {
  880. let params = KeyBuilder::new(Self::ENCRYPT_SCHEME, self.cookie.as_slice())
  881. .with_parent(Parent::Seed(Hierarchy::Owner))
  882. .with_allow_dup(false)
  883. .with_auth(self.cookie.auth());
  884. self.gen_key(params)
  885. }
  886. fn gen_node_creds(&self) -> Result<TpmCreds> {
  887. let sign = self.gen_node_sign_key()?;
  888. let enc = self.gen_node_enc_key()?;
  889. let cred_data = CredData {
  890. sign,
  891. enc,
  892. writecap: None,
  893. };
  894. let creds = TpmCreds::new(cred_data, &self.state);
  895. self.persist(&creds, |storage, handles| storage.node = Some(handles))?;
  896. Ok(creds)
  897. }
  898. fn gen_root_sign_key(&self, password: &str, policy: Digest) -> Result<KeyPair<Sign>> {
  899. let scheme = Self::SIGN_SCHEME;
  900. let unique = rand_vec(scheme.key_len() as usize)?;
  901. let storage_key = self.get_or_init_storage_key()?;
  902. let params = KeyBuilder::new(scheme, unique.as_slice())
  903. .with_parent(Parent::Key(storage_key.private))
  904. .with_allow_dup(true)
  905. .with_auth(password.as_bytes().try_into()?)
  906. .with_policy_digest(policy);
  907. self.gen_key(params)
  908. }
  909. fn gen_root_enc_key(&self, password: &str, policy: Digest) -> Result<KeyPair<Encrypt>> {
  910. let scheme = Self::ENCRYPT_SCHEME;
  911. let unique = rand_vec(scheme.key_len() as usize)?;
  912. let storage_key = self.get_or_init_storage_key()?;
  913. let params = KeyBuilder::new(scheme, unique.as_slice())
  914. .with_parent(Parent::Key(storage_key.private))
  915. .with_allow_dup(true)
  916. .with_auth(password.as_bytes().try_into()?)
  917. .with_policy_digest(policy);
  918. self.gen_key(params)
  919. }
  920. }
  921. #[derive(Serialize, Deserialize)]
  922. struct DerivationParams {
  923. iter: usize,
  924. hash: HashKind,
  925. kind: AeadKeyKind,
  926. salt: Vec<u8>,
  927. iv: Vec<u8>,
  928. }
  929. impl DerivationParams {
  930. const PBKDF2_ITER: usize = 1000000;
  931. const PBKDF2_HASH: HashKind = HashKind::Sha2_256;
  932. const EXPORT_KEY_KIND: AeadKeyKind = AeadKeyKind::AesGcm256;
  933. fn new() -> Result<DerivationParams> {
  934. const_assert!(
  935. DerivationParams::PBKDF2_HASH.len() == DerivationParams::EXPORT_KEY_KIND.key_len()
  936. );
  937. Ok(DerivationParams {
  938. iter: Self::PBKDF2_ITER,
  939. hash: Self::PBKDF2_HASH,
  940. kind: Self::EXPORT_KEY_KIND,
  941. salt: rand_vec(Self::PBKDF2_HASH.len())?,
  942. iv: rand_vec(Self::EXPORT_KEY_KIND.iv_len())?,
  943. })
  944. }
  945. fn derive_key(&self, password: &str) -> Result<AeadKey> {
  946. let mut key = Zeroizing::new([0u8; Self::EXPORT_KEY_KIND.key_len()]);
  947. pbkdf2_hmac(
  948. password.as_bytes(),
  949. self.salt.as_slice(),
  950. self.iter,
  951. self.hash.into(),
  952. key.as_mut_slice(),
  953. )?;
  954. AeadKey::copy_components(self.kind, key.as_slice(), &self.iv)
  955. }
  956. }
  957. impl CredStore for TpmCredStore {
  958. type CredHandle = TpmCreds;
  959. type ExportedCreds = ExportedCreds;
  960. fn node_creds(&self) -> Result<TpmCreds> {
  961. {
  962. let guard = self.state.read()?;
  963. if let Some(creds) = &guard.node_creds {
  964. return Ok(creds.clone());
  965. }
  966. }
  967. self.gen_node_creds()
  968. }
  969. fn root_creds(&self, password: &str) -> Result<Self::CredHandle> {
  970. let root_handles = {
  971. let guard = self.state.read()?;
  972. guard
  973. .storage
  974. .root
  975. .as_ref()
  976. .ok_or_else(|| Error::custom("root creds have not yet been generated"))?
  977. .clone()
  978. };
  979. let mut guard = self.state.write()?;
  980. let key_handles = root_handles.to_cred_data(&mut guard.context)?;
  981. guard.context.set_auth(&key_handles, password)?;
  982. Ok(TpmCreds::new(key_handles, &self.state))
  983. }
  984. fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle> {
  985. {
  986. let guard = self.state.read()?;
  987. if guard.storage.root.is_some() {
  988. return Err(Error::custom("root creds have already been generated"));
  989. }
  990. }
  991. let policy = {
  992. let mut guard = self.state.write()?;
  993. guard.context.dup_with_password_policy()?
  994. };
  995. let sign = self.gen_root_sign_key(password, policy.clone())?;
  996. let enc = self.gen_root_enc_key(password, policy)?;
  997. let cred_data = CredData {
  998. sign,
  999. enc,
  1000. writecap: None,
  1001. };
  1002. {
  1003. let mut guard = self.state.write()?;
  1004. guard.context.set_auth(&cred_data, password)?;
  1005. }
  1006. let mut creds = TpmCreds::new(cred_data, &self.state);
  1007. creds.init_root_writecap(Epoch::now() + Self::DEFAULT_WRITECAP_EXP)?;
  1008. self.persist(&creds, |storage, handles| storage.root = Some(handles))?;
  1009. Ok(creds)
  1010. }
  1011. fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>> {
  1012. let pair = self.get_or_init_storage_key()?;
  1013. Ok(pair.public)
  1014. }
  1015. fn export_root_creds(
  1016. &self,
  1017. root_creds: &TpmCreds,
  1018. password: &str,
  1019. new_parent: &AsymKeyPub<Encrypt>,
  1020. ) -> Result<ExportedCreds> {
  1021. let params = DerivationParams::new()?;
  1022. let aead_key = params.derive_key(password)?;
  1023. let new_parent = new_parent.storage_key_public()?;
  1024. let mut guard = self.state.write()?;
  1025. if let Some(storage_key) = guard.storage_key.take() {
  1026. // Save memory by flushing the storage key from the TPM's RAM.
  1027. guard.context.flush_context(storage_key.private.into())?;
  1028. }
  1029. let new_parent_handle = guard
  1030. .context
  1031. .load_external_public(new_parent, Hierarchy::Null)?;
  1032. let policy_session = guard.context.start_policy_session(IsTrial::False)?;
  1033. let auth = Auth::try_from(password.as_bytes())?;
  1034. let sign = guard.context.export_key(
  1035. &root_creds.sign,
  1036. new_parent_handle,
  1037. auth.clone(),
  1038. policy_session,
  1039. &aead_key,
  1040. )?;
  1041. let enc = guard.context.export_key(
  1042. &root_creds.enc,
  1043. new_parent_handle,
  1044. auth,
  1045. policy_session,
  1046. &aead_key,
  1047. )?;
  1048. Ok(ExportedCreds {
  1049. sign,
  1050. enc,
  1051. params,
  1052. writecap: root_creds.writecap.clone(),
  1053. })
  1054. }
  1055. fn import_root_creds(&self, password: &str, exported: ExportedCreds) -> Result<TpmCreds> {
  1056. let aead_key = exported.params.derive_key(password)?;
  1057. let auth = Auth::try_from(password.as_bytes())?;
  1058. let storage_key = self.get_or_init_storage_key()?;
  1059. let creds = {
  1060. let mut guard = self.state.write()?;
  1061. let sign = guard.context.import_key(
  1062. exported.sign,
  1063. storage_key.private,
  1064. auth.clone(),
  1065. &aead_key,
  1066. )?;
  1067. let enc =
  1068. guard
  1069. .context
  1070. .import_key(exported.enc, storage_key.private, auth, &aead_key)?;
  1071. let cred_data = CredData {
  1072. sign,
  1073. enc,
  1074. writecap: exported.writecap,
  1075. };
  1076. TpmCreds::new(cred_data, &self.state)
  1077. };
  1078. self.persist(&creds, |storage, handles| storage.root = Some(handles))?;
  1079. Ok(creds)
  1080. }
  1081. }
  1082. impl<S: Scheme> AsymKeyPub<S> {
  1083. fn try_from(public: Public, scheme: S) -> Result<AsymKeyPub<S>> {
  1084. match public {
  1085. Public::Rsa {
  1086. parameters, unique, ..
  1087. } => {
  1088. let exponent_value = parameters.exponent().value();
  1089. let exponent = BigNum::from_u32(exponent_value)?;
  1090. let modulus = BigNum::from_slice(unique.as_slice())?;
  1091. let rsa = OsslRsa::from_public_components(modulus, exponent)?;
  1092. let pkey = PKey::from_rsa(rsa)?.conv_pub();
  1093. Ok(AsymKey { pkey, scheme })
  1094. }
  1095. _ => Err(Error::custom("Unsupported key type returned by TPM")),
  1096. }
  1097. }
  1098. }
  1099. impl AsymKeyPub<Encrypt> {
  1100. fn storage_key_public(&self) -> Result<Public> {
  1101. fn from_rsa(scheme: Encrypt, rsa: openssl::rsa::Rsa<super::Public>) -> Result<Public> {
  1102. let exponent = rsa.e().try_into_u32()?;
  1103. let modulus = rsa.n().to_vec();
  1104. let builder = KeyBuilder::for_storage_key(scheme, &modulus).with_rsa_exponent(exponent);
  1105. builder.rsa_template()
  1106. }
  1107. match self.scheme {
  1108. Encrypt::RsaEsOaep(_) => from_rsa(self.scheme, self.pkey.rsa()?),
  1109. }
  1110. }
  1111. }
  1112. trait NidExt {
  1113. fn sha3_256() -> Nid {
  1114. Nid::from_raw(1097)
  1115. }
  1116. fn sha3_384() -> Nid {
  1117. Nid::from_raw(1098)
  1118. }
  1119. fn sha3_512() -> Nid {
  1120. Nid::from_raw(1099)
  1121. }
  1122. }
  1123. impl NidExt for Nid {}
  1124. trait BigNumRefExt {
  1125. fn try_into_u32(self) -> Result<u32>;
  1126. }
  1127. impl BigNumRefExt for &BigNumRef {
  1128. fn try_into_u32(self) -> Result<u32> {
  1129. let data = self.to_vec();
  1130. if data.len() > 4 {
  1131. return Err(Error::custom(format!("data was too long: {}", data.len())));
  1132. }
  1133. let mut buf = [0u8; 4];
  1134. // Note that BigNum data is stored in big endian format, so padding zeros go at the
  1135. // beginning of the buffer.
  1136. let subslice = &mut buf[4 - data.len()..];
  1137. subslice.copy_from_slice(data.as_slice());
  1138. let int = u32::from_be_bytes(buf);
  1139. Ok(int)
  1140. }
  1141. }
  1142. trait MessageDigestExt {
  1143. fn hash_algo(&self) -> Result<HashingAlgorithm>;
  1144. fn hash_scheme(&self) -> Result<HashScheme> {
  1145. Ok(HashScheme::new(self.hash_algo()?))
  1146. }
  1147. }
  1148. impl MessageDigestExt for MessageDigest {
  1149. fn hash_algo(&self) -> Result<HashingAlgorithm> {
  1150. let nid = self.type_();
  1151. let algo = if Nid::SHA1 == nid {
  1152. HashingAlgorithm::Sha1
  1153. } else if Nid::SHA256 == nid {
  1154. HashingAlgorithm::Sha256
  1155. } else if Nid::SHA384 == nid {
  1156. HashingAlgorithm::Sha384
  1157. } else if Nid::SHA512 == nid {
  1158. HashingAlgorithm::Sha512
  1159. } else if Nid::sha3_256() == nid {
  1160. HashingAlgorithm::Sha3_256
  1161. } else if Nid::sha3_384() == nid {
  1162. HashingAlgorithm::Sha3_384
  1163. } else if Nid::sha3_512() == nid {
  1164. HashingAlgorithm::Sha3_512
  1165. } else {
  1166. return Err(Error::custom(format!(
  1167. "Unsupported hash algorithm with NID: {:?}",
  1168. nid
  1169. )));
  1170. };
  1171. Ok(algo)
  1172. }
  1173. }
  1174. trait HashcheckTicketExt {
  1175. fn null() -> HashcheckTicket;
  1176. }
  1177. impl HashcheckTicketExt for HashcheckTicket {
  1178. /// Returns the NULL Ticket of the hashcheck type, as defined in part 1 of the TPM spec,
  1179. /// clause 4.47.
  1180. fn null() -> HashcheckTicket {
  1181. TPMT_TK_HASHCHECK {
  1182. tag: HashcheckTicket::POSSIBLE_TAGS[0].into(),
  1183. digest: Default::default(),
  1184. hierarchy: TPM2_RH_NULL,
  1185. }
  1186. .try_into()
  1187. .unwrap()
  1188. }
  1189. }
  1190. #[derive(Clone)]
  1191. pub struct TpmCreds {
  1192. state: Arc<RwLock<State>>,
  1193. sign: KeyPair<Sign>,
  1194. enc: KeyPair<Encrypt>,
  1195. writecap: Option<Writecap>,
  1196. }
  1197. impl TpmCreds {
  1198. fn new(key_handles: CredData, state: &Arc<RwLock<State>>) -> TpmCreds {
  1199. TpmCreds {
  1200. sign: key_handles.sign,
  1201. enc: key_handles.enc,
  1202. state: state.clone(),
  1203. writecap: key_handles.writecap,
  1204. }
  1205. }
  1206. fn init_root_writecap(&mut self, expires: Epoch) -> Result<()> {
  1207. let writecap = self.issue_writecap(self.principal(), Vec::new(), expires)?;
  1208. self.writecap = Some(writecap);
  1209. Ok(())
  1210. }
  1211. }
  1212. impl Principaled for TpmCreds {
  1213. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1214. self.sign.public.principal_of_kind(kind)
  1215. }
  1216. }
  1217. impl Verifier for TpmCreds {
  1218. type Op<'v> = OsslVerifyOp<'v>;
  1219. fn init_verify(&self) -> Result<Self::Op<'_>> {
  1220. self.sign.public.init_verify()
  1221. }
  1222. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
  1223. self.sign.public.verify(parts, signature)
  1224. }
  1225. }
  1226. impl Encrypter for TpmCreds {
  1227. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1228. self.enc.public.encrypt(slice)
  1229. }
  1230. }
  1231. impl CredsPub for TpmCreds {
  1232. fn public_sign(&self) -> &AsymKeyPub<Sign> {
  1233. &self.sign.public
  1234. }
  1235. }
  1236. pub struct TpmSignOp<'a> {
  1237. op: VarHashOp,
  1238. creds: &'a TpmCreds,
  1239. }
  1240. impl<'a> Op for TpmSignOp<'a> {
  1241. type Arg = &'a TpmCreds;
  1242. fn init(arg: Self::Arg) -> Result<Self> {
  1243. let op = VarHashOp::init(arg.sign.public.scheme.hash_kind())?;
  1244. Ok(TpmSignOp { op, creds: arg })
  1245. }
  1246. fn update(&mut self, data: &[u8]) -> Result<()> {
  1247. self.op.update(data)
  1248. }
  1249. fn finish_into(self, buf: &mut [u8]) -> Result<usize> {
  1250. let hash = self.op.finish()?;
  1251. let digest = Digest::try_from(hash.as_ref())?;
  1252. let validation = HashcheckTicket::null();
  1253. // Null means the scheme used during key creation will be used.
  1254. let scheme = SignatureScheme::Null;
  1255. let sig = {
  1256. let mut guard = self.creds.state.write()?;
  1257. guard
  1258. .context
  1259. .sign(self.creds.sign.private, digest, scheme, validation)?
  1260. };
  1261. let slice: &[u8] = match &sig {
  1262. tss_esapi::structures::Signature::RsaSsa(inner) => inner.signature(),
  1263. tss_esapi::structures::Signature::RsaPss(inner) => inner.signature(),
  1264. _ => {
  1265. return Err(Error::custom(format!(
  1266. "Unexpected signature type: {:?}",
  1267. sig.algorithm()
  1268. )))
  1269. }
  1270. };
  1271. if buf.len() < slice.len() {
  1272. return Err(Error::IncorrectSize {
  1273. expected: slice.len(),
  1274. actual: buf.len(),
  1275. });
  1276. }
  1277. buf.copy_from_slice(slice);
  1278. Ok(slice.len())
  1279. }
  1280. }
  1281. impl<'a> SignOp for TpmSignOp<'a> {
  1282. fn scheme(&self) -> Sign {
  1283. self.creds.sign.public.scheme
  1284. }
  1285. }
  1286. impl Signer for TpmCreds {
  1287. type Op<'s> = TpmSignOp<'s>;
  1288. fn init_sign(&self) -> Result<Self::Op<'_>> {
  1289. TpmSignOp::init(self)
  1290. }
  1291. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
  1292. let mut op = self.init_sign()?;
  1293. for part in parts {
  1294. op.update(part)?;
  1295. }
  1296. op.finish()
  1297. }
  1298. }
  1299. impl Decrypter for TpmCreds {
  1300. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1301. let cipher_text = PublicKeyRsa::try_from(slice)?;
  1302. // Null means the scheme used during key creation will be used.
  1303. let in_scheme = RsaDecryptionScheme::Null;
  1304. let empty = [0u8; 0];
  1305. let label = Data::try_from(empty.as_slice())?;
  1306. let plain_text = {
  1307. let mut guard = self.state.write()?;
  1308. guard
  1309. .context
  1310. .rsa_decrypt(self.enc.private, cipher_text, in_scheme, label)?
  1311. };
  1312. Ok(Vec::from(plain_text.value()))
  1313. }
  1314. }
  1315. impl CredsPriv for TpmCreds {
  1316. fn writecap(&self) -> Option<&Writecap> {
  1317. self.writecap.as_ref()
  1318. }
  1319. fn set_writecap(&mut self, writecap: Writecap) {
  1320. self.writecap = Some(writecap)
  1321. }
  1322. }
  1323. impl Creds for TpmCreds {}
  1324. trait TctiNameConfExt {
  1325. fn default() -> TctiNameConf;
  1326. }
  1327. impl TctiNameConfExt for TctiNameConf {
  1328. /// Returns a configuration which specifies that Tabrmd should be connected to using the system
  1329. /// DBus.
  1330. fn default() -> TctiNameConf {
  1331. TctiNameConf::Tabrmd(TabrmdConfig::default())
  1332. }
  1333. }
  1334. #[link(name = "tss2-rc")]
  1335. extern "C" {
  1336. fn Tss2_RC_Decode(rc: TSS2_RC) -> *const c_char;
  1337. }
  1338. /// Interface for types which can be converted to TSS2 response codes.
  1339. trait HasResponseCode {
  1340. /// Returns the TSS2 response code associated with this instance.
  1341. fn tss2_rc(&self) -> TSS2_RC;
  1342. }
  1343. /// Returns the error message associated with the given TSS2 response code.
  1344. fn tss2_rc_decode<E: HasResponseCode>(err: E) -> &'static str {
  1345. let c_str = unsafe {
  1346. let ptr = Tss2_RC_Decode(err.tss2_rc());
  1347. CStr::from_ptr(ptr)
  1348. };
  1349. // We're relying on Tss2_RC_Decode to return valid C strings.
  1350. c_str.to_str().unwrap()
  1351. }
  1352. impl HasResponseCode for Tss2ResponseCode {
  1353. fn tss2_rc(&self) -> TSS2_RC {
  1354. match self {
  1355. Tss2ResponseCode::Success => 0,
  1356. Tss2ResponseCode::FormatZero(code) => code.0,
  1357. Tss2ResponseCode::FormatOne(code) => code.0,
  1358. }
  1359. }
  1360. }
  1361. impl HasResponseCode for TSS2_RC {
  1362. fn tss2_rc(&self) -> TSS2_RC {
  1363. *self
  1364. }
  1365. }
  1366. #[cfg(feature = "testing")]
  1367. #[cfg(test)]
  1368. mod test {
  1369. use crate::test_helpers::{BtCursor, SwtpmHarness};
  1370. use super::*;
  1371. use ctor::ctor;
  1372. use std::{fs::File, io::SeekFrom};
  1373. use tss_esapi::{
  1374. interface_types::ecc::EccCurve,
  1375. structures::{EccPoint, EccScheme, KeyDerivationFunctionScheme, PublicEccParameters},
  1376. };
  1377. #[ctor]
  1378. fn ctor() {
  1379. env_logger::init();
  1380. }
  1381. /// Displays the message associated with a TSS2 return code.
  1382. #[test]
  1383. fn print_error_message() {
  1384. const RC: TSS2_RC = 2461;
  1385. let msg = tss2_rc_decode(RC);
  1386. println!("{}", msg);
  1387. }
  1388. #[test]
  1389. fn create_context() {
  1390. let harness = SwtpmHarness::new().unwrap();
  1391. harness.context().unwrap().self_test(true).unwrap();
  1392. }
  1393. #[test]
  1394. fn create_primary_key() {
  1395. let harness = SwtpmHarness::new().unwrap();
  1396. let mut context = harness.context().unwrap();
  1397. let public = {
  1398. let object_attributes = ObjectAttributes::builder()
  1399. .with_fixed_tpm(true)
  1400. .with_fixed_parent(true)
  1401. .with_sensitive_data_origin(true)
  1402. .with_user_with_auth(true)
  1403. .with_decrypt(false)
  1404. .with_sign_encrypt(true)
  1405. .with_restricted(false)
  1406. .build()
  1407. .expect("ObjectAttributesBuilder failed");
  1408. let name_hashing_algorithm = HashingAlgorithm::Sha256;
  1409. let empty = [0u8; 0];
  1410. let auth_policy = Digest::try_from(empty.as_slice()).unwrap();
  1411. let parameters = PublicEccParameters::new(
  1412. SymmetricDefinitionObject::Null,
  1413. EccScheme::EcDsa(HashScheme::new(HashingAlgorithm::Sha256)),
  1414. EccCurve::NistP256,
  1415. KeyDerivationFunctionScheme::Null,
  1416. );
  1417. Public::Ecc {
  1418. object_attributes,
  1419. name_hashing_algorithm,
  1420. auth_policy,
  1421. parameters,
  1422. unique: EccPoint::default(),
  1423. }
  1424. };
  1425. let session = context
  1426. .start_auth_session(
  1427. None,
  1428. None,
  1429. None,
  1430. SessionType::Hmac,
  1431. SymmetricDefinition::AES_256_CFB,
  1432. HashingAlgorithm::Sha256,
  1433. )
  1434. .expect("Failed to create session")
  1435. .expect("Received invalid handle");
  1436. context.execute_with_session(Some(session), |ctx| {
  1437. let primary = ctx
  1438. .create_primary(Hierarchy::Null, public, None, None, None, None)
  1439. .expect("create_primary failed")
  1440. .key_handle;
  1441. ctx.flush_context(primary.into())
  1442. .expect("flush_context failed");
  1443. });
  1444. }
  1445. /// Tests that a TPM Credential Store can be created when a cookie does not already exist.
  1446. #[test]
  1447. fn tpm_cred_store_new() -> Result<()> {
  1448. let harness = SwtpmHarness::new()?;
  1449. let cookie_path = harness.dir_path().join("cookie.bin");
  1450. let store = TpmCredStore::new(harness.context()?, &cookie_path)?;
  1451. let cookie = File::open(&cookie_path)?;
  1452. let metadata = cookie.metadata()?;
  1453. let actual = metadata.permissions().mode();
  1454. // Assert that the cookie can only be read by its owner.
  1455. assert_eq!(0o600, 0o777 & actual);
  1456. drop(store);
  1457. Ok(())
  1458. }
  1459. #[test]
  1460. fn gen_creds() -> Result<()> {
  1461. let harness = SwtpmHarness::new()?;
  1462. let cookie_path = harness.dir_path().join("cookie.bin");
  1463. let store = TpmCredStore::new(harness.context()?, &cookie_path)?;
  1464. store.gen_node_creds()?;
  1465. Ok(())
  1466. }
  1467. /// Displays the numeric identifiers used by the supported hash algorithms.
  1468. //#[test]
  1469. #[allow(dead_code)]
  1470. fn show_nids() {
  1471. fn show_nid(digest: MessageDigest) {
  1472. let nid = digest.type_();
  1473. println!("{}: {:?}", nid.long_name().unwrap(), nid);
  1474. }
  1475. show_nid(MessageDigest::sha1());
  1476. show_nid(MessageDigest::sha256());
  1477. show_nid(MessageDigest::sha384());
  1478. show_nid(MessageDigest::sha512());
  1479. show_nid(MessageDigest::sha3_256());
  1480. show_nid(MessageDigest::sha3_384());
  1481. show_nid(MessageDigest::sha3_512());
  1482. }
  1483. /// Verifies that the NIDs returned by the supported hash algorithms are as expected.
  1484. #[test]
  1485. fn verify_expected_nids() {
  1486. fn assert_eq(digest: MessageDigest, nid: Nid) {
  1487. assert_eq!(digest.type_(), nid);
  1488. }
  1489. assert_eq(MessageDigest::sha1(), Nid::SHA1);
  1490. assert_eq(MessageDigest::sha256(), Nid::SHA256);
  1491. assert_eq(MessageDigest::sha384(), Nid::SHA384);
  1492. assert_eq(MessageDigest::sha512(), Nid::SHA512);
  1493. assert_eq(MessageDigest::sha3_256(), Nid::sha3_256());
  1494. assert_eq(MessageDigest::sha3_384(), Nid::sha3_384());
  1495. assert_eq(MessageDigest::sha3_512(), Nid::sha3_512());
  1496. }
  1497. /// Returns a SwtpmHarness and a TpmCredStore that uses it. Note that the order of the entries
  1498. /// in the returned tuple is significant, as TpmCredStore must be dropped _before_ SwtpmHarness.
  1499. fn test_store() -> Result<(SwtpmHarness, TpmCredStore)> {
  1500. let harness = SwtpmHarness::new()?;
  1501. let store = TpmCredStore::new(harness.context()?, &harness.state_path())?;
  1502. Ok((harness, store))
  1503. }
  1504. fn sign_verify_test(creds: &TpmCreds) -> Result<()> {
  1505. let data: [u8; 1024] = rand_array()?;
  1506. let parts = [data.as_slice()];
  1507. let sig = creds.sign(parts.into_iter())?;
  1508. creds.verify(parts.into_iter(), sig.as_slice())
  1509. }
  1510. #[test]
  1511. fn tpm_sign_verify() -> Result<()> {
  1512. let (_harness, store) = test_store()?;
  1513. let creds = store.gen_node_creds()?;
  1514. sign_verify_test(&creds)
  1515. }
  1516. fn encrypt_decrypt_test(creds: &TpmCreds) -> Result<()> {
  1517. let expected: [u8; Cookie::LEN / 2] = rand_array()?;
  1518. let ct = creds.encrypt(expected.as_slice())?;
  1519. let actual = creds.decrypt(&ct)?;
  1520. if expected.as_slice() == actual {
  1521. Ok(())
  1522. } else {
  1523. Err(Error::custom("decrypted data did not match input"))
  1524. }
  1525. }
  1526. #[test]
  1527. fn tpm_encrypt_decrypt() -> Result<()> {
  1528. let (_harness, store) = test_store()?;
  1529. let creds = store.gen_node_creds()?;
  1530. encrypt_decrypt_test(&creds)
  1531. }
  1532. /// Tests that `HashcheckTicket::null` doesn't panic.
  1533. #[test]
  1534. fn hashcheck_null() {
  1535. HashcheckTicket::null();
  1536. }
  1537. #[test]
  1538. fn persistent_handles() -> Result<()> {
  1539. let harness = SwtpmHarness::new()?;
  1540. let mut context = harness.context()?;
  1541. context.persistent_handles()?;
  1542. Ok(())
  1543. }
  1544. #[test]
  1545. fn first_free_persistent() -> Result<()> {
  1546. let harness = SwtpmHarness::new()?;
  1547. let mut context = harness.context()?;
  1548. context.unused_persistent_primary_key()?;
  1549. Ok(())
  1550. }
  1551. #[test]
  1552. fn persist_key() -> Result<()> {
  1553. let (_harness, store) = test_store()?;
  1554. let cookie = Cookie::random()?;
  1555. let params = KeyBuilder::new(Sign::RSA_PSS_3072_SHA_256, cookie.as_slice());
  1556. let pair = store.gen_key(params)?;
  1557. let mut guard = store.state.write()?;
  1558. guard.context.persist_key(pair.private)?;
  1559. Ok(())
  1560. }
  1561. /// Tests that the same node key is returned by after a cred store is dropped and recreated.
  1562. #[test]
  1563. fn node_key_persisted() -> Result<()> {
  1564. let (harness, store) = test_store()?;
  1565. let expected = {
  1566. let creds = store.node_creds()?;
  1567. creds.principal()
  1568. };
  1569. drop(store);
  1570. let store = TpmCredStore::new(harness.context()?, harness.state_path())?;
  1571. let creds = store.node_creds()?;
  1572. let actual = creds.principal();
  1573. assert_eq!(expected, actual);
  1574. sign_verify_test(&creds)?;
  1575. encrypt_decrypt_test(&creds)?;
  1576. Ok(())
  1577. }
  1578. #[test]
  1579. fn root_key_can_be_used_after_generation() {
  1580. let (_harness, store) = test_store().expect("failed to make test store");
  1581. let creds = store
  1582. .gen_root_creds(&"TimeInvariant")
  1583. .expect("failed to gen root creds");
  1584. let data = [1u8; 32];
  1585. creds
  1586. .sign(std::iter::once(data.as_slice()))
  1587. .expect("sign failed");
  1588. }
  1589. #[test]
  1590. fn root_and_node_keys_generated() {
  1591. let (_harness, store) = test_store().expect("failed to make test store");
  1592. let _root_creds = store
  1593. .gen_root_creds(&"TranslationInvariant")
  1594. .expect("failed to gen root creds");
  1595. let _node_creds = store.node_creds().expect("failed to gen node creds");
  1596. }
  1597. #[test]
  1598. fn verify_root_writecap() {
  1599. let (_harness, store) = test_store().expect("failed to make test store");
  1600. let root_creds = store
  1601. .gen_root_creds(&"TranslationInvariant")
  1602. .expect("failed to gen root creds");
  1603. let writecap = root_creds.writecap().expect("no root writecap was present");
  1604. let path = crate::BlockPath::new(root_creds.principal(), Vec::new());
  1605. writecap
  1606. .assert_valid_for(&path)
  1607. .expect("failed to verify root writecap");
  1608. }
  1609. #[test]
  1610. fn issue_writecap_to_node() {
  1611. let (_harness, store) = test_store().expect("failed to make test store");
  1612. let root_creds = store
  1613. .gen_root_creds(&"TranslationInvariant")
  1614. .expect("failed to gen root creds");
  1615. let path = crate::BlockPath::new(
  1616. root_creds.principal(),
  1617. vec!["apps".to_string(), "comms".to_string()],
  1618. );
  1619. let node_creds = store.node_creds().expect("failed to gen node creds");
  1620. let writecap = root_creds
  1621. .issue_writecap(
  1622. node_creds.principal(),
  1623. path.components().map(|e| e.to_string()).collect(),
  1624. Epoch::now() + Duration::from_secs(3600),
  1625. )
  1626. .expect("failed to issue writecap");
  1627. writecap
  1628. .assert_valid_for(&path)
  1629. .expect("failed to verify writecap");
  1630. }
  1631. #[test]
  1632. fn root_key_persisted() -> Result<()> {
  1633. const PASSWORD: &str = "Scaramouch";
  1634. let (harness, store) = test_store()?;
  1635. let expected = {
  1636. let creds = store.gen_root_creds(PASSWORD)?;
  1637. creds.principal()
  1638. };
  1639. drop(store);
  1640. let store = TpmCredStore::new(harness.context()?, harness.state_path())?;
  1641. let creds = store.root_creds(PASSWORD)?;
  1642. let actual = creds.principal();
  1643. assert_eq!(expected, actual);
  1644. sign_verify_test(&creds)?;
  1645. encrypt_decrypt_test(&creds)?;
  1646. Ok(())
  1647. }
  1648. #[test]
  1649. fn root_key_unusable_when_password_wrong() -> Result<()> {
  1650. let (harness, store) = test_store()?;
  1651. store.gen_root_creds("Galileo")?;
  1652. drop(store);
  1653. let store = TpmCredStore::new(harness.context()?, harness.state_path())?;
  1654. let creds = store.root_creds("Figaro")?;
  1655. assert!(sign_verify_test(&creds).is_err());
  1656. assert!(encrypt_decrypt_test(&creds).is_err());
  1657. Ok(())
  1658. }
  1659. #[test]
  1660. fn root_key_export_import() {
  1661. const PASSWORD: &str = "Frobinate";
  1662. let (_src_harness, src_store) = test_store().unwrap();
  1663. let src_root_creds = src_store.gen_root_creds(PASSWORD).unwrap();
  1664. let (_dest_harness, dest_store) = test_store().unwrap();
  1665. let dest_storage_key = dest_store.storage_key().unwrap();
  1666. let exported = src_store
  1667. .export_root_creds(&src_root_creds, PASSWORD, &dest_storage_key)
  1668. .unwrap();
  1669. let vec = to_vec(&exported).unwrap();
  1670. let mut slice = vec.as_slice();
  1671. let exported = read_from(&mut slice).unwrap();
  1672. let dest_root_creds = dest_store.import_root_creds(PASSWORD, exported).unwrap();
  1673. let message = rand_vec(TpmCredStore::ENCRYPT_SCHEME.key_len() as usize / 2).unwrap();
  1674. let sig = dest_root_creds
  1675. .sign([message.as_slice()].into_iter())
  1676. .unwrap();
  1677. src_root_creds
  1678. .verify([message.as_slice()].into_iter(), sig.as_slice())
  1679. .unwrap();
  1680. let ct = src_root_creds.encrypt(message.as_slice()).unwrap();
  1681. let pt = dest_root_creds.decrypt(ct.as_slice()).unwrap();
  1682. assert_eq!(message.as_slice(), pt.as_slice());
  1683. }
  1684. /// Tests that a signature computed using a `TpmSignOp` can be verified.
  1685. #[test]
  1686. fn sign_write_can_be_verified() {
  1687. const LEN: usize = 512;
  1688. let cursor = BtCursor::new([0u8; LEN]);
  1689. let (_harness, store) = test_store().unwrap();
  1690. let creds = store.gen_node_creds().expect("gen_node_creds failed");
  1691. let sign_op = creds.init_sign().expect("init_sign failed");
  1692. let mut sign_wrap = SignWrite::new(cursor, sign_op);
  1693. let part_values = (1..9u8).map(|k| [k; LEN / 8]).collect::<Vec<_>>();
  1694. let get_parts = || part_values.iter().map(|arr| arr.as_slice());
  1695. for part in get_parts() {
  1696. sign_wrap.write(part).expect("write failed");
  1697. }
  1698. let (sig, ..) = sign_wrap.finish().expect("finish failed");
  1699. creds
  1700. .verify(get_parts(), sig.as_ref())
  1701. .expect("verify failed");
  1702. }
  1703. /// Tests that data written into a `SignWrite` using a `TpmSignOp` and later read from a
  1704. /// `VerifyRead` using a `OsslVerifyOp` can be successfully verified.
  1705. #[test]
  1706. fn sign_write_then_verify_read() {
  1707. use std::io::Seek;
  1708. const LEN: usize = 512;
  1709. let cursor = BtCursor::new([0u8; LEN]);
  1710. let (_harness, store) = test_store().unwrap();
  1711. let creds = store.gen_node_creds().expect("gen_node_creds failed");
  1712. let sign_op = creds.init_sign().expect("init_sign failed");
  1713. let mut sign_wrap = SignWrite::new(cursor, sign_op);
  1714. for part in (1..9u8).map(|k| [k; LEN / 8]) {
  1715. sign_wrap.write(part.as_slice()).expect("write failed");
  1716. }
  1717. let (sig, mut cursor) = sign_wrap.finish().expect("finish failed");
  1718. cursor.seek(SeekFrom::Start(0)).expect("seek failed");
  1719. let verify_op = creds.init_verify().expect("init_verify failed");
  1720. let mut verify_read = VerifyRead::new(cursor, verify_op);
  1721. let mut buf = Vec::with_capacity(LEN);
  1722. verify_read
  1723. .read_to_end(&mut buf)
  1724. .expect("read_to_end failed");
  1725. verify_read
  1726. .finish(sig.as_ref())
  1727. .expect("failed to verify signature");
  1728. }
  1729. /// This test is broken for unknown reasons. It passes if no inner encryption key is supplied.
  1730. /// To work-around this issue I've chosen to wrap the data returned by `duplicate` with a
  1731. /// symmetric key in software.
  1732. //#[test]
  1733. #[allow(dead_code)]
  1734. fn key_export_import() -> Result<()> {
  1735. let auth = Auth::try_from(vec![0u8; 32])?;
  1736. let src_harness = SwtpmHarness::new()?;
  1737. let mut src_ctx = src_harness.context()?;
  1738. {
  1739. let session = src_ctx.start_default_auth_session()?;
  1740. src_ctx.set_sessions((Some(session), None, None));
  1741. }
  1742. let src_storage = {
  1743. let unique = [0u8; 0];
  1744. KeyBuilder::for_storage_key(Encrypt::RSA_OAEP_2048_SHA_256, unique.as_slice())
  1745. .with_parent(Parent::Seed(Hierarchy::Owner))
  1746. .with_auth(auth.clone())
  1747. .build(&mut src_ctx)?
  1748. .private
  1749. };
  1750. let dest_harness = SwtpmHarness::new()?;
  1751. let mut dest_ctx = dest_harness.context()?;
  1752. {
  1753. let session = dest_ctx.start_default_auth_session()?;
  1754. dest_ctx.set_sessions((Some(session), None, None));
  1755. }
  1756. let dest_storage = {
  1757. let unique = [0u8; 0];
  1758. KeyBuilder::for_storage_key(Encrypt::RSA_OAEP_2048_SHA_256, unique.as_slice())
  1759. .with_parent(Parent::Seed(Hierarchy::Owner))
  1760. .with_auth(auth.clone())
  1761. .build(&mut dest_ctx)?
  1762. .private
  1763. };
  1764. let key_handle = {
  1765. let policy = src_ctx.dup_with_password_policy()?;
  1766. let unique = rand_array::<256>()?;
  1767. KeyBuilder::new(Sign::RSA_PSS_2048_SHA_256, unique.as_slice())
  1768. .with_parent(Parent::Key(src_storage))
  1769. .with_allow_dup(true)
  1770. .with_policy_digest(policy)
  1771. .build(&mut src_ctx)?
  1772. .private
  1773. };
  1774. let new_parent = {
  1775. let (public, ..) = dest_ctx.read_public(dest_storage)?;
  1776. src_ctx.load_external_public(public, Hierarchy::Owner)?
  1777. };
  1778. let (public, ..) = src_ctx.read_public(key_handle)?;
  1779. let encryption_key = Data::try_from(vec![7u8; 16])?;
  1780. let (_, private, secret) = {
  1781. let session = src_ctx.start_policy_session(IsTrial::False)?;
  1782. let result: Result<()> = src_ctx.execute_with_session(None, |ctx| {
  1783. ctx.policy_password(session)?;
  1784. ctx.policy_command_code(session, CommandCode::Duplicate)?;
  1785. Ok(())
  1786. });
  1787. result?;
  1788. src_ctx
  1789. .execute_with_session(Some(session.into()), |ctx| {
  1790. ctx.duplicate(
  1791. key_handle.into(),
  1792. new_parent.into(),
  1793. Some(encryption_key.clone()),
  1794. SymmetricDefinitionObject::AES_128_CFB,
  1795. )
  1796. })
  1797. .unwrap()
  1798. };
  1799. dest_ctx
  1800. .import(
  1801. dest_storage.into(),
  1802. Some(encryption_key),
  1803. public,
  1804. private,
  1805. secret,
  1806. SymmetricDefinitionObject::AES_128_CFB,
  1807. )
  1808. .unwrap();
  1809. Ok(())
  1810. }
  1811. }