crypto_digest.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_digest.c
  8. * \brief Block of functions related with digest and xof utilities and
  9. * operations.
  10. **/
  11. #include "lib/container/smartlist.h"
  12. #include "lib/crypt_ops/crypto_digest.h"
  13. #include "lib/crypt_ops/crypto_util.h"
  14. #include "lib/log/log.h"
  15. #include "lib/log/util_bug.h"
  16. #include "keccak-tiny/keccak-tiny.h"
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include "lib/arch/bytes.h"
  20. #ifdef ENABLE_NSS
  21. DISABLE_GCC_WARNING(strict-prototypes)
  22. #include <pk11pub.h>
  23. ENABLE_GCC_WARNING(strict-prototypes)
  24. #else
  25. #include "lib/crypt_ops/crypto_openssl_mgt.h"
  26. DISABLE_GCC_WARNING(redundant-decls)
  27. #include <openssl/hmac.h>
  28. #include <openssl/sha.h>
  29. ENABLE_GCC_WARNING(redundant-decls)
  30. #endif
  31. #ifdef ENABLE_NSS
  32. /**
  33. * Convert a digest_algorithm_t (used by tor) to a HashType (used by NSS).
  34. * On failure, return SEC_OID_UNKNOWN. */
  35. static SECOidTag
  36. digest_alg_to_nss_oid(digest_algorithm_t alg)
  37. {
  38. switch (alg) {
  39. case DIGEST_SHA1: return SEC_OID_SHA1;
  40. case DIGEST_SHA256: return SEC_OID_SHA256;
  41. case DIGEST_SHA512: return SEC_OID_SHA512;
  42. case DIGEST_SHA3_256: /* Fall through */
  43. case DIGEST_SHA3_512: /* Fall through */
  44. default:
  45. return SEC_OID_UNKNOWN;
  46. }
  47. }
  48. /* Helper: get an unkeyed digest via pk11wrap */
  49. static int
  50. digest_nss_internal(SECOidTag alg,
  51. char *digest, unsigned len_out,
  52. const char *msg, size_t msg_len)
  53. {
  54. if (alg == SEC_OID_UNKNOWN)
  55. return -1;
  56. tor_assert(msg_len <= UINT_MAX);
  57. int rv = -1;
  58. SECStatus s;
  59. PK11Context *ctx = PK11_CreateDigestContext(alg);
  60. if (!ctx)
  61. return -1;
  62. s = PK11_DigestBegin(ctx);
  63. if (s != SECSuccess)
  64. goto done;
  65. s = PK11_DigestOp(ctx, (const unsigned char *)msg, (unsigned int)msg_len);
  66. if (s != SECSuccess)
  67. goto done;
  68. unsigned int len = 0;
  69. s = PK11_DigestFinal(ctx, (unsigned char *)digest, &len, len_out);
  70. if (s != SECSuccess)
  71. goto done;
  72. rv = 0;
  73. done:
  74. PK11_DestroyContext(ctx, PR_TRUE);
  75. return rv;
  76. }
  77. /** True iff alg is implemented in our crypto library, and we want to use that
  78. * implementation */
  79. static bool
  80. library_supports_digest(digest_algorithm_t alg)
  81. {
  82. switch (alg) {
  83. case DIGEST_SHA1: /* Fall through */
  84. case DIGEST_SHA256: /* Fall through */
  85. case DIGEST_SHA512: /* Fall through */
  86. return true;
  87. case DIGEST_SHA3_256: /* Fall through */
  88. case DIGEST_SHA3_512: /* Fall through */
  89. default:
  90. return false;
  91. }
  92. }
  93. #endif
  94. /* Crypto digest functions */
  95. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  96. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  97. * Return 0 on success, -1 on failure.
  98. */
  99. MOCK_IMPL(int,
  100. crypto_digest,(char *digest, const char *m, size_t len))
  101. {
  102. tor_assert(m);
  103. tor_assert(digest);
  104. #ifdef ENABLE_NSS
  105. return digest_nss_internal(SEC_OID_SHA1, digest, DIGEST_LEN, m, len);
  106. #else
  107. if (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL) {
  108. return -1;
  109. }
  110. #endif
  111. return 0;
  112. }
  113. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  114. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  115. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  116. int
  117. crypto_digest256(char *digest, const char *m, size_t len,
  118. digest_algorithm_t algorithm)
  119. {
  120. tor_assert(m);
  121. tor_assert(digest);
  122. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  123. int ret = 0;
  124. if (algorithm == DIGEST_SHA256) {
  125. #ifdef ENABLE_NSS
  126. return digest_nss_internal(SEC_OID_SHA256, digest, DIGEST256_LEN, m, len);
  127. #else
  128. ret = (SHA256((const uint8_t*)m,len,(uint8_t*)digest) != NULL);
  129. #endif
  130. } else {
  131. ret = (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  132. > -1);
  133. }
  134. if (!ret)
  135. return -1;
  136. return 0;
  137. }
  138. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  139. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  140. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  141. int
  142. crypto_digest512(char *digest, const char *m, size_t len,
  143. digest_algorithm_t algorithm)
  144. {
  145. tor_assert(m);
  146. tor_assert(digest);
  147. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  148. int ret = 0;
  149. if (algorithm == DIGEST_SHA512) {
  150. #ifdef ENABLE_NSS
  151. return digest_nss_internal(SEC_OID_SHA512, digest, DIGEST512_LEN, m, len);
  152. #else
  153. ret = (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  154. != NULL);
  155. #endif
  156. } else {
  157. ret = (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  158. > -1);
  159. }
  160. if (!ret)
  161. return -1;
  162. return 0;
  163. }
  164. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  165. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  166. * success, -1 on failure. */
  167. int
  168. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  169. {
  170. tor_assert(ds_out);
  171. memset(ds_out, 0, sizeof(*ds_out));
  172. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  173. return -1;
  174. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  175. return -1;
  176. return 0;
  177. }
  178. /** Return the name of an algorithm, as used in directory documents. */
  179. const char *
  180. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  181. {
  182. switch (alg) {
  183. case DIGEST_SHA1:
  184. return "sha1";
  185. case DIGEST_SHA256:
  186. return "sha256";
  187. case DIGEST_SHA512:
  188. return "sha512";
  189. case DIGEST_SHA3_256:
  190. return "sha3-256";
  191. case DIGEST_SHA3_512:
  192. return "sha3-512";
  193. // LCOV_EXCL_START
  194. default:
  195. tor_fragile_assert();
  196. return "??unknown_digest??";
  197. // LCOV_EXCL_STOP
  198. }
  199. }
  200. /** Given the name of a digest algorithm, return its integer value, or -1 if
  201. * the name is not recognized. */
  202. int
  203. crypto_digest_algorithm_parse_name(const char *name)
  204. {
  205. if (!strcmp(name, "sha1"))
  206. return DIGEST_SHA1;
  207. else if (!strcmp(name, "sha256"))
  208. return DIGEST_SHA256;
  209. else if (!strcmp(name, "sha512"))
  210. return DIGEST_SHA512;
  211. else if (!strcmp(name, "sha3-256"))
  212. return DIGEST_SHA3_256;
  213. else if (!strcmp(name, "sha3-512"))
  214. return DIGEST_SHA3_512;
  215. else
  216. return -1;
  217. }
  218. /** Given an algorithm, return the digest length in bytes. */
  219. size_t
  220. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  221. {
  222. switch (alg) {
  223. case DIGEST_SHA1:
  224. return DIGEST_LEN;
  225. case DIGEST_SHA256:
  226. return DIGEST256_LEN;
  227. case DIGEST_SHA512:
  228. return DIGEST512_LEN;
  229. case DIGEST_SHA3_256:
  230. return DIGEST256_LEN;
  231. case DIGEST_SHA3_512:
  232. return DIGEST512_LEN;
  233. default:
  234. tor_assert(0); // LCOV_EXCL_LINE
  235. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  236. }
  237. }
  238. /** Intermediate information about the digest of a stream of data. */
  239. struct crypto_digest_t {
  240. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  241. /** State for the digest we're using. Only one member of the
  242. * union is usable, depending on the value of <b>algorithm</b>. Note also
  243. * that space for other members might not even be allocated!
  244. */
  245. union {
  246. #ifdef ENABLE_NSS
  247. PK11Context *ctx;
  248. #else
  249. SHA_CTX sha1; /**< state for SHA1 */
  250. SHA256_CTX sha2; /**< state for SHA256 */
  251. SHA512_CTX sha512; /**< state for SHA512 */
  252. #endif
  253. keccak_state sha3; /**< state for SHA3-[256,512] */
  254. } d;
  255. };
  256. #ifdef TOR_UNIT_TESTS
  257. digest_algorithm_t
  258. crypto_digest_get_algorithm(crypto_digest_t *digest)
  259. {
  260. tor_assert(digest);
  261. return digest->algorithm;
  262. }
  263. #endif /* defined(TOR_UNIT_TESTS) */
  264. /**
  265. * Return the number of bytes we need to malloc in order to get a
  266. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  267. * when we free one.
  268. */
  269. static size_t
  270. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  271. {
  272. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  273. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  274. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  275. #define END_OF_FIELD(f) (offsetof(crypto_digest_t, f) + \
  276. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  277. switch (alg) {
  278. #ifdef ENABLE_NSS
  279. case DIGEST_SHA1: /* Fall through */
  280. case DIGEST_SHA256: /* Fall through */
  281. case DIGEST_SHA512:
  282. return END_OF_FIELD(d.ctx);
  283. #else
  284. case DIGEST_SHA1:
  285. return END_OF_FIELD(d.sha1);
  286. case DIGEST_SHA256:
  287. return END_OF_FIELD(d.sha2);
  288. case DIGEST_SHA512:
  289. return END_OF_FIELD(d.sha512);
  290. #endif
  291. case DIGEST_SHA3_256:
  292. case DIGEST_SHA3_512:
  293. return END_OF_FIELD(d.sha3);
  294. default:
  295. tor_assert(0); // LCOV_EXCL_LINE
  296. return 0; // LCOV_EXCL_LINE
  297. }
  298. #undef END_OF_FIELD
  299. #undef STRUCT_FIELD_SIZE
  300. }
  301. /**
  302. * Internal function: create and return a new digest object for 'algorithm'.
  303. * Does not typecheck the algorithm.
  304. */
  305. static crypto_digest_t *
  306. crypto_digest_new_internal(digest_algorithm_t algorithm)
  307. {
  308. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  309. r->algorithm = algorithm;
  310. switch (algorithm)
  311. {
  312. #ifdef ENABLE_NSS
  313. case DIGEST_SHA1: /* fall through */
  314. case DIGEST_SHA256: /* fall through */
  315. case DIGEST_SHA512:
  316. r->d.ctx = PK11_CreateDigestContext(digest_alg_to_nss_oid(algorithm));
  317. if (BUG(!r->d.ctx)) {
  318. tor_free(r);
  319. return NULL;
  320. }
  321. if (BUG(SECSuccess != PK11_DigestBegin(r->d.ctx))) {
  322. crypto_digest_free(r);
  323. return NULL;
  324. }
  325. break;
  326. #else
  327. case DIGEST_SHA1:
  328. SHA1_Init(&r->d.sha1);
  329. break;
  330. case DIGEST_SHA256:
  331. SHA256_Init(&r->d.sha2);
  332. break;
  333. case DIGEST_SHA512:
  334. SHA512_Init(&r->d.sha512);
  335. break;
  336. #endif
  337. case DIGEST_SHA3_256:
  338. keccak_digest_init(&r->d.sha3, 256);
  339. break;
  340. case DIGEST_SHA3_512:
  341. keccak_digest_init(&r->d.sha3, 512);
  342. break;
  343. default:
  344. tor_assert_unreached();
  345. }
  346. return r;
  347. }
  348. /** Allocate and return a new digest object to compute SHA1 digests.
  349. */
  350. crypto_digest_t *
  351. crypto_digest_new(void)
  352. {
  353. return crypto_digest_new_internal(DIGEST_SHA1);
  354. }
  355. /** Allocate and return a new digest object to compute 256-bit digests
  356. * using <b>algorithm</b>.
  357. *
  358. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest256_new`
  359. * C_RUST_COUPLED: `crypto::digest::Sha256::default`
  360. */
  361. crypto_digest_t *
  362. crypto_digest256_new(digest_algorithm_t algorithm)
  363. {
  364. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  365. return crypto_digest_new_internal(algorithm);
  366. }
  367. /** Allocate and return a new digest object to compute 512-bit digests
  368. * using <b>algorithm</b>. */
  369. crypto_digest_t *
  370. crypto_digest512_new(digest_algorithm_t algorithm)
  371. {
  372. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  373. return crypto_digest_new_internal(algorithm);
  374. }
  375. /** Deallocate a digest object.
  376. */
  377. void
  378. crypto_digest_free_(crypto_digest_t *digest)
  379. {
  380. if (!digest)
  381. return;
  382. #ifdef ENABLE_NSS
  383. if (library_supports_digest(digest->algorithm)) {
  384. PK11_DestroyContext(digest->d.ctx, PR_TRUE);
  385. }
  386. #endif
  387. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  388. memwipe(digest, 0, bytes);
  389. tor_free(digest);
  390. }
  391. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  392. *
  393. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_add_bytess`
  394. * C_RUST_COUPLED: `crypto::digest::Sha256::process`
  395. */
  396. void
  397. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  398. size_t len)
  399. {
  400. tor_assert(digest);
  401. tor_assert(data);
  402. /* Using the SHA*_*() calls directly means we don't support doing
  403. * SHA in hardware. But so far the delay of getting the question
  404. * to the hardware, and hearing the answer, is likely higher than
  405. * just doing it ourselves. Hashes are fast.
  406. */
  407. switch (digest->algorithm) {
  408. #ifdef ENABLE_NSS
  409. case DIGEST_SHA1: /* fall through */
  410. case DIGEST_SHA256: /* fall through */
  411. case DIGEST_SHA512:
  412. tor_assert(len <= UINT_MAX);
  413. SECStatus s = PK11_DigestOp(digest->d.ctx,
  414. (const unsigned char *)data,
  415. (unsigned int)len);
  416. tor_assert(s == SECSuccess);
  417. break;
  418. #else
  419. case DIGEST_SHA1:
  420. SHA1_Update(&digest->d.sha1, (void*)data, len);
  421. break;
  422. case DIGEST_SHA256:
  423. SHA256_Update(&digest->d.sha2, (void*)data, len);
  424. break;
  425. case DIGEST_SHA512:
  426. SHA512_Update(&digest->d.sha512, (void*)data, len);
  427. break;
  428. #endif
  429. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  430. case DIGEST_SHA3_512:
  431. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  432. break;
  433. default:
  434. /* LCOV_EXCL_START */
  435. tor_fragile_assert();
  436. break;
  437. /* LCOV_EXCL_STOP */
  438. }
  439. }
  440. /** Compute the hash of the data that has been passed to the digest
  441. * object; write the first out_len bytes of the result to <b>out</b>.
  442. * <b>out_len</b> must be \<= DIGEST512_LEN.
  443. *
  444. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_get_digest`
  445. * C_RUST_COUPLED: `impl digest::FixedOutput for Sha256`
  446. */
  447. void
  448. crypto_digest_get_digest(crypto_digest_t *digest,
  449. char *out, size_t out_len)
  450. {
  451. unsigned char r[DIGEST512_LEN];
  452. tor_assert(digest);
  453. tor_assert(out);
  454. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  455. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  456. * short output buffers by truncating appropriately. */
  457. if (digest->algorithm == DIGEST_SHA3_256 ||
  458. digest->algorithm == DIGEST_SHA3_512) {
  459. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  460. return;
  461. }
  462. #ifdef ENABLE_NSS
  463. /* Copy into a temporary buffer since DigestFinal (alters) the context */
  464. unsigned char buf[1024];
  465. unsigned int saved_len = 0;
  466. unsigned rlen;
  467. unsigned char *saved = PK11_SaveContextAlloc(digest->d.ctx,
  468. buf, sizeof(buf),
  469. &saved_len);
  470. tor_assert(saved);
  471. SECStatus s = PK11_DigestFinal(digest->d.ctx, r, &rlen, sizeof(r));
  472. tor_assert(s == SECSuccess);
  473. tor_assert(rlen >= out_len);
  474. s = PK11_RestoreContext(digest->d.ctx, saved, saved_len);
  475. tor_assert(s == SECSuccess);
  476. if (saved != buf) {
  477. PORT_ZFree(saved, saved_len);
  478. }
  479. #else
  480. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  481. crypto_digest_t tmpenv;
  482. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  483. memcpy(&tmpenv, digest, alloc_bytes);
  484. switch (digest->algorithm) {
  485. case DIGEST_SHA1:
  486. SHA1_Final(r, &tmpenv.d.sha1);
  487. break;
  488. case DIGEST_SHA256:
  489. SHA256_Final(r, &tmpenv.d.sha2);
  490. break;
  491. case DIGEST_SHA512:
  492. SHA512_Final(r, &tmpenv.d.sha512);
  493. break;
  494. //LCOV_EXCL_START
  495. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  496. case DIGEST_SHA3_512:
  497. default:
  498. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  499. /* This is fatal, because it should never happen. */
  500. tor_assert_unreached();
  501. break;
  502. //LCOV_EXCL_STOP
  503. }
  504. #endif
  505. memcpy(out, r, out_len);
  506. memwipe(r, 0, sizeof(r));
  507. }
  508. /** Allocate and return a new digest object with the same state as
  509. * <b>digest</b>
  510. *
  511. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_dup`
  512. * C_RUST_COUPLED: `impl Clone for crypto::digest::Sha256`
  513. */
  514. crypto_digest_t *
  515. crypto_digest_dup(const crypto_digest_t *digest)
  516. {
  517. tor_assert(digest);
  518. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  519. crypto_digest_t *result = tor_memdup(digest, alloc_bytes);
  520. #ifdef ENABLE_NSS
  521. if (library_supports_digest(digest->algorithm)) {
  522. result->d.ctx = PK11_CloneContext(digest->d.ctx);
  523. }
  524. #endif
  525. return result;
  526. }
  527. /** Temporarily save the state of <b>digest</b> in <b>checkpoint</b>.
  528. * Asserts that <b>digest</b> is a SHA1 digest object.
  529. */
  530. void
  531. crypto_digest_checkpoint(crypto_digest_checkpoint_t *checkpoint,
  532. const crypto_digest_t *digest)
  533. {
  534. const size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  535. tor_assert(bytes <= sizeof(checkpoint->mem));
  536. #ifdef ENABLE_NSS
  537. if (library_supports_digest(digest->algorithm)) {
  538. unsigned char *allocated;
  539. allocated = PK11_SaveContextAlloc(digest->d.ctx,
  540. (unsigned char *)checkpoint->mem,
  541. sizeof(checkpoint->mem),
  542. &checkpoint->bytes_used);
  543. /* No allocation is allowed here. */
  544. tor_assert(allocated == checkpoint->mem);
  545. return;
  546. }
  547. #endif
  548. memcpy(checkpoint->mem, digest, bytes);
  549. }
  550. /** Restore the state of <b>digest</b> from <b>checkpoint</b>.
  551. * Asserts that <b>digest</b> is a SHA1 digest object. Requires that the
  552. * state was previously stored with crypto_digest_checkpoint() */
  553. void
  554. crypto_digest_restore(crypto_digest_t *digest,
  555. const crypto_digest_checkpoint_t *checkpoint)
  556. {
  557. const size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  558. #ifdef ENABLE_NSS
  559. if (library_supports_digest(digest->algorithm)) {
  560. SECStatus s = PK11_RestoreContext(digest->d.ctx,
  561. (unsigned char *)checkpoint->mem,
  562. checkpoint->bytes_used);
  563. tor_assert(s == SECSuccess);
  564. return;
  565. }
  566. #endif
  567. memcpy(digest, checkpoint->mem, bytes);
  568. }
  569. /** Replace the state of the digest object <b>into</b> with the state
  570. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  571. * have the same digest type.
  572. */
  573. void
  574. crypto_digest_assign(crypto_digest_t *into,
  575. const crypto_digest_t *from)
  576. {
  577. tor_assert(into);
  578. tor_assert(from);
  579. tor_assert(into->algorithm == from->algorithm);
  580. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  581. #ifdef ENABLE_NSS
  582. if (library_supports_digest(from->algorithm)) {
  583. PK11_DestroyContext(into->d.ctx, PR_TRUE);
  584. into->d.ctx = PK11_CloneContext(from->d.ctx);
  585. return;
  586. }
  587. #endif
  588. memcpy(into,from,alloc_bytes);
  589. }
  590. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  591. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  592. * plus the optional string <b>append</b>, computed with the algorithm
  593. * <b>alg</b>.
  594. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  595. void
  596. crypto_digest_smartlist(char *digest_out, size_t len_out,
  597. const smartlist_t *lst,
  598. const char *append,
  599. digest_algorithm_t alg)
  600. {
  601. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  602. }
  603. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  604. * at <b>digest_out</b> to the hash of the concatenation of: the
  605. * optional string <b>prepend</b>, those strings,
  606. * and the optional string <b>append</b>, computed with the algorithm
  607. * <b>alg</b>.
  608. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  609. void
  610. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  611. const char *prepend,
  612. const smartlist_t *lst,
  613. const char *append,
  614. digest_algorithm_t alg)
  615. {
  616. crypto_digest_t *d = crypto_digest_new_internal(alg);
  617. if (prepend)
  618. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  619. SMARTLIST_FOREACH(lst, const char *, cp,
  620. crypto_digest_add_bytes(d, cp, strlen(cp)));
  621. if (append)
  622. crypto_digest_add_bytes(d, append, strlen(append));
  623. crypto_digest_get_digest(d, digest_out, len_out);
  624. crypto_digest_free(d);
  625. }
  626. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  627. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  628. * result in <b>hmac_out</b>. Asserts on failure.
  629. */
  630. void
  631. crypto_hmac_sha256(char *hmac_out,
  632. const char *key, size_t key_len,
  633. const char *msg, size_t msg_len)
  634. {
  635. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  636. tor_assert(key_len < INT_MAX);
  637. tor_assert(msg_len < INT_MAX);
  638. tor_assert(hmac_out);
  639. #ifdef ENABLE_NSS
  640. PK11SlotInfo *slot = NULL;
  641. PK11SymKey *symKey = NULL;
  642. PK11Context *hmac = NULL;
  643. int ok = 0;
  644. SECStatus s;
  645. SECItem keyItem, paramItem;
  646. keyItem.data = (unsigned char *)key;
  647. keyItem.len = (unsigned)key_len;
  648. paramItem.type = siBuffer;
  649. paramItem.data = NULL;
  650. paramItem.len = 0;
  651. slot = PK11_GetBestSlot(CKM_SHA256_HMAC, NULL);
  652. if (!slot)
  653. goto done;
  654. symKey = PK11_ImportSymKey(slot, CKM_SHA256_HMAC,
  655. PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);
  656. if (!symKey)
  657. goto done;
  658. hmac = PK11_CreateContextBySymKey(CKM_SHA256_HMAC, CKA_SIGN, symKey,
  659. &paramItem);
  660. if (!hmac)
  661. goto done;
  662. s = PK11_DigestBegin(hmac);
  663. if (s != SECSuccess)
  664. goto done;
  665. s = PK11_DigestOp(hmac, (const unsigned char *)msg, (unsigned int)msg_len);
  666. if (s != SECSuccess)
  667. goto done;
  668. unsigned int len=0;
  669. s = PK11_DigestFinal(hmac, (unsigned char *)hmac_out, &len, DIGEST256_LEN);
  670. if (s != SECSuccess || len != DIGEST256_LEN)
  671. goto done;
  672. ok = 1;
  673. done:
  674. if (hmac)
  675. PK11_DestroyContext(hmac, PR_TRUE);
  676. if (symKey)
  677. PK11_FreeSymKey(symKey);
  678. if (slot)
  679. PK11_FreeSlot(slot);
  680. tor_assert(ok);
  681. #else
  682. unsigned char *rv = NULL;
  683. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  684. (unsigned char*)hmac_out, NULL);
  685. tor_assert(rv);
  686. #endif
  687. }
  688. /** Compute a MAC using SHA3-256 of <b>msg_len</b> bytes in <b>msg</b> using a
  689. * <b>key</b> of length <b>key_len</b> and a <b>salt</b> of length
  690. * <b>salt_len</b>. Store the result of <b>len_out</b> bytes in in
  691. * <b>mac_out</b>. This function can't fail. */
  692. void
  693. crypto_mac_sha3_256(uint8_t *mac_out, size_t len_out,
  694. const uint8_t *key, size_t key_len,
  695. const uint8_t *msg, size_t msg_len)
  696. {
  697. crypto_digest_t *digest;
  698. const uint64_t key_len_netorder = tor_htonll(key_len);
  699. tor_assert(mac_out);
  700. tor_assert(key);
  701. tor_assert(msg);
  702. digest = crypto_digest256_new(DIGEST_SHA3_256);
  703. /* Order matters here that is any subsystem using this function should
  704. * expect this very precise ordering in the MAC construction. */
  705. crypto_digest_add_bytes(digest, (const char *) &key_len_netorder,
  706. sizeof(key_len_netorder));
  707. crypto_digest_add_bytes(digest, (const char *) key, key_len);
  708. crypto_digest_add_bytes(digest, (const char *) msg, msg_len);
  709. crypto_digest_get_digest(digest, (char *) mac_out, len_out);
  710. crypto_digest_free(digest);
  711. }
  712. /* xof functions */
  713. /** Internal state for a eXtendable-Output Function (XOF). */
  714. struct crypto_xof_t {
  715. keccak_state s;
  716. };
  717. /** Allocate a new XOF object backed by SHAKE-256. The security level
  718. * provided is a function of the length of the output used. Read and
  719. * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
  720. * Functions" before using this construct.
  721. */
  722. crypto_xof_t *
  723. crypto_xof_new(void)
  724. {
  725. crypto_xof_t *xof;
  726. xof = tor_malloc(sizeof(crypto_xof_t));
  727. keccak_xof_init(&xof->s, 256);
  728. return xof;
  729. }
  730. /** Absorb bytes into a XOF object. Must not be called after a call to
  731. * crypto_xof_squeeze_bytes() for the same instance, and will assert
  732. * if attempted.
  733. */
  734. void
  735. crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
  736. {
  737. int i = keccak_xof_absorb(&xof->s, data, len);
  738. tor_assert(i == 0);
  739. }
  740. /** Squeeze bytes out of a XOF object. Calling this routine will render
  741. * the XOF instance ineligible to absorb further data.
  742. */
  743. void
  744. crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
  745. {
  746. int i = keccak_xof_squeeze(&xof->s, out, len);
  747. tor_assert(i == 0);
  748. }
  749. /** Cleanse and deallocate a XOF object. */
  750. void
  751. crypto_xof_free_(crypto_xof_t *xof)
  752. {
  753. if (!xof)
  754. return;
  755. memwipe(xof, 0, sizeof(crypto_xof_t));
  756. tor_free(xof);
  757. }