crypto_digest.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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-2018, 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 "common/container.h"
  12. #include "common/crypto_digest.h"
  13. #include "common/crypto_openssl_mgt.h"
  14. #include "common/crypto_util.h"
  15. #include "common/torlog.h"
  16. #include "keccak-tiny/keccak-tiny.h"
  17. DISABLE_GCC_WARNING(redundant-decls)
  18. #include <openssl/hmac.h>
  19. #include <openssl/sha.h>
  20. ENABLE_GCC_WARNING(redundant-decls)
  21. /* Crypto digest functions */
  22. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  23. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  24. * Return 0 on success, -1 on failure.
  25. */
  26. int
  27. crypto_digest(char *digest, const char *m, size_t len)
  28. {
  29. tor_assert(m);
  30. tor_assert(digest);
  31. if (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL)
  32. return -1;
  33. return 0;
  34. }
  35. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  36. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  37. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  38. int
  39. crypto_digest256(char *digest, const char *m, size_t len,
  40. digest_algorithm_t algorithm)
  41. {
  42. tor_assert(m);
  43. tor_assert(digest);
  44. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  45. int ret = 0;
  46. if (algorithm == DIGEST_SHA256)
  47. ret = (SHA256((const uint8_t*)m,len,(uint8_t*)digest) != NULL);
  48. else
  49. ret = (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  50. > -1);
  51. if (!ret)
  52. return -1;
  53. return 0;
  54. }
  55. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  56. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  57. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  58. int
  59. crypto_digest512(char *digest, const char *m, size_t len,
  60. digest_algorithm_t algorithm)
  61. {
  62. tor_assert(m);
  63. tor_assert(digest);
  64. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  65. int ret = 0;
  66. if (algorithm == DIGEST_SHA512)
  67. ret = (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  68. != NULL);
  69. else
  70. ret = (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  71. > -1);
  72. if (!ret)
  73. return -1;
  74. return 0;
  75. }
  76. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  77. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  78. * success, -1 on failure. */
  79. int
  80. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  81. {
  82. tor_assert(ds_out);
  83. memset(ds_out, 0, sizeof(*ds_out));
  84. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  85. return -1;
  86. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  87. return -1;
  88. return 0;
  89. }
  90. /** Return the name of an algorithm, as used in directory documents. */
  91. const char *
  92. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  93. {
  94. switch (alg) {
  95. case DIGEST_SHA1:
  96. return "sha1";
  97. case DIGEST_SHA256:
  98. return "sha256";
  99. case DIGEST_SHA512:
  100. return "sha512";
  101. case DIGEST_SHA3_256:
  102. return "sha3-256";
  103. case DIGEST_SHA3_512:
  104. return "sha3-512";
  105. // LCOV_EXCL_START
  106. default:
  107. tor_fragile_assert();
  108. return "??unknown_digest??";
  109. // LCOV_EXCL_STOP
  110. }
  111. }
  112. /** Given the name of a digest algorithm, return its integer value, or -1 if
  113. * the name is not recognized. */
  114. int
  115. crypto_digest_algorithm_parse_name(const char *name)
  116. {
  117. if (!strcmp(name, "sha1"))
  118. return DIGEST_SHA1;
  119. else if (!strcmp(name, "sha256"))
  120. return DIGEST_SHA256;
  121. else if (!strcmp(name, "sha512"))
  122. return DIGEST_SHA512;
  123. else if (!strcmp(name, "sha3-256"))
  124. return DIGEST_SHA3_256;
  125. else if (!strcmp(name, "sha3-512"))
  126. return DIGEST_SHA3_512;
  127. else
  128. return -1;
  129. }
  130. /** Given an algorithm, return the digest length in bytes. */
  131. size_t
  132. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  133. {
  134. switch (alg) {
  135. case DIGEST_SHA1:
  136. return DIGEST_LEN;
  137. case DIGEST_SHA256:
  138. return DIGEST256_LEN;
  139. case DIGEST_SHA512:
  140. return DIGEST512_LEN;
  141. case DIGEST_SHA3_256:
  142. return DIGEST256_LEN;
  143. case DIGEST_SHA3_512:
  144. return DIGEST512_LEN;
  145. default:
  146. tor_assert(0); // LCOV_EXCL_LINE
  147. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  148. }
  149. }
  150. /** Intermediate information about the digest of a stream of data. */
  151. struct crypto_digest_t {
  152. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  153. /** State for the digest we're using. Only one member of the
  154. * union is usable, depending on the value of <b>algorithm</b>. Note also
  155. * that space for other members might not even be allocated!
  156. */
  157. union {
  158. SHA_CTX sha1; /**< state for SHA1 */
  159. SHA256_CTX sha2; /**< state for SHA256 */
  160. SHA512_CTX sha512; /**< state for SHA512 */
  161. keccak_state sha3; /**< state for SHA3-[256,512] */
  162. } d;
  163. };
  164. #ifdef TOR_UNIT_TESTS
  165. digest_algorithm_t
  166. crypto_digest_get_algorithm(crypto_digest_t *digest)
  167. {
  168. tor_assert(digest);
  169. return digest->algorithm;
  170. }
  171. #endif /* defined(TOR_UNIT_TESTS) */
  172. /**
  173. * Return the number of bytes we need to malloc in order to get a
  174. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  175. * when we free one.
  176. */
  177. static size_t
  178. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  179. {
  180. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  181. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  182. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  183. #define END_OF_FIELD(f) (offsetof(crypto_digest_t, f) + \
  184. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  185. switch (alg) {
  186. case DIGEST_SHA1:
  187. return END_OF_FIELD(d.sha1);
  188. case DIGEST_SHA256:
  189. return END_OF_FIELD(d.sha2);
  190. case DIGEST_SHA512:
  191. return END_OF_FIELD(d.sha512);
  192. case DIGEST_SHA3_256:
  193. case DIGEST_SHA3_512:
  194. return END_OF_FIELD(d.sha3);
  195. default:
  196. tor_assert(0); // LCOV_EXCL_LINE
  197. return 0; // LCOV_EXCL_LINE
  198. }
  199. #undef END_OF_FIELD
  200. #undef STRUCT_FIELD_SIZE
  201. }
  202. /**
  203. * Internal function: create and return a new digest object for 'algorithm'.
  204. * Does not typecheck the algorithm.
  205. */
  206. static crypto_digest_t *
  207. crypto_digest_new_internal(digest_algorithm_t algorithm)
  208. {
  209. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  210. r->algorithm = algorithm;
  211. switch (algorithm)
  212. {
  213. case DIGEST_SHA1:
  214. SHA1_Init(&r->d.sha1);
  215. break;
  216. case DIGEST_SHA256:
  217. SHA256_Init(&r->d.sha2);
  218. break;
  219. case DIGEST_SHA512:
  220. SHA512_Init(&r->d.sha512);
  221. break;
  222. case DIGEST_SHA3_256:
  223. keccak_digest_init(&r->d.sha3, 256);
  224. break;
  225. case DIGEST_SHA3_512:
  226. keccak_digest_init(&r->d.sha3, 512);
  227. break;
  228. default:
  229. tor_assert_unreached();
  230. }
  231. return r;
  232. }
  233. /** Allocate and return a new digest object to compute SHA1 digests.
  234. */
  235. crypto_digest_t *
  236. crypto_digest_new(void)
  237. {
  238. return crypto_digest_new_internal(DIGEST_SHA1);
  239. }
  240. /** Allocate and return a new digest object to compute 256-bit digests
  241. * using <b>algorithm</b>.
  242. *
  243. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest256_new`
  244. * C_RUST_COUPLED: `crypto::digest::Sha256::default`
  245. */
  246. crypto_digest_t *
  247. crypto_digest256_new(digest_algorithm_t algorithm)
  248. {
  249. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  250. return crypto_digest_new_internal(algorithm);
  251. }
  252. /** Allocate and return a new digest object to compute 512-bit digests
  253. * using <b>algorithm</b>. */
  254. crypto_digest_t *
  255. crypto_digest512_new(digest_algorithm_t algorithm)
  256. {
  257. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  258. return crypto_digest_new_internal(algorithm);
  259. }
  260. /** Deallocate a digest object.
  261. */
  262. void
  263. crypto_digest_free_(crypto_digest_t *digest)
  264. {
  265. if (!digest)
  266. return;
  267. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  268. memwipe(digest, 0, bytes);
  269. tor_free(digest);
  270. }
  271. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  272. *
  273. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_add_bytess`
  274. * C_RUST_COUPLED: `crypto::digest::Sha256::process`
  275. */
  276. void
  277. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  278. size_t len)
  279. {
  280. tor_assert(digest);
  281. tor_assert(data);
  282. /* Using the SHA*_*() calls directly means we don't support doing
  283. * SHA in hardware. But so far the delay of getting the question
  284. * to the hardware, and hearing the answer, is likely higher than
  285. * just doing it ourselves. Hashes are fast.
  286. */
  287. switch (digest->algorithm) {
  288. case DIGEST_SHA1:
  289. SHA1_Update(&digest->d.sha1, (void*)data, len);
  290. break;
  291. case DIGEST_SHA256:
  292. SHA256_Update(&digest->d.sha2, (void*)data, len);
  293. break;
  294. case DIGEST_SHA512:
  295. SHA512_Update(&digest->d.sha512, (void*)data, len);
  296. break;
  297. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  298. case DIGEST_SHA3_512:
  299. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  300. break;
  301. default:
  302. /* LCOV_EXCL_START */
  303. tor_fragile_assert();
  304. break;
  305. /* LCOV_EXCL_STOP */
  306. }
  307. }
  308. /** Compute the hash of the data that has been passed to the digest
  309. * object; write the first out_len bytes of the result to <b>out</b>.
  310. * <b>out_len</b> must be \<= DIGEST512_LEN.
  311. *
  312. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_get_digest`
  313. * C_RUST_COUPLED: `impl digest::FixedOutput for Sha256`
  314. */
  315. void
  316. crypto_digest_get_digest(crypto_digest_t *digest,
  317. char *out, size_t out_len)
  318. {
  319. unsigned char r[DIGEST512_LEN];
  320. crypto_digest_t tmpenv;
  321. tor_assert(digest);
  322. tor_assert(out);
  323. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  324. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  325. * short output buffers by truncating appropriately. */
  326. if (digest->algorithm == DIGEST_SHA3_256 ||
  327. digest->algorithm == DIGEST_SHA3_512) {
  328. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  329. return;
  330. }
  331. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  332. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  333. memcpy(&tmpenv, digest, alloc_bytes);
  334. switch (digest->algorithm) {
  335. case DIGEST_SHA1:
  336. SHA1_Final(r, &tmpenv.d.sha1);
  337. break;
  338. case DIGEST_SHA256:
  339. SHA256_Final(r, &tmpenv.d.sha2);
  340. break;
  341. case DIGEST_SHA512:
  342. SHA512_Final(r, &tmpenv.d.sha512);
  343. break;
  344. //LCOV_EXCL_START
  345. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  346. case DIGEST_SHA3_512:
  347. default:
  348. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  349. /* This is fatal, because it should never happen. */
  350. tor_assert_unreached();
  351. break;
  352. //LCOV_EXCL_STOP
  353. }
  354. memcpy(out, r, out_len);
  355. memwipe(r, 0, sizeof(r));
  356. }
  357. /** Allocate and return a new digest object with the same state as
  358. * <b>digest</b>
  359. *
  360. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_dup`
  361. * C_RUST_COUPLED: `impl Clone for crypto::digest::Sha256`
  362. */
  363. crypto_digest_t *
  364. crypto_digest_dup(const crypto_digest_t *digest)
  365. {
  366. tor_assert(digest);
  367. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  368. return tor_memdup(digest, alloc_bytes);
  369. }
  370. /** Temporarily save the state of <b>digest</b> in <b>checkpoint</b>.
  371. * Asserts that <b>digest</b> is a SHA1 digest object.
  372. */
  373. void
  374. crypto_digest_checkpoint(crypto_digest_checkpoint_t *checkpoint,
  375. const crypto_digest_t *digest)
  376. {
  377. const size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  378. tor_assert(bytes <= sizeof(checkpoint->mem));
  379. memcpy(checkpoint->mem, digest, bytes);
  380. }
  381. /** Restore the state of <b>digest</b> from <b>checkpoint</b>.
  382. * Asserts that <b>digest</b> is a SHA1 digest object. Requires that the
  383. * state was previously stored with crypto_digest_checkpoint() */
  384. void
  385. crypto_digest_restore(crypto_digest_t *digest,
  386. const crypto_digest_checkpoint_t *checkpoint)
  387. {
  388. const size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  389. memcpy(digest, checkpoint->mem, bytes);
  390. }
  391. /** Replace the state of the digest object <b>into</b> with the state
  392. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  393. * have the same digest type.
  394. */
  395. void
  396. crypto_digest_assign(crypto_digest_t *into,
  397. const crypto_digest_t *from)
  398. {
  399. tor_assert(into);
  400. tor_assert(from);
  401. tor_assert(into->algorithm == from->algorithm);
  402. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  403. memcpy(into,from,alloc_bytes);
  404. }
  405. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  406. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  407. * plus the optional string <b>append</b>, computed with the algorithm
  408. * <b>alg</b>.
  409. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  410. void
  411. crypto_digest_smartlist(char *digest_out, size_t len_out,
  412. const smartlist_t *lst,
  413. const char *append,
  414. digest_algorithm_t alg)
  415. {
  416. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  417. }
  418. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  419. * at <b>digest_out</b> to the hash of the concatenation of: the
  420. * optional string <b>prepend</b>, those strings,
  421. * and the optional string <b>append</b>, computed with the algorithm
  422. * <b>alg</b>.
  423. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  424. void
  425. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  426. const char *prepend,
  427. const smartlist_t *lst,
  428. const char *append,
  429. digest_algorithm_t alg)
  430. {
  431. crypto_digest_t *d = crypto_digest_new_internal(alg);
  432. if (prepend)
  433. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  434. SMARTLIST_FOREACH(lst, const char *, cp,
  435. crypto_digest_add_bytes(d, cp, strlen(cp)));
  436. if (append)
  437. crypto_digest_add_bytes(d, append, strlen(append));
  438. crypto_digest_get_digest(d, digest_out, len_out);
  439. crypto_digest_free(d);
  440. }
  441. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  442. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  443. * result in <b>hmac_out</b>. Asserts on failure.
  444. */
  445. void
  446. crypto_hmac_sha256(char *hmac_out,
  447. const char *key, size_t key_len,
  448. const char *msg, size_t msg_len)
  449. {
  450. unsigned char *rv = NULL;
  451. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  452. tor_assert(key_len < INT_MAX);
  453. tor_assert(msg_len < INT_MAX);
  454. tor_assert(hmac_out);
  455. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  456. (unsigned char*)hmac_out, NULL);
  457. tor_assert(rv);
  458. }
  459. /** Compute a MAC using SHA3-256 of <b>msg_len</b> bytes in <b>msg</b> using a
  460. * <b>key</b> of length <b>key_len</b> and a <b>salt</b> of length
  461. * <b>salt_len</b>. Store the result of <b>len_out</b> bytes in in
  462. * <b>mac_out</b>. This function can't fail. */
  463. void
  464. crypto_mac_sha3_256(uint8_t *mac_out, size_t len_out,
  465. const uint8_t *key, size_t key_len,
  466. const uint8_t *msg, size_t msg_len)
  467. {
  468. crypto_digest_t *digest;
  469. const uint64_t key_len_netorder = tor_htonll(key_len);
  470. tor_assert(mac_out);
  471. tor_assert(key);
  472. tor_assert(msg);
  473. digest = crypto_digest256_new(DIGEST_SHA3_256);
  474. /* Order matters here that is any subsystem using this function should
  475. * expect this very precise ordering in the MAC construction. */
  476. crypto_digest_add_bytes(digest, (const char *) &key_len_netorder,
  477. sizeof(key_len_netorder));
  478. crypto_digest_add_bytes(digest, (const char *) key, key_len);
  479. crypto_digest_add_bytes(digest, (const char *) msg, msg_len);
  480. crypto_digest_get_digest(digest, (char *) mac_out, len_out);
  481. crypto_digest_free(digest);
  482. }
  483. /* xof functions */
  484. /** Internal state for a eXtendable-Output Function (XOF). */
  485. struct crypto_xof_t {
  486. keccak_state s;
  487. };
  488. /** Allocate a new XOF object backed by SHAKE-256. The security level
  489. * provided is a function of the length of the output used. Read and
  490. * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
  491. * Functions" before using this construct.
  492. */
  493. crypto_xof_t *
  494. crypto_xof_new(void)
  495. {
  496. crypto_xof_t *xof;
  497. xof = tor_malloc(sizeof(crypto_xof_t));
  498. keccak_xof_init(&xof->s, 256);
  499. return xof;
  500. }
  501. /** Absorb bytes into a XOF object. Must not be called after a call to
  502. * crypto_xof_squeeze_bytes() for the same instance, and will assert
  503. * if attempted.
  504. */
  505. void
  506. crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
  507. {
  508. int i = keccak_xof_absorb(&xof->s, data, len);
  509. tor_assert(i == 0);
  510. }
  511. /** Squeeze bytes out of a XOF object. Calling this routine will render
  512. * the XOF instance ineligible to absorb further data.
  513. */
  514. void
  515. crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
  516. {
  517. int i = keccak_xof_squeeze(&xof->s, out, len);
  518. tor_assert(i == 0);
  519. }
  520. /** Cleanse and deallocate a XOF object. */
  521. void
  522. crypto_xof_free_(crypto_xof_t *xof)
  523. {
  524. if (!xof)
  525. return;
  526. memwipe(xof, 0, sizeof(crypto_xof_t));
  527. tor_free(xof);
  528. }