crypto_digest_nss.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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_nss.c
  8. * \brief Block of functions related with digest and xof utilities and
  9. * operations (NSS specific implementations).
  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. DISABLE_GCC_WARNING(strict-prototypes)
  21. #include <pk11pub.h>
  22. ENABLE_GCC_WARNING(strict-prototypes)
  23. /**
  24. * Convert a digest_algorithm_t (used by tor) to a HashType (used by NSS).
  25. * On failure, return SEC_OID_UNKNOWN. */
  26. static SECOidTag
  27. digest_alg_to_nss_oid(digest_algorithm_t alg)
  28. {
  29. switch (alg) {
  30. case DIGEST_SHA1: return SEC_OID_SHA1;
  31. case DIGEST_SHA256: return SEC_OID_SHA256;
  32. case DIGEST_SHA512: return SEC_OID_SHA512;
  33. case DIGEST_SHA3_256: /* Fall through */
  34. case DIGEST_SHA3_512: /* Fall through */
  35. default:
  36. return SEC_OID_UNKNOWN;
  37. }
  38. }
  39. /* Helper: get an unkeyed digest via pk11wrap */
  40. static int
  41. digest_nss_internal(SECOidTag alg,
  42. char *digest, unsigned len_out,
  43. const char *msg, size_t msg_len)
  44. {
  45. if (alg == SEC_OID_UNKNOWN)
  46. return -1;
  47. tor_assert(msg_len <= UINT_MAX);
  48. int rv = -1;
  49. SECStatus s;
  50. PK11Context *ctx = PK11_CreateDigestContext(alg);
  51. if (!ctx)
  52. return -1;
  53. s = PK11_DigestBegin(ctx);
  54. if (s != SECSuccess)
  55. goto done;
  56. s = PK11_DigestOp(ctx, (const unsigned char *)msg, (unsigned int)msg_len);
  57. if (s != SECSuccess)
  58. goto done;
  59. unsigned int len = 0;
  60. s = PK11_DigestFinal(ctx, (unsigned char *)digest, &len, len_out);
  61. if (s != SECSuccess)
  62. goto done;
  63. rv = 0;
  64. done:
  65. PK11_DestroyContext(ctx, PR_TRUE);
  66. return rv;
  67. }
  68. /** True iff alg is implemented in our crypto library, and we want to use that
  69. * implementation */
  70. static bool
  71. library_supports_digest(digest_algorithm_t alg)
  72. {
  73. switch (alg) {
  74. case DIGEST_SHA1: /* Fall through */
  75. case DIGEST_SHA256: /* Fall through */
  76. case DIGEST_SHA512: /* Fall through */
  77. return true;
  78. case DIGEST_SHA3_256: /* Fall through */
  79. case DIGEST_SHA3_512: /* Fall through */
  80. default:
  81. return false;
  82. }
  83. }
  84. /* Crypto digest functions */
  85. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  86. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  87. * Return 0 on success, -1 on failure.
  88. */
  89. MOCK_IMPL(int,
  90. crypto_digest,(char *digest, const char *m, size_t len))
  91. {
  92. tor_assert(m);
  93. tor_assert(digest);
  94. return digest_nss_internal(SEC_OID_SHA1, digest, DIGEST_LEN, m, len);
  95. }
  96. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  97. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  98. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  99. int
  100. crypto_digest256(char *digest, const char *m, size_t len,
  101. digest_algorithm_t algorithm)
  102. {
  103. tor_assert(m);
  104. tor_assert(digest);
  105. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  106. int ret = 0;
  107. if (algorithm == DIGEST_SHA256) {
  108. return digest_nss_internal(SEC_OID_SHA256, digest, DIGEST256_LEN, m, len);
  109. } else {
  110. ret = (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  111. > -1);
  112. }
  113. if (!ret)
  114. return -1;
  115. return 0;
  116. }
  117. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  118. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  119. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  120. int
  121. crypto_digest512(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_SHA512 || algorithm == DIGEST_SHA3_512);
  127. int ret = 0;
  128. if (algorithm == DIGEST_SHA512) {
  129. return digest_nss_internal(SEC_OID_SHA512, digest, DIGEST512_LEN, m, len);
  130. } else {
  131. ret = (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  132. > -1);
  133. }
  134. if (!ret)
  135. return -1;
  136. return 0;
  137. }
  138. /** Intermediate information about the digest of a stream of data. */
  139. struct crypto_digest_t {
  140. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  141. /** State for the digest we're using. Only one member of the
  142. * union is usable, depending on the value of <b>algorithm</b>. Note also
  143. * that space for other members might not even be allocated!
  144. */
  145. union {
  146. PK11Context *ctx;
  147. keccak_state sha3; /**< state for SHA3-[256,512] */
  148. } d;
  149. };
  150. #ifdef TOR_UNIT_TESTS
  151. digest_algorithm_t
  152. crypto_digest_get_algorithm(crypto_digest_t *digest)
  153. {
  154. tor_assert(digest);
  155. return digest->algorithm;
  156. }
  157. #endif /* defined(TOR_UNIT_TESTS) */
  158. /**
  159. * Return the number of bytes we need to malloc in order to get a
  160. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  161. * when we free one.
  162. */
  163. static size_t
  164. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  165. {
  166. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  167. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  168. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  169. #define END_OF_FIELD(f) (offsetof(crypto_digest_t, f) + \
  170. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  171. switch (alg) {
  172. case DIGEST_SHA1: /* Fall through */
  173. case DIGEST_SHA256: /* Fall through */
  174. case DIGEST_SHA512:
  175. return END_OF_FIELD(d.ctx);
  176. case DIGEST_SHA3_256:
  177. case DIGEST_SHA3_512:
  178. return END_OF_FIELD(d.sha3);
  179. default:
  180. tor_assert(0); // LCOV_EXCL_LINE
  181. return 0; // LCOV_EXCL_LINE
  182. }
  183. #undef END_OF_FIELD
  184. #undef STRUCT_FIELD_SIZE
  185. }
  186. /**
  187. * Internal function: create and return a new digest object for 'algorithm'.
  188. * Does not typecheck the algorithm.
  189. */
  190. static crypto_digest_t *
  191. crypto_digest_new_internal(digest_algorithm_t algorithm)
  192. {
  193. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  194. r->algorithm = algorithm;
  195. switch (algorithm)
  196. {
  197. case DIGEST_SHA1: /* fall through */
  198. case DIGEST_SHA256: /* fall through */
  199. case DIGEST_SHA512:
  200. r->d.ctx = PK11_CreateDigestContext(digest_alg_to_nss_oid(algorithm));
  201. if (BUG(!r->d.ctx)) {
  202. tor_free(r);
  203. return NULL;
  204. }
  205. if (BUG(SECSuccess != PK11_DigestBegin(r->d.ctx))) {
  206. crypto_digest_free(r);
  207. return NULL;
  208. }
  209. break;
  210. case DIGEST_SHA3_256:
  211. keccak_digest_init(&r->d.sha3, 256);
  212. break;
  213. case DIGEST_SHA3_512:
  214. keccak_digest_init(&r->d.sha3, 512);
  215. break;
  216. default:
  217. tor_assert_unreached();
  218. }
  219. return r;
  220. }
  221. /** Allocate and return a new digest object to compute SHA1 digests.
  222. */
  223. crypto_digest_t *
  224. crypto_digest_new(void)
  225. {
  226. return crypto_digest_new_internal(DIGEST_SHA1);
  227. }
  228. /** Allocate and return a new digest object to compute 256-bit digests
  229. * using <b>algorithm</b>.
  230. *
  231. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest256_new`
  232. * C_RUST_COUPLED: `crypto::digest::Sha256::default`
  233. */
  234. crypto_digest_t *
  235. crypto_digest256_new(digest_algorithm_t algorithm)
  236. {
  237. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  238. return crypto_digest_new_internal(algorithm);
  239. }
  240. /** Allocate and return a new digest object to compute 512-bit digests
  241. * using <b>algorithm</b>. */
  242. crypto_digest_t *
  243. crypto_digest512_new(digest_algorithm_t algorithm)
  244. {
  245. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  246. return crypto_digest_new_internal(algorithm);
  247. }
  248. /** Deallocate a digest object.
  249. */
  250. void
  251. crypto_digest_free_(crypto_digest_t *digest)
  252. {
  253. if (!digest)
  254. return;
  255. if (library_supports_digest(digest->algorithm)) {
  256. PK11_DestroyContext(digest->d.ctx, PR_TRUE);
  257. }
  258. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  259. memwipe(digest, 0, bytes);
  260. tor_free(digest);
  261. }
  262. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  263. *
  264. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_add_bytess`
  265. * C_RUST_COUPLED: `crypto::digest::Sha256::process`
  266. */
  267. void
  268. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  269. size_t len)
  270. {
  271. tor_assert(digest);
  272. tor_assert(data);
  273. /* Using the SHA*_*() calls directly means we don't support doing
  274. * SHA in hardware. But so far the delay of getting the question
  275. * to the hardware, and hearing the answer, is likely higher than
  276. * just doing it ourselves. Hashes are fast.
  277. */
  278. switch (digest->algorithm) {
  279. case DIGEST_SHA1: /* fall through */
  280. case DIGEST_SHA256: /* fall through */
  281. case DIGEST_SHA512:
  282. tor_assert(len <= UINT_MAX);
  283. SECStatus s = PK11_DigestOp(digest->d.ctx,
  284. (const unsigned char *)data,
  285. (unsigned int)len);
  286. tor_assert(s == SECSuccess);
  287. break;
  288. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  289. case DIGEST_SHA3_512:
  290. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  291. break;
  292. default:
  293. /* LCOV_EXCL_START */
  294. tor_fragile_assert();
  295. break;
  296. /* LCOV_EXCL_STOP */
  297. }
  298. }
  299. /** Compute the hash of the data that has been passed to the digest
  300. * object; write the first out_len bytes of the result to <b>out</b>.
  301. * <b>out_len</b> must be \<= DIGEST512_LEN.
  302. *
  303. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_get_digest`
  304. * C_RUST_COUPLED: `impl digest::FixedOutput for Sha256`
  305. */
  306. void
  307. crypto_digest_get_digest(crypto_digest_t *digest,
  308. char *out, size_t out_len)
  309. {
  310. unsigned char r[DIGEST512_LEN];
  311. tor_assert(digest);
  312. tor_assert(out);
  313. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  314. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  315. * short output buffers by truncating appropriately. */
  316. if (digest->algorithm == DIGEST_SHA3_256 ||
  317. digest->algorithm == DIGEST_SHA3_512) {
  318. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  319. return;
  320. }
  321. /* Copy into a temporary buffer since DigestFinal (alters) the context */
  322. unsigned char buf[1024];
  323. unsigned int saved_len = 0;
  324. unsigned rlen;
  325. unsigned char *saved = PK11_SaveContextAlloc(digest->d.ctx,
  326. buf, sizeof(buf),
  327. &saved_len);
  328. tor_assert(saved);
  329. SECStatus s = PK11_DigestFinal(digest->d.ctx, r, &rlen, sizeof(r));
  330. tor_assert(s == SECSuccess);
  331. tor_assert(rlen >= out_len);
  332. s = PK11_RestoreContext(digest->d.ctx, saved, saved_len);
  333. tor_assert(s == SECSuccess);
  334. if (saved != buf) {
  335. PORT_ZFree(saved, saved_len);
  336. }
  337. memcpy(out, r, out_len);
  338. memwipe(r, 0, sizeof(r));
  339. }
  340. /** Allocate and return a new digest object with the same state as
  341. * <b>digest</b>
  342. *
  343. * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_dup`
  344. * C_RUST_COUPLED: `impl Clone for crypto::digest::Sha256`
  345. */
  346. crypto_digest_t *
  347. crypto_digest_dup(const crypto_digest_t *digest)
  348. {
  349. tor_assert(digest);
  350. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  351. crypto_digest_t *result = tor_memdup(digest, alloc_bytes);
  352. if (library_supports_digest(digest->algorithm)) {
  353. result->d.ctx = PK11_CloneContext(digest->d.ctx);
  354. }
  355. return result;
  356. }
  357. /** Temporarily save the state of <b>digest</b> in <b>checkpoint</b>.
  358. * Asserts that <b>digest</b> is a SHA1 digest object.
  359. */
  360. void
  361. crypto_digest_checkpoint(crypto_digest_checkpoint_t *checkpoint,
  362. const crypto_digest_t *digest)
  363. {
  364. const size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  365. tor_assert(bytes <= sizeof(checkpoint->mem));
  366. if (library_supports_digest(digest->algorithm)) {
  367. unsigned char *allocated;
  368. allocated = PK11_SaveContextAlloc(digest->d.ctx,
  369. (unsigned char *)checkpoint->mem,
  370. sizeof(checkpoint->mem),
  371. &checkpoint->bytes_used);
  372. /* No allocation is allowed here. */
  373. tor_assert(allocated == checkpoint->mem);
  374. return;
  375. }
  376. memcpy(checkpoint->mem, digest, bytes);
  377. }
  378. /** Restore the state of <b>digest</b> from <b>checkpoint</b>.
  379. * Asserts that <b>digest</b> is a SHA1 digest object. Requires that the
  380. * state was previously stored with crypto_digest_checkpoint() */
  381. void
  382. crypto_digest_restore(crypto_digest_t *digest,
  383. const crypto_digest_checkpoint_t *checkpoint)
  384. {
  385. const size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  386. if (library_supports_digest(digest->algorithm)) {
  387. SECStatus s = PK11_RestoreContext(digest->d.ctx,
  388. (unsigned char *)checkpoint->mem,
  389. checkpoint->bytes_used);
  390. tor_assert(s == SECSuccess);
  391. return;
  392. }
  393. memcpy(digest, checkpoint->mem, bytes);
  394. }
  395. /** Replace the state of the digest object <b>into</b> with the state
  396. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  397. * have the same digest type.
  398. */
  399. void
  400. crypto_digest_assign(crypto_digest_t *into,
  401. const crypto_digest_t *from)
  402. {
  403. tor_assert(into);
  404. tor_assert(from);
  405. tor_assert(into->algorithm == from->algorithm);
  406. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  407. if (library_supports_digest(from->algorithm)) {
  408. PK11_DestroyContext(into->d.ctx, PR_TRUE);
  409. into->d.ctx = PK11_CloneContext(from->d.ctx);
  410. return;
  411. }
  412. memcpy(into,from,alloc_bytes);
  413. }
  414. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  415. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  416. * plus the optional string <b>append</b>, computed with the algorithm
  417. * <b>alg</b>.
  418. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  419. void
  420. crypto_digest_smartlist(char *digest_out, size_t len_out,
  421. const smartlist_t *lst,
  422. const char *append,
  423. digest_algorithm_t alg)
  424. {
  425. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  426. }
  427. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  428. * at <b>digest_out</b> to the hash of the concatenation of: the
  429. * optional string <b>prepend</b>, those strings,
  430. * and the optional string <b>append</b>, computed with the algorithm
  431. * <b>alg</b>.
  432. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  433. void
  434. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  435. const char *prepend,
  436. const smartlist_t *lst,
  437. const char *append,
  438. digest_algorithm_t alg)
  439. {
  440. crypto_digest_t *d = crypto_digest_new_internal(alg);
  441. if (prepend)
  442. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  443. SMARTLIST_FOREACH(lst, const char *, cp,
  444. crypto_digest_add_bytes(d, cp, strlen(cp)));
  445. if (append)
  446. crypto_digest_add_bytes(d, append, strlen(append));
  447. crypto_digest_get_digest(d, digest_out, len_out);
  448. crypto_digest_free(d);
  449. }
  450. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  451. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  452. * result in <b>hmac_out</b>. Asserts on failure.
  453. */
  454. void
  455. crypto_hmac_sha256(char *hmac_out,
  456. const char *key, size_t key_len,
  457. const char *msg, size_t msg_len)
  458. {
  459. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  460. tor_assert(key_len < INT_MAX);
  461. tor_assert(msg_len < INT_MAX);
  462. tor_assert(hmac_out);
  463. PK11SlotInfo *slot = NULL;
  464. PK11SymKey *symKey = NULL;
  465. PK11Context *hmac = NULL;
  466. int ok = 0;
  467. SECStatus s;
  468. SECItem keyItem, paramItem;
  469. keyItem.data = (unsigned char *)key;
  470. keyItem.len = (unsigned)key_len;
  471. paramItem.type = siBuffer;
  472. paramItem.data = NULL;
  473. paramItem.len = 0;
  474. slot = PK11_GetBestSlot(CKM_SHA256_HMAC, NULL);
  475. if (!slot)
  476. goto done;
  477. symKey = PK11_ImportSymKey(slot, CKM_SHA256_HMAC,
  478. PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);
  479. if (!symKey)
  480. goto done;
  481. hmac = PK11_CreateContextBySymKey(CKM_SHA256_HMAC, CKA_SIGN, symKey,
  482. &paramItem);
  483. if (!hmac)
  484. goto done;
  485. s = PK11_DigestBegin(hmac);
  486. if (s != SECSuccess)
  487. goto done;
  488. s = PK11_DigestOp(hmac, (const unsigned char *)msg, (unsigned int)msg_len);
  489. if (s != SECSuccess)
  490. goto done;
  491. unsigned int len=0;
  492. s = PK11_DigestFinal(hmac, (unsigned char *)hmac_out, &len, DIGEST256_LEN);
  493. if (s != SECSuccess || len != DIGEST256_LEN)
  494. goto done;
  495. ok = 1;
  496. done:
  497. if (hmac)
  498. PK11_DestroyContext(hmac, PR_TRUE);
  499. if (symKey)
  500. PK11_FreeSymKey(symKey);
  501. if (slot)
  502. PK11_FreeSlot(slot);
  503. tor_assert(ok);
  504. }