crypto_digest.c 27 KB

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