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-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
8 * \file crypto_digest_nss.c
9 * \brief Block of functions related with digest and xof utilities and
10 * operations (NSS specific implementations).
13 #include "lib/container/smartlist.h"
14 #include "lib/crypt_ops/crypto_digest.h"
15 #include "lib/crypt_ops/crypto_util.h"
16 #include "lib/log/log.h"
17 #include "lib/log/util_bug.h"
19 #include "keccak-tiny/keccak-tiny.h"
24 #include "lib/arch/bytes.h"
26 DISABLE_GCC_WARNING("-Wstrict-prototypes")
28 ENABLE_GCC_WARNING("-Wstrict-prototypes")
31 * Convert a digest_algorithm_t (used by tor) to a HashType (used by NSS).
32 * On failure, return SEC_OID_UNKNOWN. */
34 digest_alg_to_nss_oid(digest_algorithm_t alg
)
37 case DIGEST_SHA1
: return SEC_OID_SHA1
;
38 case DIGEST_SHA256
: return SEC_OID_SHA256
;
39 case DIGEST_SHA512
: return SEC_OID_SHA512
;
40 case DIGEST_SHA3_256
: FALLTHROUGH
;
41 case DIGEST_SHA3_512
: FALLTHROUGH
;
43 return SEC_OID_UNKNOWN
;
47 /** Helper: Compute an unkeyed digest of the <b>msg_len</b> bytes at
48 * <b>msg</b>, using the digest algorithm specified by <b>alg</b>.
49 * Store the result in the <b>len_out</b>-byte buffer at <b>digest</b>.
50 * Return the number of bytes written on success, and -1 on failure.
53 digest_nss_internal(SECOidTag alg
,
54 char *digest
, unsigned len_out
,
55 const char *msg
, size_t msg_len
)
57 if (alg
== SEC_OID_UNKNOWN
)
59 tor_assert(msg_len
<= UINT_MAX
);
63 PK11Context
*ctx
= PK11_CreateDigestContext(alg
);
67 s
= PK11_DigestBegin(ctx
);
71 s
= PK11_DigestOp(ctx
, (const unsigned char *)msg
, (unsigned int)msg_len
);
76 s
= PK11_DigestFinal(ctx
, (unsigned char *)digest
, &len
, len_out
);
82 PK11_DestroyContext(ctx
, PR_TRUE
);
86 /** True iff alg is implemented in our crypto library, and we want to use that
89 library_supports_digest(digest_algorithm_t alg
)
92 case DIGEST_SHA1
: FALLTHROUGH
;
93 case DIGEST_SHA256
: FALLTHROUGH
;
96 case DIGEST_SHA3_256
: FALLTHROUGH
;
97 case DIGEST_SHA3_512
: FALLTHROUGH
;
103 /* Crypto digest functions */
105 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
106 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
107 * Return 0 on success, -1 on failure.
110 crypto_digest
,(char *digest
, const char *m
, size_t len
))
114 return digest_nss_internal(SEC_OID_SHA1
, digest
, DIGEST_LEN
, m
, len
);
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. */
121 crypto_digest256(char *digest
, const char *m
, size_t len
,
122 digest_algorithm_t algorithm
)
126 tor_assert(algorithm
== DIGEST_SHA256
|| algorithm
== DIGEST_SHA3_256
);
129 if (algorithm
== DIGEST_SHA256
) {
130 return digest_nss_internal(SEC_OID_SHA256
, digest
, DIGEST256_LEN
, m
, len
);
132 ret
= (sha3_256((uint8_t *)digest
, DIGEST256_LEN
,(const uint8_t *)m
, len
)
141 /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
142 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
143 * into <b>digest</b>. Return 0 on success, -1 on failure. */
145 crypto_digest512(char *digest
, const char *m
, size_t len
,
146 digest_algorithm_t algorithm
)
150 tor_assert(algorithm
== DIGEST_SHA512
|| algorithm
== DIGEST_SHA3_512
);
153 if (algorithm
== DIGEST_SHA512
) {
154 return digest_nss_internal(SEC_OID_SHA512
, digest
, DIGEST512_LEN
, m
, len
);
156 ret
= (sha3_512((uint8_t*)digest
, DIGEST512_LEN
, (const uint8_t*)m
, len
)
165 /** Intermediate information about the digest of a stream of data. */
166 struct crypto_digest_t
{
167 digest_algorithm_t algorithm
; /**< Which algorithm is in use? */
168 /** State for the digest we're using. Only one member of the
169 * union is usable, depending on the value of <b>algorithm</b>. Note also
170 * that space for other members might not even be allocated!
174 keccak_state sha3
; /**< state for SHA3-[256,512] */
178 #ifdef TOR_UNIT_TESTS
181 crypto_digest_get_algorithm(crypto_digest_t
*digest
)
185 return digest
->algorithm
;
188 #endif /* defined(TOR_UNIT_TESTS) */
191 * Return the number of bytes we need to malloc in order to get a
192 * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
196 crypto_digest_alloc_bytes(digest_algorithm_t alg
)
198 /* Helper: returns the number of bytes in the 'f' field of 'st' */
199 #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
200 /* Gives the length of crypto_digest_t through the end of the field 'd' */
201 #define END_OF_FIELD(f) (offsetof(crypto_digest_t, f) + \
202 STRUCT_FIELD_SIZE(crypto_digest_t, f))
204 case DIGEST_SHA1
: FALLTHROUGH
;
205 case DIGEST_SHA256
: FALLTHROUGH
;
207 return END_OF_FIELD(d
.ctx
);
208 case DIGEST_SHA3_256
:
209 case DIGEST_SHA3_512
:
210 return END_OF_FIELD(d
.sha3
);
212 tor_assert(0); // LCOV_EXCL_LINE
213 return 0; // LCOV_EXCL_LINE
216 #undef STRUCT_FIELD_SIZE
220 * Internal function: create and return a new digest object for 'algorithm'.
221 * Does not typecheck the algorithm.
223 static crypto_digest_t
*
224 crypto_digest_new_internal(digest_algorithm_t algorithm
)
226 crypto_digest_t
*r
= tor_malloc(crypto_digest_alloc_bytes(algorithm
));
227 r
->algorithm
= algorithm
;
231 case DIGEST_SHA1
: FALLTHROUGH
;
232 case DIGEST_SHA256
: FALLTHROUGH
;
234 r
->d
.ctx
= PK11_CreateDigestContext(digest_alg_to_nss_oid(algorithm
));
235 if (BUG(!r
->d
.ctx
)) {
239 if (BUG(SECSuccess
!= PK11_DigestBegin(r
->d
.ctx
))) {
240 crypto_digest_free(r
);
244 case DIGEST_SHA3_256
:
245 keccak_digest_init(&r
->d
.sha3
, 256);
247 case DIGEST_SHA3_512
:
248 keccak_digest_init(&r
->d
.sha3
, 512);
251 tor_assert_unreached();
257 /** Allocate and return a new digest object to compute SHA1 digests.
260 crypto_digest_new(void)
262 return crypto_digest_new_internal(DIGEST_SHA1
);
265 /** Allocate and return a new digest object to compute 256-bit digests
266 * using <b>algorithm</b>.
268 * C_RUST_COUPLED: `external::crypto_digest::crypto_digest256_new`
269 * C_RUST_COUPLED: `crypto::digest::Sha256::default`
272 crypto_digest256_new(digest_algorithm_t algorithm
)
274 tor_assert(algorithm
== DIGEST_SHA256
|| algorithm
== DIGEST_SHA3_256
);
275 return crypto_digest_new_internal(algorithm
);
278 /** Allocate and return a new digest object to compute 512-bit digests
279 * using <b>algorithm</b>. */
281 crypto_digest512_new(digest_algorithm_t algorithm
)
283 tor_assert(algorithm
== DIGEST_SHA512
|| algorithm
== DIGEST_SHA3_512
);
284 return crypto_digest_new_internal(algorithm
);
287 /** Deallocate a digest object.
290 crypto_digest_free_(crypto_digest_t
*digest
)
294 if (library_supports_digest(digest
->algorithm
)) {
295 PK11_DestroyContext(digest
->d
.ctx
, PR_TRUE
);
297 size_t bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
298 memwipe(digest
, 0, bytes
);
302 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
304 * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_add_bytess`
305 * C_RUST_COUPLED: `crypto::digest::Sha256::process`
308 crypto_digest_add_bytes(crypto_digest_t
*digest
, const char *data
,
313 /* Using the SHA*_*() calls directly means we don't support doing
314 * SHA in hardware. But so far the delay of getting the question
315 * to the hardware, and hearing the answer, is likely higher than
316 * just doing it ourselves. Hashes are fast.
318 switch (digest
->algorithm
) {
319 case DIGEST_SHA1
: FALLTHROUGH
;
320 case DIGEST_SHA256
: FALLTHROUGH
;
322 tor_assert(len
<= UINT_MAX
);
323 SECStatus s
= PK11_DigestOp(digest
->d
.ctx
,
324 (const unsigned char *)data
,
326 tor_assert(s
== SECSuccess
);
328 case DIGEST_SHA3_256
: FALLTHROUGH
;
329 case DIGEST_SHA3_512
:
330 keccak_digest_update(&digest
->d
.sha3
, (const uint8_t *)data
, len
);
333 /* LCOV_EXCL_START */
334 tor_fragile_assert();
340 /** Compute the hash of the data that has been passed to the digest
341 * object; write the first out_len bytes of the result to <b>out</b>.
342 * <b>out_len</b> must be \<= DIGEST512_LEN.
344 * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_get_digest`
345 * C_RUST_COUPLED: `impl digest::FixedOutput for Sha256`
348 crypto_digest_get_digest(crypto_digest_t
*digest
,
349 char *out
, size_t out_len
)
351 unsigned char r
[DIGEST512_LEN
];
354 tor_assert(out_len
<= crypto_digest_algorithm_get_length(digest
->algorithm
));
356 /* The SHA-3 code handles copying into a temporary ctx, and also can handle
357 * short output buffers by truncating appropriately. */
358 if (digest
->algorithm
== DIGEST_SHA3_256
||
359 digest
->algorithm
== DIGEST_SHA3_512
) {
360 keccak_digest_sum(&digest
->d
.sha3
, (uint8_t *)out
, out_len
);
364 /* Copy into a temporary buffer since DigestFinal (alters) the context */
365 unsigned char buf
[1024];
366 unsigned int saved_len
= 0;
368 unsigned char *saved
= PK11_SaveContextAlloc(digest
->d
.ctx
,
372 SECStatus s
= PK11_DigestFinal(digest
->d
.ctx
, r
, &rlen
, sizeof(r
));
373 tor_assert(s
== SECSuccess
);
374 tor_assert(rlen
>= out_len
);
375 s
= PK11_RestoreContext(digest
->d
.ctx
, saved
, saved_len
);
376 tor_assert(s
== SECSuccess
);
379 PORT_ZFree(saved
, saved_len
);
381 memcpy(out
, r
, out_len
);
382 memwipe(r
, 0, sizeof(r
));
385 /** Allocate and return a new digest object with the same state as
388 * C_RUST_COUPLED: `external::crypto_digest::crypto_digest_dup`
389 * C_RUST_COUPLED: `impl Clone for crypto::digest::Sha256`
392 crypto_digest_dup(const crypto_digest_t
*digest
)
395 const size_t alloc_bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
396 crypto_digest_t
*result
= tor_memdup(digest
, alloc_bytes
);
398 if (library_supports_digest(digest
->algorithm
)) {
399 result
->d
.ctx
= PK11_CloneContext(digest
->d
.ctx
);
405 /** Temporarily save the state of <b>digest</b> in <b>checkpoint</b>.
406 * Asserts that <b>digest</b> is a SHA1 digest object.
409 crypto_digest_checkpoint(crypto_digest_checkpoint_t
*checkpoint
,
410 const crypto_digest_t
*digest
)
412 const size_t bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
413 tor_assert(bytes
<= sizeof(checkpoint
->mem
));
414 if (library_supports_digest(digest
->algorithm
)) {
415 unsigned char *allocated
;
416 allocated
= PK11_SaveContextAlloc(digest
->d
.ctx
,
417 (unsigned char *)checkpoint
->mem
,
418 sizeof(checkpoint
->mem
),
419 &checkpoint
->bytes_used
);
420 /* No allocation is allowed here. */
421 tor_assert(allocated
== checkpoint
->mem
);
424 memcpy(checkpoint
->mem
, digest
, bytes
);
427 /** Restore the state of <b>digest</b> from <b>checkpoint</b>.
428 * Asserts that <b>digest</b> is a SHA1 digest object. Requires that the
429 * state was previously stored with crypto_digest_checkpoint() */
431 crypto_digest_restore(crypto_digest_t
*digest
,
432 const crypto_digest_checkpoint_t
*checkpoint
)
434 const size_t bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
435 if (library_supports_digest(digest
->algorithm
)) {
436 SECStatus s
= PK11_RestoreContext(digest
->d
.ctx
,
437 (unsigned char *)checkpoint
->mem
,
438 checkpoint
->bytes_used
);
439 tor_assert(s
== SECSuccess
);
442 memcpy(digest
, checkpoint
->mem
, bytes
);
445 /** Replace the state of the digest object <b>into</b> with the state
446 * of the digest object <b>from</b>. Requires that 'into' and 'from'
447 * have the same digest type.
450 crypto_digest_assign(crypto_digest_t
*into
,
451 const crypto_digest_t
*from
)
455 tor_assert(into
->algorithm
== from
->algorithm
);
456 const size_t alloc_bytes
= crypto_digest_alloc_bytes(from
->algorithm
);
457 if (library_supports_digest(from
->algorithm
)) {
458 PK11_DestroyContext(into
->d
.ctx
, PR_TRUE
);
459 into
->d
.ctx
= PK11_CloneContext(from
->d
.ctx
);
462 memcpy(into
,from
,alloc_bytes
);
465 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
466 * at <b>digest_out</b> to the hash of the concatenation of those strings,
467 * plus the optional string <b>append</b>, computed with the algorithm
469 * <b>out_len</b> must be \<= DIGEST512_LEN. */
471 crypto_digest_smartlist(char *digest_out
, size_t len_out
,
472 const smartlist_t
*lst
,
474 digest_algorithm_t alg
)
476 crypto_digest_smartlist_prefix(digest_out
, len_out
, NULL
, lst
, append
, alg
);
479 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
480 * at <b>digest_out</b> to the hash of the concatenation of: the
481 * optional string <b>prepend</b>, those strings,
482 * and the optional string <b>append</b>, computed with the algorithm
484 * <b>len_out</b> must be \<= DIGEST512_LEN. */
486 crypto_digest_smartlist_prefix(char *digest_out
, size_t len_out
,
488 const smartlist_t
*lst
,
490 digest_algorithm_t alg
)
492 crypto_digest_t
*d
= crypto_digest_new_internal(alg
);
494 crypto_digest_add_bytes(d
, prepend
, strlen(prepend
));
495 SMARTLIST_FOREACH(lst
, const char *, cp
,
496 crypto_digest_add_bytes(d
, cp
, strlen(cp
)));
498 crypto_digest_add_bytes(d
, append
, strlen(append
));
499 crypto_digest_get_digest(d
, digest_out
, len_out
);
500 crypto_digest_free(d
);
503 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
504 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
505 * result in <b>hmac_out</b>. Asserts on failure.
508 crypto_hmac_sha256(char *hmac_out
,
509 const char *key
, size_t key_len
,
510 const char *msg
, size_t msg_len
)
512 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
513 tor_assert(key_len
< INT_MAX
);
514 tor_assert(msg_len
< INT_MAX
);
515 tor_assert(hmac_out
);
517 PK11SlotInfo
*slot
= NULL
;
518 PK11SymKey
*symKey
= NULL
;
519 PK11Context
*hmac
= NULL
;
523 SECItem keyItem
, paramItem
;
524 keyItem
.data
= (unsigned char *)key
;
525 keyItem
.len
= (unsigned)key_len
;
526 paramItem
.type
= siBuffer
;
527 paramItem
.data
= NULL
;
530 slot
= PK11_GetBestSlot(CKM_SHA256_HMAC
, NULL
);
533 symKey
= PK11_ImportSymKey(slot
, CKM_SHA256_HMAC
,
534 PK11_OriginUnwrap
, CKA_SIGN
, &keyItem
, NULL
);
538 hmac
= PK11_CreateContextBySymKey(CKM_SHA256_HMAC
, CKA_SIGN
, symKey
,
542 s
= PK11_DigestBegin(hmac
);
545 s
= PK11_DigestOp(hmac
, (const unsigned char *)msg
, (unsigned int)msg_len
);
549 s
= PK11_DigestFinal(hmac
, (unsigned char *)hmac_out
, &len
, DIGEST256_LEN
);
550 if (s
!= SECSuccess
|| len
!= DIGEST256_LEN
)
556 PK11_DestroyContext(hmac
, PR_TRUE
);
558 PK11_FreeSymKey(symKey
);