tpm.rs 63 KB

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