CryptHash.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /********************************************************************************/
  2. /* */
  3. /* Implementation of cryptographic functions for hashing. */
  4. /* Written by Ken Goldman */
  5. /* IBM Thomas J. Watson Research Center */
  6. /* $Id: CryptHash.c 1658 2021-01-22 23:14:01Z kgoldman $ */
  7. /* */
  8. /* Licenses and Notices */
  9. /* */
  10. /* 1. Copyright Licenses: */
  11. /* */
  12. /* - Trusted Computing Group (TCG) grants to the user of the source code in */
  13. /* this specification (the "Source Code") a worldwide, irrevocable, */
  14. /* nonexclusive, royalty free, copyright license to reproduce, create */
  15. /* derivative works, distribute, display and perform the Source Code and */
  16. /* derivative works thereof, and to grant others the rights granted herein. */
  17. /* */
  18. /* - The TCG grants to the user of the other parts of the specification */
  19. /* (other than the Source Code) the rights to reproduce, distribute, */
  20. /* display, and perform the specification solely for the purpose of */
  21. /* developing products based on such documents. */
  22. /* */
  23. /* 2. Source Code Distribution Conditions: */
  24. /* */
  25. /* - Redistributions of Source Code must retain the above copyright licenses, */
  26. /* this list of conditions and the following disclaimers. */
  27. /* */
  28. /* - Redistributions in binary form must reproduce the above copyright */
  29. /* licenses, this list of conditions and the following disclaimers in the */
  30. /* documentation and/or other materials provided with the distribution. */
  31. /* */
  32. /* 3. Disclaimers: */
  33. /* */
  34. /* - THE COPYRIGHT LICENSES SET FORTH ABOVE DO NOT REPRESENT ANY FORM OF */
  35. /* LICENSE OR WAIVER, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, WITH */
  36. /* RESPECT TO PATENT RIGHTS HELD BY TCG MEMBERS (OR OTHER THIRD PARTIES) */
  37. /* THAT MAY BE NECESSARY TO IMPLEMENT THIS SPECIFICATION OR OTHERWISE. */
  38. /* Contact TCG Administration (admin@trustedcomputinggroup.org) for */
  39. /* information on specification licensing rights available through TCG */
  40. /* membership agreements. */
  41. /* */
  42. /* - THIS SPECIFICATION IS PROVIDED "AS IS" WITH NO EXPRESS OR IMPLIED */
  43. /* WARRANTIES WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY OR */
  44. /* FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, COMPLETENESS, OR */
  45. /* NONINFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS, OR ANY WARRANTY */
  46. /* OTHERWISE ARISING OUT OF ANY PROPOSAL, SPECIFICATION OR SAMPLE. */
  47. /* */
  48. /* - Without limitation, TCG and its members and licensors disclaim all */
  49. /* liability, including liability for infringement of any proprietary */
  50. /* rights, relating to use of information in this specification and to the */
  51. /* implementation of this specification, and TCG disclaims all liability for */
  52. /* cost of procurement of substitute goods or services, lost profits, loss */
  53. /* of use, loss of data or any incidental, consequential, direct, indirect, */
  54. /* or special damages, whether under contract, tort, warranty or otherwise, */
  55. /* arising in any way out of use or reliance upon this specification or any */
  56. /* information herein. */
  57. /* */
  58. /* (c) Copyright IBM Corp. and others, 2016 - 2021 */
  59. /* */
  60. /********************************************************************************/
  61. /* 10.2.13 CryptHash.c */
  62. /* 10.2.13.1 Description */
  63. /* This file contains implementation of cryptographic functions for hashing. */
  64. /* 10.2.13.2 Includes, Defines, and Types */
  65. #define _CRYPT_HASH_C_
  66. #include "Tpm.h"
  67. #include "CryptHash_fp.h"
  68. #include "CryptHash.h"
  69. #include "OIDs.h"
  70. /* Instance each of the hash descriptors based on the implemented algorithms */
  71. FOR_EACH_HASH(HASH_DEF_TEMPLATE)
  72. /* Instance a null def. */
  73. HASH_DEF NULL_Def = {{0}};
  74. /* Create a table of pointers to the defined hash definitions */
  75. #define HASH_DEF_ENTRY(HASH, Hash) &Hash##_Def,
  76. PHASH_DEF HashDefArray[] = {
  77. // for each implemented HASH, expands to: &HASH_Def,
  78. FOR_EACH_HASH(HASH_DEF_ENTRY)
  79. &NULL_Def
  80. };
  81. /* 10.2.13.3 Obligatory Initialization Functions */
  82. /* 10.2.13.3.1 CryptHashInit() */
  83. /* This function is called by _TPM_Init() do perform the initialization operations for the
  84. library. */
  85. BOOL
  86. CryptHashInit(
  87. void
  88. )
  89. {
  90. LibHashInit();
  91. return TRUE;
  92. }
  93. /* 10.2.13.3.2 CryptHashStartup() */
  94. /* This function is called by TPM2_Startup(). It checks that the size of the HashDefArray() is
  95. consistent with the HASH_COUNT. */
  96. BOOL
  97. CryptHashStartup(
  98. void
  99. )
  100. {
  101. int i = sizeof(HashDefArray) / sizeof(PHASH_DEF) - 1;
  102. return (i == HASH_COUNT);
  103. }
  104. /* 10.2.13.4 Hash Information Access Functions */
  105. /* 10.2.13.4.1 Introduction */
  106. /* These functions provide access to the hash algorithm description information. */
  107. /* 10.2.13.4.2 CryptGetHashDef() */
  108. /* This function accesses the hash descriptor associated with a hash a algorithm. The function
  109. returns a pointer to a null descriptor if hashAlg is TPM_ALG_NULL or not a defined algorithm. */
  110. PHASH_DEF
  111. CryptGetHashDef(
  112. TPM_ALG_ID hashAlg
  113. )
  114. {
  115. #define GET_DEF(HASH, Hash) case ALG_##HASH##_VALUE: return &Hash##_Def;
  116. switch(hashAlg)
  117. {
  118. FOR_EACH_HASH(GET_DEF)
  119. default:
  120. return &NULL_Def;
  121. }
  122. #undef GET_DEF
  123. }
  124. /* 10.2.13.4.3 CryptHashIsValidAlg() */
  125. /* This function tests to see if an algorithm ID is a valid hash algorithm. If flag is true, then
  126. TPM_ALG_NULL is a valid hash. */
  127. /* Return Value Meaning */
  128. /* TRUE(1) hashAlg is a valid, implemented hash on this TPM */
  129. /* FALSE(0) hashAlg is not valid for this TPM */
  130. BOOL
  131. CryptHashIsValidAlg(
  132. TPM_ALG_ID hashAlg, // IN: the algorithm to check
  133. BOOL flag // IN: TRUE if TPM_ALG_NULL is to be treated
  134. // as a valid hash
  135. )
  136. {
  137. if(hashAlg == TPM_ALG_NULL)
  138. return flag;
  139. return CryptGetHashDef(hashAlg) != &NULL_Def;
  140. }
  141. /* 10.2.13.4.4 CryptHashGetAlgByIndex() */
  142. /* This function is used to iterate through the hashes. TPM_ALG_NULL is returned for all indexes
  143. that are not valid hashes. If the TPM implements 3 hashes, then an index value of 0 will return
  144. the first implemented hash and an index of 2 will return the last. All other index values will
  145. return TPM_ALG_NULL. */
  146. /* Return Value Meaning */
  147. /* TPM_ALG_xxx a hash algorithm */
  148. /* TPM_ALG_NULL this can be used as a stop value */
  149. LIB_EXPORT TPM_ALG_ID
  150. CryptHashGetAlgByIndex(
  151. UINT32 index // IN: the index
  152. )
  153. {
  154. TPM_ALG_ID hashAlg;
  155. if(index >= HASH_COUNT)
  156. hashAlg = TPM_ALG_NULL;
  157. else
  158. hashAlg = HashDefArray[index]->hashAlg;
  159. return hashAlg;
  160. }
  161. /* 10.2.13.4.5 CryptHashGetDigestSize() */
  162. /* Returns the size of the digest produced by the hash. If hashAlg is not a hash algorithm, the TPM
  163. will FAIL. */
  164. /* Return Value Meaning */
  165. /* 0 TPM_ALG_NULL */
  166. /* > 0 the digest size */
  167. LIB_EXPORT UINT16
  168. CryptHashGetDigestSize(
  169. TPM_ALG_ID hashAlg // IN: hash algorithm to look up
  170. )
  171. {
  172. return CryptGetHashDef(hashAlg)->digestSize;
  173. }
  174. /* 10.2.13.4.6 CryptHashGetBlockSize() */
  175. /* Returns the size of the block used by the hash. If hashAlg is not a hash algorithm, the TPM will
  176. FAIL. */
  177. /* Return Value Meaning */
  178. /* 0 TPM_ALG_NULL */
  179. /* > 0 the digest size */
  180. LIB_EXPORT UINT16
  181. CryptHashGetBlockSize(
  182. TPM_ALG_ID hashAlg // IN: hash algorithm to look up
  183. )
  184. {
  185. return CryptGetHashDef(hashAlg)->blockSize;
  186. }
  187. /* 10.2.13.4.7 CryptHashGetOid() */
  188. /* This function returns a pointer to DER=encoded OID for a hash algorithm. All OIDs are full OID
  189. values including the Tag (0x06) and length byte. */
  190. LIB_EXPORT const BYTE *
  191. CryptHashGetOid(
  192. TPM_ALG_ID hashAlg
  193. )
  194. {
  195. return CryptGetHashDef(hashAlg)->OID;
  196. }
  197. /* 10.2.13.4.8 CryptHashGetContextAlg() */
  198. /* This function returns the hash algorithm associated with a hash context. */
  199. TPM_ALG_ID
  200. CryptHashGetContextAlg(
  201. PHASH_STATE state // IN: the context to check
  202. )
  203. {
  204. return state->hashAlg;
  205. }
  206. /* 10.2.13.5 State Import and Export */
  207. /* 10.2.13.5.1 CryptHashCopyState */
  208. /* This function is used to clone a HASH_STATE. */
  209. LIB_EXPORT void
  210. CryptHashCopyState(
  211. HASH_STATE *out, // OUT: destination of the state
  212. const HASH_STATE *in // IN: source of the state
  213. )
  214. {
  215. pAssert(out->type == in->type);
  216. out->hashAlg = in->hashAlg;
  217. out->def = in->def;
  218. if(in->hashAlg != TPM_ALG_NULL)
  219. {
  220. HASH_STATE_COPY(out, in);
  221. }
  222. if(in->type == HASH_STATE_HMAC)
  223. {
  224. const HMAC_STATE *hIn = (HMAC_STATE *)in;
  225. HMAC_STATE *hOut = (HMAC_STATE *)out;
  226. hOut->hmacKey = hIn->hmacKey;
  227. }
  228. return;
  229. }
  230. /* 10.2.13.5.2 CryptHashExportState() */
  231. /* This function is used to export a hash or HMAC hash state. This function would be called when
  232. preparing to context save a sequence object. */
  233. void
  234. CryptHashExportState(
  235. PCHASH_STATE internalFmt, // IN: the hash state formatted for use by
  236. // library
  237. PEXPORT_HASH_STATE externalFmt // OUT: the exported hash state
  238. )
  239. {
  240. BYTE *outBuf = (BYTE *)externalFmt;
  241. //
  242. cAssert(sizeof(HASH_STATE) <= sizeof(EXPORT_HASH_STATE));
  243. // the following #define is used to move data from an aligned internal data
  244. // structure to a byte buffer (external format data.
  245. #define CopyToOffset(value) \
  246. memcpy(&outBuf[offsetof(HASH_STATE,value)], &internalFmt->value, \
  247. sizeof(internalFmt->value))
  248. // Copy the hashAlg
  249. CopyToOffset(hashAlg);
  250. CopyToOffset(type);
  251. #ifdef HASH_STATE_SMAC
  252. if(internalFmt->type == HASH_STATE_SMAC)
  253. {
  254. memcpy(outBuf, internalFmt, sizeof(HASH_STATE));
  255. return;
  256. }
  257. #endif
  258. if(internalFmt->type == HASH_STATE_HMAC)
  259. {
  260. HMAC_STATE *from = (HMAC_STATE *)internalFmt;
  261. memcpy(&outBuf[offsetof(HMAC_STATE, hmacKey)], &from->hmacKey,
  262. sizeof(from->hmacKey));
  263. }
  264. if(internalFmt->hashAlg != TPM_ALG_NULL)
  265. HASH_STATE_EXPORT(externalFmt, internalFmt);
  266. }
  267. /* 10.2.13.5.3 CryptHashImportState() */
  268. /* This function is used to import the hash state. This function would be called to import a hash
  269. state when the context of a sequence object was being loaded. */
  270. void
  271. CryptHashImportState(
  272. PHASH_STATE internalFmt, // OUT: the hash state formatted for use by
  273. // the library
  274. PCEXPORT_HASH_STATE externalFmt // IN: the exported hash state
  275. )
  276. {
  277. BYTE *inBuf = (BYTE *)externalFmt;
  278. //
  279. #define CopyFromOffset(value) \
  280. memcpy(&internalFmt->value, &inBuf[offsetof(HASH_STATE,value)], \
  281. sizeof(internalFmt->value))
  282. // Copy the hashAlg of the byte-aligned input structure to the structure-aligned
  283. // internal structure.
  284. CopyFromOffset(hashAlg);
  285. CopyFromOffset(type);
  286. if(internalFmt->hashAlg != TPM_ALG_NULL)
  287. {
  288. #ifdef HASH_STATE_SMAC
  289. if(internalFmt->type == HASH_STATE_SMAC)
  290. {
  291. memcpy(internalFmt, inBuf, sizeof(HASH_STATE));
  292. return;
  293. }
  294. #endif
  295. internalFmt->def = CryptGetHashDef(internalFmt->hashAlg);
  296. HASH_STATE_IMPORT(internalFmt, inBuf);
  297. if(internalFmt->type == HASH_STATE_HMAC)
  298. {
  299. HMAC_STATE *to = (HMAC_STATE *)internalFmt;
  300. memcpy(&to->hmacKey, &inBuf[offsetof(HMAC_STATE, hmacKey)],
  301. sizeof(to->hmacKey));
  302. }
  303. }
  304. }
  305. /* 10.2.13.6 State Modification Functions */
  306. /* 10.2.13.6.1 HashEnd() */
  307. /* Local function to complete a hash that uses the hashDef instead of an algorithm ID. This function
  308. is used to complete the hash and only return a partial digest. The return value is the size of
  309. the data copied. */
  310. static UINT16
  311. HashEnd(
  312. PHASH_STATE hashState, // IN: the hash state
  313. UINT32 dOutSize, // IN: the size of receive buffer
  314. PBYTE dOut // OUT: the receive buffer
  315. )
  316. {
  317. BYTE temp[MAX_DIGEST_SIZE];
  318. if((hashState->hashAlg == TPM_ALG_NULL)
  319. || (hashState->type != HASH_STATE_HASH))
  320. dOutSize = 0;
  321. if(dOutSize > 0)
  322. {
  323. hashState->def = CryptGetHashDef(hashState->hashAlg);
  324. // Set the final size
  325. dOutSize = MIN(dOutSize, hashState->def->digestSize);
  326. // Complete into the temp buffer and then copy
  327. HASH_END(hashState, temp);
  328. // Don't want any other functions calling the HASH_END method
  329. // directly.
  330. #undef HASH_END
  331. memcpy(dOut, &temp, dOutSize);
  332. }
  333. hashState->type = HASH_STATE_EMPTY;
  334. return (UINT16)dOutSize;
  335. }
  336. /* 10.2.13.6.2 CryptHashStart() */
  337. /* Functions starts a hash stack Start a hash stack and returns the digest size. As a side effect,
  338. the value of stateSize in hashState is updated to indicate the number of bytes of state that were
  339. saved. This function calls GetHashServer() and that function will put the TPM into failure mode
  340. if the hash algorithm is not supported. */
  341. /* This function does not use the sequence parameter. If it is necessary to import or export
  342. context, this will start the sequence in a local state and export the state to the input
  343. buffer. Will need to add a flag to the state structure to indicate that it needs to be imported
  344. before it can be used. (BLEH). */
  345. /* Return Value Meaning */
  346. /* 0 hash is TPM_ALG_NULL */
  347. /* >0 digest size */
  348. LIB_EXPORT UINT16
  349. CryptHashStart(
  350. PHASH_STATE hashState, // OUT: the running hash state
  351. TPM_ALG_ID hashAlg // IN: hash algorithm
  352. )
  353. {
  354. UINT16 retVal;
  355. TEST(hashAlg);
  356. hashState->hashAlg = hashAlg;
  357. if(hashAlg == TPM_ALG_NULL)
  358. {
  359. retVal = 0;
  360. }
  361. else
  362. {
  363. hashState->def = CryptGetHashDef(hashAlg);
  364. HASH_START(hashState);
  365. retVal = hashState->def->digestSize;
  366. }
  367. #undef HASH_START
  368. hashState->type = HASH_STATE_HASH;
  369. return retVal;
  370. }
  371. /* 10.2.13.6.3 CryptDigestUpdate() */
  372. /* Add data to a hash or HMAC, SMAC stack. */
  373. void
  374. CryptDigestUpdate(
  375. PHASH_STATE hashState, // IN: the hash context information
  376. UINT32 dataSize, // IN: the size of data to be added
  377. const BYTE *data // IN: data to be hashed
  378. )
  379. {
  380. if(hashState->hashAlg != TPM_ALG_NULL)
  381. {
  382. if((hashState->type == HASH_STATE_HASH)
  383. || (hashState->type == HASH_STATE_HMAC))
  384. HASH_DATA(hashState, dataSize, (BYTE *)data);
  385. #if SMAC_IMPLEMENTED
  386. else if(hashState->type == HASH_STATE_SMAC)
  387. (hashState->state.smac.smacMethods.data)(&hashState->state.smac.state,
  388. dataSize, data);
  389. #endif // SMAC_IMPLEMENTED
  390. else
  391. FAIL(FATAL_ERROR_INTERNAL);
  392. }
  393. return;
  394. }
  395. /* 10.2.13.6.4 CryptHashEnd() */
  396. /* Complete a hash or HMAC computation. This function will place the smaller of digestSize or the
  397. size of the digest in dOut. The number of bytes in the placed in the buffer is returned. If there
  398. is a failure, the returned value is <= 0. */
  399. /* Return Value Meaning */
  400. /* 0 no data returned */
  401. /* > 0 the number of bytes in the digest or dOutSize, whichever is smaller */
  402. LIB_EXPORT UINT16
  403. CryptHashEnd(
  404. PHASH_STATE hashState, // IN: the state of hash stack
  405. UINT32 dOutSize, // IN: size of digest buffer
  406. BYTE *dOut // OUT: hash digest
  407. )
  408. {
  409. pAssert(hashState->type == HASH_STATE_HASH);
  410. return HashEnd(hashState, dOutSize, dOut);
  411. }
  412. /* 10.2.13.6.5 CryptHashBlock() */
  413. /* Start a hash, hash a single block, update digest and return the size of the results. */
  414. /* The digestSize parameter can be smaller than the digest. If so, only the more significant
  415. bytes are returned. */
  416. /* Return Value Meaning */
  417. /* >= 0 number of bytes placed in dOut */
  418. LIB_EXPORT UINT16
  419. CryptHashBlock(
  420. TPM_ALG_ID hashAlg, // IN: The hash algorithm
  421. UINT32 dataSize, // IN: size of buffer to hash
  422. const BYTE *data, // IN: the buffer to hash
  423. UINT32 dOutSize, // IN: size of the digest buffer
  424. BYTE *dOut // OUT: digest buffer
  425. )
  426. {
  427. HASH_STATE state;
  428. CryptHashStart(&state, hashAlg);
  429. CryptDigestUpdate(&state, dataSize, data);
  430. return HashEnd(&state, dOutSize, dOut);
  431. }
  432. /* 10.2.13.6.6 CryptDigestUpdate2B() */
  433. /* This function updates a digest (hash or HMAC) with a TPM2B. */
  434. /* This function can be used for both HMAC and hash functions so the digestState is void so that
  435. either state type can be passed. */
  436. LIB_EXPORT void
  437. CryptDigestUpdate2B(
  438. PHASH_STATE state, // IN: the digest state
  439. const TPM2B *bIn // IN: 2B containing the data
  440. )
  441. {
  442. // Only compute the digest if a pointer to the 2B is provided.
  443. // In CryptDigestUpdate(), if size is zero or buffer is NULL, then no change
  444. // to the digest occurs. This function should not provide a buffer if bIn is
  445. // not provided.
  446. pAssert(bIn != NULL);
  447. CryptDigestUpdate(state, bIn->size, bIn->buffer);
  448. return;
  449. }
  450. /* 10.2.13.6.7 CryptHashEnd2B() */
  451. /* This function is the same as CryptCompleteHash() but the digest is placed in a TPM2B. This is the
  452. most common use and this is provided for specification clarity. digest.size should be set to
  453. indicate the number of bytes to place in the buffer */
  454. /* Return Value Meaning */
  455. /* >=0 the number of bytes placed in digest.buffer */
  456. LIB_EXPORT UINT16
  457. CryptHashEnd2B(
  458. PHASH_STATE state, // IN: the hash state
  459. P2B digest // IN: the size of the buffer Out: requested
  460. // number of bytes
  461. )
  462. {
  463. return CryptHashEnd(state, digest->size, digest->buffer);
  464. }
  465. /* 10.2.13.6.8 CryptDigestUpdateInt() */
  466. /* This function is used to include an integer value to a hash stack. The function marshals the
  467. integer into its canonical form before calling CryptDigestUpdate(). */
  468. LIB_EXPORT void
  469. CryptDigestUpdateInt(
  470. void *state, // IN: the state of hash stack
  471. UINT32 intSize, // IN: the size of 'intValue' in bytes
  472. UINT64 intValue // IN: integer value to be hashed
  473. )
  474. {
  475. #if LITTLE_ENDIAN_TPM
  476. intValue = REVERSE_ENDIAN_64(intValue);
  477. #endif
  478. CryptDigestUpdate(state, intSize, &((BYTE *)&intValue)[8 - intSize]);
  479. }
  480. /* 10.2.13.7 HMAC Functions */
  481. /* 10.2.13.7.1 CryptHmacStart() */
  482. /* This function is used to start an HMAC using a temp hash context. The function does the
  483. initialization of the hash with the HMAC key XOR iPad and updates the HMAC key XOR oPad. */
  484. /* The function returns the number of bytes in a digest produced by hashAlg. */
  485. /* Return Value Meaning */
  486. /* >= 0 number of bytes in digest produced by hashAlg (may be zero) */
  487. LIB_EXPORT UINT16
  488. CryptHmacStart(
  489. PHMAC_STATE state, // IN/OUT: the state buffer
  490. TPM_ALG_ID hashAlg, // IN: the algorithm to use
  491. UINT16 keySize, // IN: the size of the HMAC key
  492. const BYTE *key // IN: the HMAC key
  493. )
  494. {
  495. PHASH_DEF hashDef;
  496. BYTE * pb;
  497. UINT32 i;
  498. //
  499. hashDef = CryptGetHashDef(hashAlg);
  500. if(hashDef->digestSize != 0)
  501. {
  502. // If the HMAC key is larger than the hash block size, it has to be reduced
  503. // to fit. The reduction is a digest of the hashKey.
  504. if(keySize > hashDef->blockSize)
  505. {
  506. // if the key is too big, reduce it to a digest of itself
  507. state->hmacKey.t.size = CryptHashBlock(hashAlg, keySize, key,
  508. hashDef->digestSize,
  509. state->hmacKey.t.buffer);
  510. }
  511. else
  512. {
  513. memcpy(state->hmacKey.t.buffer, key, keySize);
  514. state->hmacKey.t.size = keySize;
  515. }
  516. // XOR the key with iPad (0x36)
  517. pb = state->hmacKey.t.buffer;
  518. for(i = state->hmacKey.t.size; i > 0; i--)
  519. *pb++ ^= 0x36;
  520. // if the keySize is smaller than a block, fill the rest with 0x36
  521. for(i = hashDef->blockSize - state->hmacKey.t.size; i > 0; i--)
  522. *pb++ = 0x36;
  523. // Increase the oPadSize to a full block
  524. state->hmacKey.t.size = hashDef->blockSize;
  525. // Start a new hash with the HMAC key
  526. // This will go in the caller's state structure and may be a sequence or not
  527. CryptHashStart((PHASH_STATE)state, hashAlg);
  528. CryptDigestUpdate((PHASH_STATE)state, state->hmacKey.t.size,
  529. state->hmacKey.t.buffer);
  530. // XOR the key block with 0x5c ^ 0x36
  531. for(pb = state->hmacKey.t.buffer, i = hashDef->blockSize; i > 0; i--)
  532. *pb++ ^= (0x5c ^ 0x36);
  533. }
  534. // Set the hash algorithm
  535. state->hashState.hashAlg = hashAlg;
  536. // Set the hash state type
  537. state->hashState.type = HASH_STATE_HMAC;
  538. return hashDef->digestSize;
  539. }
  540. /* 10.2.13.7.2 CryptHmacEnd() */
  541. /* This function is called to complete an HMAC. It will finish the current digest, and start a new digest. It will then add the oPadKey and the completed digest and return the results in dOut. It will not return more than dOutSize bytes. */
  542. /* Return Value Meaning */
  543. /* >= 0 number of bytes in dOut (may be zero) */
  544. LIB_EXPORT UINT16
  545. CryptHmacEnd(
  546. PHMAC_STATE state, // IN: the hash state buffer
  547. UINT32 dOutSize, // IN: size of digest buffer
  548. BYTE *dOut // OUT: hash digest
  549. )
  550. {
  551. BYTE temp[MAX_DIGEST_SIZE];
  552. PHASH_STATE hState = (PHASH_STATE)&state->hashState;
  553. #if SMAC_IMPLEMENTED
  554. if(hState->type == HASH_STATE_SMAC)
  555. return (state->hashState.state.smac.smacMethods.end)
  556. (&state->hashState.state.smac.state,
  557. dOutSize,
  558. dOut);
  559. #endif
  560. pAssert(hState->type == HASH_STATE_HMAC);
  561. hState->def = CryptGetHashDef(hState->hashAlg);
  562. // Change the state type for completion processing
  563. hState->type = HASH_STATE_HASH;
  564. if(hState->hashAlg == TPM_ALG_NULL)
  565. dOutSize = 0;
  566. else
  567. {
  568. // Complete the current hash
  569. HashEnd(hState, hState->def->digestSize, temp);
  570. // Do another hash starting with the oPad
  571. CryptHashStart(hState, hState->hashAlg);
  572. CryptDigestUpdate(hState, state->hmacKey.t.size, state->hmacKey.t.buffer);
  573. CryptDigestUpdate(hState, hState->def->digestSize, temp);
  574. }
  575. return HashEnd(hState, dOutSize, dOut);
  576. }
  577. /* 10.2.13.7.3 CryptHmacStart2B() */
  578. /* This function starts an HMAC and returns the size of the digest that will be produced. */
  579. /* This function is provided to support the most common use of starting an HMAC with a TPM2B key. */
  580. /* The caller must provide a block of memory in which the hash sequence state is kept. The caller
  581. should not alter the contents of this buffer until the hash sequence is completed or
  582. abandoned. */
  583. /* Return Value Meaning */
  584. /* > 0 the digest size of the algorithm */
  585. /* = 0 the hashAlg was TPM_ALG_NULL */
  586. LIB_EXPORT UINT16
  587. CryptHmacStart2B(
  588. PHMAC_STATE hmacState, // OUT: the state of HMAC stack. It will be used
  589. // in HMAC update and completion
  590. TPMI_ALG_HASH hashAlg, // IN: hash algorithm
  591. P2B key // IN: HMAC key
  592. )
  593. {
  594. return CryptHmacStart(hmacState, hashAlg, key->size, key->buffer);
  595. }
  596. /* 10.2.13.7.4 CryptHmacEnd2B() */
  597. /* This function is the same as CryptHmacEnd() but the HMAC result is returned in a TPM2B which is the most common use. */
  598. /* Return Value Meaning */
  599. /* >=0 the number of bytes placed in digest */
  600. LIB_EXPORT UINT16
  601. CryptHmacEnd2B(
  602. PHMAC_STATE hmacState, // IN: the state of HMAC stack
  603. P2B digest // OUT: HMAC
  604. )
  605. {
  606. return CryptHmacEnd(hmacState, digest->size, digest->buffer);
  607. }
  608. /* 10.2.13.8 Mask and Key Generation Functions */
  609. /* 10.2.13.8.1 CryptMGF_KDF() */
  610. /* This function performs MGF1/KDF1 or KDF2 using the selected hash. KDF1 and KDF2 are T(n) = T(n-1)
  611. || H(seed || counter) with the difference being that, with KDF1, counter starts at 0 but with
  612. KDF2, counter starts at 1. The caller determines which version by setting the initial value of
  613. counter to either 0 or 1. */
  614. /* Return Value Meaning */
  615. /* 0 hash algorithm was TPM_ALG_NULL */
  616. /* > 0 should be the same as mSize */
  617. LIB_EXPORT UINT16
  618. CryptMGF_KDF(
  619. UINT32 mSize, // IN: length of the mask to be produced
  620. BYTE *mask, // OUT: buffer to receive the mask
  621. TPM_ALG_ID hashAlg, // IN: hash to use
  622. UINT32 seedSize, // IN: size of the seed
  623. BYTE *seed, // IN: seed size
  624. UINT32 counter // IN: counter initial value
  625. )
  626. {
  627. HASH_STATE hashState;
  628. PHASH_DEF hDef = CryptGetHashDef(hashAlg);
  629. UINT32 hLen;
  630. UINT32 bytes;
  631. //
  632. // If there is no digest to compute return
  633. if((hDef->digestSize == 0) || (mSize == 0))
  634. return 0;
  635. if(counter != 0)
  636. counter = 1;
  637. hLen = hDef->digestSize;
  638. for(bytes = 0; bytes < mSize; bytes += hLen)
  639. {
  640. // Start the hash and include the seed and counter
  641. CryptHashStart(&hashState, hashAlg);
  642. CryptDigestUpdate(&hashState, seedSize, seed);
  643. CryptDigestUpdateInt(&hashState, 4, counter);
  644. // Get as much as will fit.
  645. CryptHashEnd(&hashState, MIN((mSize - bytes), hLen),
  646. &mask[bytes]);
  647. counter++;
  648. }
  649. return (UINT16)mSize;
  650. }
  651. /* 10.2.13.8.2 CryptKDFa() */
  652. /* This function performs the key generation according to Part 1 of the TPM specification. */
  653. /* This function returns the number of bytes generated which may be zero. */
  654. /* The key and keyStream pointers are not allowed to be NULL. The other pointer values may be
  655. NULL. The value of sizeInBits must be no larger than (2^18)-1 = 256K bits (32385 bytes). */
  656. /* The once parameter is set to allow incremental generation of a large value. If this flag is
  657. TRUE, sizeInBits will be used in the HMAC computation but only one iteration of the KDF is
  658. performed. This would be used for XOR obfuscation so that the mask value can be generated in
  659. digest-sized chunks rather than having to be generated all at once in an arbitrarily large
  660. buffer and then XORed into the result. If once is TRUE, then sizeInBits must be a multiple of
  661. 8. */
  662. /* Any error in the processing of this command is considered fatal. */
  663. /* Return Value Meaning */
  664. /* 0 hash algorithm is not supported or is TPM_ALG_NULL */
  665. /* > 0 the number of bytes in the keyStream buffer */
  666. LIB_EXPORT UINT16
  667. CryptKDFa(
  668. TPM_ALG_ID hashAlg, // IN: hash algorithm used in HMAC
  669. const TPM2B *key, // IN: HMAC key
  670. const TPM2B *label, // IN: a label for the KDF
  671. const TPM2B *contextU, // IN: context U
  672. const TPM2B *contextV, // IN: context V
  673. UINT32 sizeInBits, // IN: size of generated key in bits
  674. BYTE *keyStream, // OUT: key buffer
  675. UINT32 *counterInOut, // IN/OUT: caller may provide the iteration
  676. // counter for incremental operations to
  677. // avoid large intermediate buffers.
  678. UINT16 blocks // IN: If non-zero, this is the maximum number
  679. // of blocks to be returned, regardless
  680. // of sizeInBits
  681. )
  682. {
  683. UINT32 counter = 0; // counter value
  684. INT16 bytes; // number of bytes to produce
  685. UINT16 generated; // number of bytes generated
  686. BYTE *stream = keyStream;
  687. HMAC_STATE hState;
  688. UINT16 digestSize = CryptHashGetDigestSize(hashAlg);
  689. pAssert(key != NULL && keyStream != NULL);
  690. TEST(TPM_ALG_KDF1_SP800_108);
  691. if(digestSize == 0)
  692. return 0;
  693. if(counterInOut != NULL)
  694. counter = *counterInOut;
  695. // If the size of the request is larger than the numbers will handle,
  696. // it is a fatal error.
  697. pAssert(((sizeInBits + 7) / 8) <= INT16_MAX);
  698. // The number of bytes to be generated is the smaller of the sizeInBits bytes or
  699. // the number of requested blocks. The number of blocks is the smaller of the
  700. // number requested or the number allowed by sizeInBits. A partial block is
  701. // a full block.
  702. bytes = (blocks > 0) ? blocks * digestSize : (UINT16)BITS_TO_BYTES(sizeInBits);
  703. generated = bytes;
  704. // Generate required bytes
  705. for(; bytes > 0; bytes -= digestSize)
  706. {
  707. counter++;
  708. // Start HMAC
  709. if(CryptHmacStart(&hState, hashAlg, key->size, key->buffer) == 0)
  710. return 0;
  711. // Adding counter
  712. CryptDigestUpdateInt(&hState.hashState, 4, counter);
  713. // Adding label
  714. if(label != NULL)
  715. HASH_DATA(&hState.hashState, label->size, (BYTE *)label->buffer);
  716. // Add a null. SP108 is not very clear about when the 0 is needed but to
  717. // make this like the previous version that did not add an 0x00 after
  718. // a null-terminated string, this version will only add a null byte
  719. // if the label parameter did not end in a null byte, or if no label
  720. // is present.
  721. if((label == NULL)
  722. || (label->size == 0)
  723. || (label->buffer[label->size - 1] != 0))
  724. CryptDigestUpdateInt(&hState.hashState, 1, 0);
  725. // Adding contextU
  726. if(contextU != NULL)
  727. HASH_DATA(&hState.hashState, contextU->size, contextU->buffer);
  728. // Adding contextV
  729. if(contextV != NULL)
  730. HASH_DATA(&hState.hashState, contextV->size, contextV->buffer);
  731. // Adding size in bits
  732. CryptDigestUpdateInt(&hState.hashState, 4, sizeInBits);
  733. // Complete and put the data in the buffer
  734. CryptHmacEnd(&hState, bytes, stream);
  735. stream = &stream[digestSize];
  736. }
  737. // Masking in the KDF is disabled. If the calling function wants something
  738. // less than even number of bytes, then the caller should do the masking
  739. // because there is no universal way to do it here
  740. if(counterInOut != NULL)
  741. *counterInOut = counter;
  742. return generated;
  743. }
  744. /* 10.2.13.8.3 CryptKDFe() */
  745. /* This function implements KDFe() as defined in TPM specification part 1. */
  746. /* This function returns the number of bytes generated which may be zero. */
  747. /* The Z and keyStream pointers are not allowed to be NULL. The other pointer values may be
  748. NULL. The value of sizeInBits must be no larger than (2^18)-1 = 256K bits (32385 bytes). Any
  749. error in the processing of this command is considered fatal. */
  750. /* Return Value Meaning */
  751. /* 0 hash algorithm is not supported or is TPM_ALG_NULL */
  752. /* > 0 the number of bytes in the keyStream buffer */
  753. LIB_EXPORT UINT16
  754. CryptKDFe(
  755. TPM_ALG_ID hashAlg, // IN: hash algorithm used in HMAC
  756. TPM2B *Z, // IN: Z
  757. const TPM2B *label, // IN: a label value for the KDF
  758. TPM2B *partyUInfo, // IN: PartyUInfo
  759. TPM2B *partyVInfo, // IN: PartyVInfo
  760. UINT32 sizeInBits, // IN: size of generated key in bits
  761. BYTE *keyStream // OUT: key buffer
  762. )
  763. {
  764. HASH_STATE hashState;
  765. PHASH_DEF hashDef = CryptGetHashDef(hashAlg);
  766. UINT32 counter = 0; // counter value
  767. UINT16 hLen;
  768. BYTE *stream = keyStream;
  769. INT16 bytes; // number of bytes to generate
  770. pAssert(keyStream != NULL && Z != NULL && ((sizeInBits + 7) / 8) < INT16_MAX);
  771. //
  772. hLen = hashDef->digestSize;
  773. bytes = (INT16)((sizeInBits + 7) / 8);
  774. if(hashAlg == TPM_ALG_NULL || bytes == 0)
  775. return 0;
  776. // Generate required bytes
  777. //The inner loop of that KDF uses:
  778. // Hash[i] := H(counter | Z | OtherInfo) (5)
  779. // Where:
  780. // Hash[i] the hash generated on the i-th iteration of the loop.
  781. // H() an approved hash function
  782. // counter a 32-bit counter that is initialized to 1 and incremented
  783. // on each iteration
  784. // Z the X coordinate of the product of a public ECC key and a
  785. // different private ECC key.
  786. // OtherInfo a collection of qualifying data for the KDF defined below.
  787. // In this specification, OtherInfo will be constructed by:
  788. // OtherInfo := Use | PartyUInfo | PartyVInfo
  789. for(; bytes > 0; stream = &stream[hLen], bytes = bytes - hLen)
  790. {
  791. if(bytes < hLen)
  792. hLen = bytes;
  793. counter++;
  794. // Do the hash
  795. CryptHashStart(&hashState, hashAlg);
  796. // Add counter
  797. CryptDigestUpdateInt(&hashState, 4, counter);
  798. // Add Z
  799. if(Z != NULL)
  800. CryptDigestUpdate2B(&hashState, Z);
  801. // Add label
  802. if(label != NULL)
  803. CryptDigestUpdate2B(&hashState, label);
  804. // Add a null. SP108 is not very clear about when the 0 is needed but to
  805. // make this like the previous version that did not add an 0x00 after
  806. // a null-terminated string, this version will only add a null byte
  807. // if the label parameter did not end in a null byte, or if no label
  808. // is present.
  809. if((label == NULL)
  810. || (label->size == 0)
  811. || (label->buffer[label->size - 1] != 0))
  812. CryptDigestUpdateInt(&hashState, 1, 0);
  813. // Add PartyUInfo
  814. if(partyUInfo != NULL)
  815. CryptDigestUpdate2B(&hashState, partyUInfo);
  816. // Add PartyVInfo
  817. if(partyVInfo != NULL)
  818. CryptDigestUpdate2B(&hashState, partyVInfo);
  819. // Compute Hash. hLen was changed to be the smaller of bytes or hLen
  820. // at the start of each iteration.
  821. CryptHashEnd(&hashState, hLen, stream);
  822. }
  823. // Mask off bits if the required bits is not a multiple of byte size
  824. if((sizeInBits % 8) != 0)
  825. keyStream[0] &= ((1 << (sizeInBits % 8)) - 1);
  826. return (UINT16)((sizeInBits + 7) / 8);
  827. }