tpm.rs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  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: {}, response text: {}", rc, 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<'v>(&'v self) -> Result<Self::Op<'v>> {
  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 { expected: slice.len(), actual: buf.len() });
  1273. }
  1274. buf.copy_from_slice(slice);
  1275. Ok(slice.len())
  1276. }
  1277. }
  1278. impl<'a> SignOp for TpmSignOp<'a> {
  1279. fn scheme(&self) -> Sign {
  1280. self.creds.sign.public.scheme
  1281. }
  1282. }
  1283. impl Signer for TpmCreds {
  1284. type Op<'s> = TpmSignOp<'s>;
  1285. fn init_sign<'s>(&'s self) -> Result<Self::Op<'s>> {
  1286. TpmSignOp::init(self)
  1287. }
  1288. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
  1289. let mut op = self.init_sign()?;
  1290. for part in parts {
  1291. op.update(part)?;
  1292. }
  1293. op.finish()
  1294. }
  1295. }
  1296. impl Decrypter for TpmCreds {
  1297. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1298. let cipher_text = PublicKeyRsa::try_from(slice)?;
  1299. // Null means the scheme used during key creation will be used.
  1300. let in_scheme = RsaDecryptionScheme::Null;
  1301. let empty = [0u8; 0];
  1302. let label = Data::try_from(empty.as_slice())?;
  1303. let plain_text = {
  1304. let mut guard = self.state.write()?;
  1305. guard
  1306. .context
  1307. .rsa_decrypt(self.enc.private, cipher_text, in_scheme, label)?
  1308. };
  1309. Ok(Vec::from(plain_text.value()))
  1310. }
  1311. }
  1312. impl CredsPriv for TpmCreds {
  1313. fn writecap(&self) -> Option<&Writecap> {
  1314. self.writecap.as_ref()
  1315. }
  1316. fn set_writecap(&mut self, writecap: Writecap) {
  1317. self.writecap = Some(writecap)
  1318. }
  1319. }
  1320. impl Creds for TpmCreds {}
  1321. trait TctiNameConfExt {
  1322. fn default() -> TctiNameConf;
  1323. }
  1324. impl TctiNameConfExt for TctiNameConf {
  1325. /// Returns a configuration which specifies that Tabrmd should be connected to using the system
  1326. /// DBus.
  1327. fn default() -> TctiNameConf {
  1328. TctiNameConf::Tabrmd(TabrmdConfig::default())
  1329. }
  1330. }
  1331. #[link(name = "tss2-rc")]
  1332. extern "C" {
  1333. fn Tss2_RC_Decode(rc: TSS2_RC) -> *const c_char;
  1334. }
  1335. /// Interface for types which can be converted to TSS2 response codes.
  1336. trait HasResponseCode {
  1337. /// Returns the TSS2 response code associated with this instance.
  1338. fn tss2_rc(&self) -> TSS2_RC;
  1339. }
  1340. /// Returns the error message associated with the given TSS2 response code.
  1341. fn tss2_rc_decode<E: HasResponseCode>(err: E) -> &'static str {
  1342. let c_str = unsafe {
  1343. let ptr = Tss2_RC_Decode(err.tss2_rc());
  1344. CStr::from_ptr(ptr)
  1345. };
  1346. // We're relying on Tss2_RC_Decode to return valid C strings.
  1347. c_str.to_str().unwrap()
  1348. }
  1349. impl HasResponseCode for Tss2ResponseCode {
  1350. fn tss2_rc(&self) -> TSS2_RC {
  1351. match self {
  1352. Tss2ResponseCode::Success => 0,
  1353. Tss2ResponseCode::FormatZero(code) => code.0,
  1354. Tss2ResponseCode::FormatOne(code) => code.0,
  1355. }
  1356. }
  1357. }
  1358. impl HasResponseCode for TSS2_RC {
  1359. fn tss2_rc(&self) -> TSS2_RC {
  1360. *self
  1361. }
  1362. }
  1363. #[cfg(test)]
  1364. mod test {
  1365. use crate::test_helpers::{BtCursor, SwtpmHarness};
  1366. use super::*;
  1367. use ctor::ctor;
  1368. use std::{fs::File, io::SeekFrom};
  1369. use tss_esapi::{
  1370. interface_types::ecc::EccCurve,
  1371. structures::{EccPoint, EccScheme, KeyDerivationFunctionScheme, PublicEccParameters},
  1372. };
  1373. #[ctor]
  1374. fn ctor() {
  1375. env_logger::init();
  1376. }
  1377. /// Displays the message associated with a TSS2 return code.
  1378. #[test]
  1379. fn print_error_message() {
  1380. const RC: TSS2_RC = 2461;
  1381. let msg = tss2_rc_decode(RC);
  1382. println!("{}", msg);
  1383. }
  1384. #[test]
  1385. fn create_context() {
  1386. let harness = SwtpmHarness::new().unwrap();
  1387. harness.context().unwrap().self_test(true).unwrap();
  1388. }
  1389. #[test]
  1390. fn create_primary_key() {
  1391. let harness = SwtpmHarness::new().unwrap();
  1392. let mut context = harness.context().unwrap();
  1393. let public = {
  1394. let object_attributes = ObjectAttributes::builder()
  1395. .with_fixed_tpm(true)
  1396. .with_fixed_parent(true)
  1397. .with_sensitive_data_origin(true)
  1398. .with_user_with_auth(true)
  1399. .with_decrypt(false)
  1400. .with_sign_encrypt(true)
  1401. .with_restricted(false)
  1402. .build()
  1403. .expect("ObjectAttributesBuilder failed");
  1404. let name_hashing_algorithm = HashingAlgorithm::Sha256;
  1405. let empty = [0u8; 0];
  1406. let auth_policy = Digest::try_from(empty.as_slice()).unwrap();
  1407. let parameters = PublicEccParameters::new(
  1408. SymmetricDefinitionObject::Null,
  1409. EccScheme::EcDsa(HashScheme::new(HashingAlgorithm::Sha256)),
  1410. EccCurve::NistP256,
  1411. KeyDerivationFunctionScheme::Null,
  1412. );
  1413. Public::Ecc {
  1414. object_attributes,
  1415. name_hashing_algorithm,
  1416. auth_policy,
  1417. parameters,
  1418. unique: EccPoint::default(),
  1419. }
  1420. };
  1421. let session = context
  1422. .start_auth_session(
  1423. None,
  1424. None,
  1425. None,
  1426. SessionType::Hmac,
  1427. SymmetricDefinition::AES_256_CFB,
  1428. HashingAlgorithm::Sha256,
  1429. )
  1430. .expect("Failed to create session")
  1431. .expect("Received invalid handle");
  1432. context.execute_with_session(Some(session), |ctx| {
  1433. let primary = ctx
  1434. .create_primary(Hierarchy::Null, public, None, None, None, None)
  1435. .expect("create_primary failed")
  1436. .key_handle;
  1437. ctx.flush_context(primary.into())
  1438. .expect("flush_context failed");
  1439. });
  1440. }
  1441. /// Tests that a TPM Credential Store can be created when a cookie does not already exist.
  1442. #[test]
  1443. fn tpm_cred_store_new() -> Result<()> {
  1444. let harness = SwtpmHarness::new()?;
  1445. let cookie_path = harness.dir_path().join("cookie.bin");
  1446. let store = TpmCredStore::new(harness.context()?, &cookie_path)?;
  1447. let cookie = File::open(&cookie_path)?;
  1448. let metadata = cookie.metadata()?;
  1449. let actual = metadata.permissions().mode();
  1450. // Assert that the cookie can only be read by its owner.
  1451. assert_eq!(0o600, 0o777 & actual);
  1452. drop(store);
  1453. Ok(())
  1454. }
  1455. #[test]
  1456. fn gen_creds() -> Result<()> {
  1457. let harness = SwtpmHarness::new()?;
  1458. let cookie_path = harness.dir_path().join("cookie.bin");
  1459. let store = TpmCredStore::new(harness.context()?, &cookie_path)?;
  1460. store.gen_node_creds()?;
  1461. Ok(())
  1462. }
  1463. /// Displays the numeric identifiers used by the supported hash algorithms.
  1464. //#[test]
  1465. #[allow(dead_code)]
  1466. fn show_nids() {
  1467. fn show_nid(digest: MessageDigest) {
  1468. let nid = digest.type_();
  1469. println!("{}: {:?}", nid.long_name().unwrap(), nid);
  1470. }
  1471. show_nid(MessageDigest::sha1());
  1472. show_nid(MessageDigest::sha256());
  1473. show_nid(MessageDigest::sha384());
  1474. show_nid(MessageDigest::sha512());
  1475. show_nid(MessageDigest::sha3_256());
  1476. show_nid(MessageDigest::sha3_384());
  1477. show_nid(MessageDigest::sha3_512());
  1478. }
  1479. /// Verifies that the NIDs returned by the supported hash algorithms are as expected.
  1480. #[test]
  1481. fn verify_expected_nids() {
  1482. fn assert_eq(digest: MessageDigest, nid: Nid) {
  1483. assert_eq!(digest.type_(), nid);
  1484. }
  1485. assert_eq(MessageDigest::sha1(), Nid::SHA1);
  1486. assert_eq(MessageDigest::sha256(), Nid::SHA256);
  1487. assert_eq(MessageDigest::sha384(), Nid::SHA384);
  1488. assert_eq(MessageDigest::sha512(), Nid::SHA512);
  1489. assert_eq(MessageDigest::sha3_256(), Nid::sha3_256());
  1490. assert_eq(MessageDigest::sha3_384(), Nid::sha3_384());
  1491. assert_eq(MessageDigest::sha3_512(), Nid::sha3_512());
  1492. }
  1493. /// Returns a SwtpmHarness and a TpmCredStore that uses it. Note that the order of the entries
  1494. /// in the returned tuple is significant, as TpmCredStore must be dropped _before_ SwtpmHarness.
  1495. fn test_store() -> Result<(SwtpmHarness, TpmCredStore)> {
  1496. let harness = SwtpmHarness::new()?;
  1497. let store = TpmCredStore::new(harness.context()?, &harness.state_path())?;
  1498. Ok((harness, store))
  1499. }
  1500. fn sign_verify_test(creds: &TpmCreds) -> Result<()> {
  1501. let data: [u8; 1024] = rand_array()?;
  1502. let parts = [data.as_slice()];
  1503. let sig = creds.sign(parts.into_iter())?;
  1504. creds.verify(parts.into_iter(), sig.as_slice())
  1505. }
  1506. #[test]
  1507. fn tpm_sign_verify() -> Result<()> {
  1508. let (_harness, store) = test_store()?;
  1509. let creds = store.gen_node_creds()?;
  1510. sign_verify_test(&creds)
  1511. }
  1512. fn encrypt_decrypt_test(creds: &TpmCreds) -> Result<()> {
  1513. let expected: [u8; Cookie::LEN / 2] = rand_array()?;
  1514. let ct = creds.encrypt(expected.as_slice())?;
  1515. let actual = creds.decrypt(&ct)?;
  1516. if expected.as_slice() == actual {
  1517. Ok(())
  1518. } else {
  1519. Err(Error::custom("decrypted data did not match input"))
  1520. }
  1521. }
  1522. #[test]
  1523. fn tpm_encrypt_decrypt() -> Result<()> {
  1524. let (_harness, store) = test_store()?;
  1525. let creds = store.gen_node_creds()?;
  1526. encrypt_decrypt_test(&creds)
  1527. }
  1528. /// Tests that `HashcheckTicket::null` doesn't panic.
  1529. #[test]
  1530. fn hashcheck_null() {
  1531. HashcheckTicket::null();
  1532. }
  1533. #[test]
  1534. fn persistent_handles() -> Result<()> {
  1535. let harness = SwtpmHarness::new()?;
  1536. let mut context = harness.context()?;
  1537. context.persistent_handles()?;
  1538. Ok(())
  1539. }
  1540. #[test]
  1541. fn first_free_persistent() -> Result<()> {
  1542. let harness = SwtpmHarness::new()?;
  1543. let mut context = harness.context()?;
  1544. context.unused_persistent_primary_key()?;
  1545. Ok(())
  1546. }
  1547. #[test]
  1548. fn persist_key() -> Result<()> {
  1549. let (_harness, store) = test_store()?;
  1550. let cookie = Cookie::random()?;
  1551. let params = KeyBuilder::new(Sign::RSA_PSS_3072_SHA_256, cookie.as_slice());
  1552. let pair = store.gen_key(params)?;
  1553. let mut guard = store.state.write()?;
  1554. guard.context.persist_key(pair.private)?;
  1555. Ok(())
  1556. }
  1557. /// Tests that the same node key is returned by after a cred store is dropped and recreated.
  1558. #[test]
  1559. fn node_key_persisted() -> Result<()> {
  1560. let (harness, store) = test_store()?;
  1561. let expected = {
  1562. let creds = store.node_creds()?;
  1563. creds.principal()
  1564. };
  1565. drop(store);
  1566. let store = TpmCredStore::new(harness.context()?, harness.state_path())?;
  1567. let creds = store.node_creds()?;
  1568. let actual = creds.principal();
  1569. assert_eq!(expected, actual);
  1570. sign_verify_test(&creds)?;
  1571. encrypt_decrypt_test(&creds)?;
  1572. Ok(())
  1573. }
  1574. #[test]
  1575. fn root_key_can_be_used_after_generation() {
  1576. let (_harness, store) = test_store().expect("failed to make test store");
  1577. let creds = store
  1578. .gen_root_creds(&"TimeInvariant")
  1579. .expect("failed to gen root creds");
  1580. let data = [1u8; 32];
  1581. creds
  1582. .sign(std::iter::once(data.as_slice()))
  1583. .expect("sign failed");
  1584. }
  1585. #[test]
  1586. fn root_and_node_keys_generated() {
  1587. let (_harness, store) = test_store().expect("failed to make test store");
  1588. let _root_creds = store
  1589. .gen_root_creds(&"TranslationInvariant")
  1590. .expect("failed to gen root creds");
  1591. let _node_creds = store.node_creds().expect("failed to gen node creds");
  1592. }
  1593. #[test]
  1594. fn verify_root_writecap() {
  1595. let (_harness, store) = test_store().expect("failed to make test store");
  1596. let root_creds = store
  1597. .gen_root_creds(&"TranslationInvariant")
  1598. .expect("failed to gen root creds");
  1599. let writecap = root_creds.writecap().expect("no root writecap was present");
  1600. let path = crate::BlockPath::new(root_creds.principal(), Vec::new());
  1601. writecap
  1602. .assert_valid_for(&path)
  1603. .expect("failed to verify root writecap");
  1604. }
  1605. #[test]
  1606. fn issue_writecap_to_node() {
  1607. let (_harness, store) = test_store().expect("failed to make test store");
  1608. let root_creds = store
  1609. .gen_root_creds(&"TranslationInvariant")
  1610. .expect("failed to gen root creds");
  1611. let path = crate::BlockPath::new(
  1612. root_creds.principal(),
  1613. vec!["apps".to_string(), "comms".to_string()],
  1614. );
  1615. let node_creds = store.node_creds().expect("failed to gen node creds");
  1616. let writecap = root_creds
  1617. .issue_writecap(
  1618. node_creds.principal(),
  1619. path.components().map(|e| e.to_string()).collect(),
  1620. Epoch::now() + Duration::from_secs(3600),
  1621. )
  1622. .expect("failed to issue writecap");
  1623. writecap
  1624. .assert_valid_for(&path)
  1625. .expect("failed to verify writecap");
  1626. }
  1627. #[test]
  1628. fn root_key_persisted() -> Result<()> {
  1629. const PASSWORD: &str = "Scaramouch";
  1630. let (harness, store) = test_store()?;
  1631. let expected = {
  1632. let creds = store.gen_root_creds(PASSWORD)?;
  1633. creds.principal()
  1634. };
  1635. drop(store);
  1636. let store = TpmCredStore::new(harness.context()?, harness.state_path())?;
  1637. let creds = store.root_creds(PASSWORD)?;
  1638. let actual = creds.principal();
  1639. assert_eq!(expected, actual);
  1640. sign_verify_test(&creds)?;
  1641. encrypt_decrypt_test(&creds)?;
  1642. Ok(())
  1643. }
  1644. #[test]
  1645. fn root_key_unusable_when_password_wrong() -> Result<()> {
  1646. let (harness, store) = test_store()?;
  1647. store.gen_root_creds("Galileo")?;
  1648. drop(store);
  1649. let store = TpmCredStore::new(harness.context()?, harness.state_path())?;
  1650. let creds = store.root_creds("Figaro")?;
  1651. assert!(sign_verify_test(&creds).is_err());
  1652. assert!(encrypt_decrypt_test(&creds).is_err());
  1653. Ok(())
  1654. }
  1655. #[test]
  1656. fn root_key_export_import() {
  1657. const PASSWORD: &str = "Frobinate";
  1658. let (_src_harness, src_store) = test_store().unwrap();
  1659. let src_root_creds = src_store.gen_root_creds(PASSWORD).unwrap();
  1660. let (_dest_harness, dest_store) = test_store().unwrap();
  1661. let dest_storage_key = dest_store.storage_key().unwrap();
  1662. let exported = src_store
  1663. .export_root_creds(&src_root_creds, PASSWORD, &dest_storage_key)
  1664. .unwrap();
  1665. let vec = to_vec(&exported).unwrap();
  1666. let mut slice = vec.as_slice();
  1667. let exported = read_from(&mut slice).unwrap();
  1668. let dest_root_creds = dest_store.import_root_creds(PASSWORD, exported).unwrap();
  1669. let message = rand_vec(TpmCredStore::ENCRYPT_SCHEME.key_len() as usize / 2).unwrap();
  1670. let sig = dest_root_creds
  1671. .sign([message.as_slice()].into_iter())
  1672. .unwrap();
  1673. src_root_creds
  1674. .verify([message.as_slice()].into_iter(), sig.as_slice())
  1675. .unwrap();
  1676. let ct = src_root_creds.encrypt(message.as_slice()).unwrap();
  1677. let pt = dest_root_creds.decrypt(ct.as_slice()).unwrap();
  1678. assert_eq!(message.as_slice(), pt.as_slice());
  1679. }
  1680. /// Tests that a signature computed using a `TpmSignOp` can be verified.
  1681. #[test]
  1682. fn sign_write_can_be_verified() {
  1683. const LEN: usize = 512;
  1684. let cursor = BtCursor::new([0u8; LEN]);
  1685. let (_harness, store) = test_store().unwrap();
  1686. let creds = store.gen_node_creds().expect("gen_node_creds failed");
  1687. let sign_op = creds.init_sign().expect("init_sign failed");
  1688. let mut sign_wrap = SignWrite::new(cursor, sign_op);
  1689. let part_values = (1..9u8).map(|k| [k; LEN / 8]).collect::<Vec<_>>();
  1690. let get_parts = || part_values.iter().map(|arr| arr.as_slice());
  1691. for part in get_parts() {
  1692. sign_wrap.write(part).expect("write failed");
  1693. }
  1694. let (sig, ..) = sign_wrap.finish().expect("finish failed");
  1695. creds
  1696. .verify(get_parts(), sig.as_ref())
  1697. .expect("verify failed");
  1698. }
  1699. /// Tests that data written into a `SignWrite` using a `TpmSignOp` and later read from a
  1700. /// `VerifyRead` using a `OsslVerifyOp` can be successfully verified.
  1701. #[test]
  1702. fn sign_write_then_verify_read() {
  1703. use std::io::Seek;
  1704. const LEN: usize = 512;
  1705. let cursor = BtCursor::new([0u8; LEN]);
  1706. let (_harness, store) = test_store().unwrap();
  1707. let creds = store.gen_node_creds().expect("gen_node_creds failed");
  1708. let sign_op = creds.init_sign().expect("init_sign failed");
  1709. let mut sign_wrap = SignWrite::new(cursor, sign_op);
  1710. for part in (1..9u8).map(|k| [k; LEN / 8]) {
  1711. sign_wrap.write(part.as_slice()).expect("write failed");
  1712. }
  1713. let (sig, mut cursor) = sign_wrap.finish().expect("finish failed");
  1714. cursor.seek(SeekFrom::Start(0)).expect("seek failed");
  1715. let verify_op = creds.init_verify().expect("init_verify failed");
  1716. let mut verify_read = VerifyRead::new(cursor, verify_op);
  1717. let mut buf = Vec::with_capacity(LEN);
  1718. verify_read
  1719. .read_to_end(&mut buf)
  1720. .expect("read_to_end failed");
  1721. verify_read
  1722. .finish(sig.as_ref())
  1723. .expect("failed to verify signature");
  1724. }
  1725. /// This test is broken for unknown reasons. It passes if no inner encryption key is supplied.
  1726. /// To work-around this issue I've chosen to wrap the data returned by `duplicate` with a
  1727. /// symmetric key in software.
  1728. //#[test]
  1729. #[allow(dead_code)]
  1730. fn key_export_import() -> Result<()> {
  1731. let auth = Auth::try_from(vec![0u8; 32])?;
  1732. let src_harness = SwtpmHarness::new()?;
  1733. let mut src_ctx = src_harness.context()?;
  1734. {
  1735. let session = src_ctx.start_default_auth_session()?;
  1736. src_ctx.set_sessions((Some(session), None, None));
  1737. }
  1738. let src_storage = {
  1739. let unique = [0u8; 0];
  1740. KeyBuilder::for_storage_key(Encrypt::RSA_OAEP_2048_SHA_256, unique.as_slice())
  1741. .with_parent(Parent::Seed(Hierarchy::Owner))
  1742. .with_auth(auth.clone())
  1743. .build(&mut src_ctx)?
  1744. .private
  1745. };
  1746. let dest_harness = SwtpmHarness::new()?;
  1747. let mut dest_ctx = dest_harness.context()?;
  1748. {
  1749. let session = dest_ctx.start_default_auth_session()?;
  1750. dest_ctx.set_sessions((Some(session), None, None));
  1751. }
  1752. let dest_storage = {
  1753. let unique = [0u8; 0];
  1754. KeyBuilder::for_storage_key(Encrypt::RSA_OAEP_2048_SHA_256, unique.as_slice())
  1755. .with_parent(Parent::Seed(Hierarchy::Owner))
  1756. .with_auth(auth.clone())
  1757. .build(&mut dest_ctx)?
  1758. .private
  1759. };
  1760. let key_handle = {
  1761. let policy = src_ctx.dup_with_password_policy()?;
  1762. let unique = rand_array::<256>()?;
  1763. KeyBuilder::new(Sign::RSA_PSS_2048_SHA_256, unique.as_slice())
  1764. .with_parent(Parent::Key(src_storage))
  1765. .with_allow_dup(true)
  1766. .with_policy_digest(policy)
  1767. .build(&mut src_ctx)?
  1768. .private
  1769. };
  1770. let new_parent = {
  1771. let (public, ..) = dest_ctx.read_public(dest_storage)?;
  1772. src_ctx.load_external_public(public, Hierarchy::Owner)?
  1773. };
  1774. let (public, ..) = src_ctx.read_public(key_handle)?;
  1775. let encryption_key = Data::try_from(vec![7u8; 16])?;
  1776. let (_, private, secret) = {
  1777. let session = src_ctx.start_policy_session(IsTrial::False)?;
  1778. let result: Result<()> = src_ctx.execute_with_session(None, |ctx| {
  1779. ctx.policy_password(session)?;
  1780. ctx.policy_command_code(session, CommandCode::Duplicate)?;
  1781. Ok(())
  1782. });
  1783. result?;
  1784. src_ctx
  1785. .execute_with_session(Some(session.into()), |ctx| {
  1786. ctx.duplicate(
  1787. key_handle.into(),
  1788. new_parent.into(),
  1789. Some(encryption_key.clone()),
  1790. SymmetricDefinitionObject::AES_128_CFB,
  1791. )
  1792. })
  1793. .unwrap()
  1794. };
  1795. dest_ctx
  1796. .import(
  1797. dest_storage.into(),
  1798. Some(encryption_key),
  1799. public,
  1800. private,
  1801. secret,
  1802. SymmetricDefinitionObject::AES_128_CFB,
  1803. )
  1804. .unwrap();
  1805. Ok(())
  1806. }
  1807. }