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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL and
20 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
21 * use either definition. */
25 #define CRYPTO_PRIVATE
27 #include "compat_openssl.h"
28 #include "crypto_curve25519.h"
29 #include "crypto_ed25519.h"
30 #include "crypto_format.h"
32 #include <openssl/err.h>
33 #include <openssl/rsa.h>
34 #include <openssl/pem.h>
35 #include <openssl/evp.h>
36 #include <openssl/engine.h>
37 #include <openssl/rand.h>
38 #include <openssl/bn.h>
39 #include <openssl/dh.h>
40 #include <openssl/conf.h>
41 #include <openssl/hmac.h>
53 #ifdef HAVE_SYS_FCNTL_H
54 #include <sys/fcntl.h>
56 #ifdef HAVE_SYS_SYSCALL_H
57 #include <sys/syscall.h>
63 #include "container.h"
66 #include "util_format.h"
68 #include "keccak-tiny/keccak-tiny.h"
71 /* Android's OpenSSL seems to have removed all of its Engine support. */
72 #define DISABLE_ENGINES
75 #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,4) && \
76 !defined(LIBRESSL_VERSION_NUMBER)
77 /* OpenSSL as of 1.1.0-pre4 has an "new" thread API, which doesn't require
78 * seting up various callbacks.
80 * Note: Yes, using OPENSSL_VER is naughty, but this was introduced in the
83 #define NEW_THREAD_API
86 /** Longest recognized */
87 #define MAX_DNS_LABEL_SIZE 63
89 /** Largest strong entropy request */
90 #define MAX_STRONGEST_RAND_SIZE 256
92 /** Macro: is k a valid RSA public or private key? */
93 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
94 /** Macro: is k a valid RSA private key? */
95 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
97 #ifndef NEW_THREAD_API
98 /** A number of preallocated mutexes for use by OpenSSL. */
99 static tor_mutex_t
**openssl_mutexes_
= NULL
;
100 /** How many mutexes have we allocated for use by OpenSSL? */
101 static int n_openssl_mutexes_
= 0;
104 /** A public key, or a public/private key-pair. */
107 int refs
; /**< reference count, so we don't have to copy keys */
108 RSA
*key
; /**< The key itself */
111 /** Key and stream information for a stream cipher. */
112 struct crypto_cipher_t
114 char key
[CIPHER_KEY_LEN
]; /**< The raw key. */
115 char iv
[CIPHER_IV_LEN
]; /**< The initial IV. */
116 aes_cnt_cipher_t
*cipher
; /**< The key in format usable for counter-mode AES
120 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
121 * while we're waiting for the second.*/
123 DH
*dh
; /**< The openssl DH object */
126 static int setup_openssl_threading(void);
127 static int tor_check_dh_key(int severity
, BIGNUM
*bn
);
129 /** Return the number of bytes added by padding method <b>padding</b>.
132 crypto_get_rsa_padding_overhead(int padding
)
136 case RSA_PKCS1_OAEP_PADDING
: return PKCS1_OAEP_PADDING_OVERHEAD
;
137 default: tor_assert(0); return -1;
141 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
144 crypto_get_rsa_padding(int padding
)
148 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
149 default: tor_assert(0); return -1;
153 /** Boolean: has OpenSSL's crypto been initialized? */
154 static int crypto_early_initialized_
= 0;
156 /** Boolean: has OpenSSL's crypto been initialized? */
157 static int crypto_global_initialized_
= 0;
159 /** Log all pending crypto errors at level <b>severity</b>. Use
160 * <b>doing</b> to describe our current activities.
163 crypto_log_errors(int severity
, const char *doing
)
166 const char *msg
, *lib
, *func
;
167 while ((err
= ERR_get_error()) != 0) {
168 msg
= (const char*)ERR_reason_error_string(err
);
169 lib
= (const char*)ERR_lib_error_string(err
);
170 func
= (const char*)ERR_func_error_string(err
);
171 if (!msg
) msg
= "(null)";
172 if (!lib
) lib
= "(null)";
173 if (!func
) func
= "(null)";
175 tor_log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
176 doing
, msg
, lib
, func
);
178 tor_log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)",
184 #ifndef DISABLE_ENGINES
185 /** Log any OpenSSL engines we're using at NOTICE. */
187 log_engine(const char *fn
, ENGINE
*e
)
190 const char *name
, *id
;
191 name
= ENGINE_get_name(e
);
192 id
= ENGINE_get_id(e
);
193 log_notice(LD_CRYPTO
, "Default OpenSSL engine for %s is %s [%s]",
194 fn
, name
?name
:"?", id
?id
:"?");
196 log_info(LD_CRYPTO
, "Using default implementation for %s", fn
);
201 #ifndef DISABLE_ENGINES
202 /** Try to load an engine in a shared library via fully qualified path.
205 try_load_engine(const char *path
, const char *engine
)
207 ENGINE
*e
= ENGINE_by_id("dynamic");
209 if (!ENGINE_ctrl_cmd_string(e
, "ID", engine
, 0) ||
210 !ENGINE_ctrl_cmd_string(e
, "DIR_LOAD", "2", 0) ||
211 !ENGINE_ctrl_cmd_string(e
, "DIR_ADD", path
, 0) ||
212 !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
221 /* Returns a trimmed and human-readable version of an openssl version string
222 * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
223 * May 2012' and this will parse them into a form similar to '1.0.0b' */
225 parse_openssl_version_str(const char *raw_version
)
227 const char *end_of_version
= NULL
;
228 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
230 if (!strcmpstart(raw_version
, "OpenSSL ")) {
231 raw_version
+= strlen("OpenSSL ");
232 end_of_version
= strchr(raw_version
, ' ');
236 return tor_strndup(raw_version
,
237 end_of_version
-raw_version
);
239 return tor_strdup(raw_version
);
242 static char *crypto_openssl_version_str
= NULL
;
243 /* Return a human-readable version of the run-time openssl version number. */
245 crypto_openssl_get_version_str(void)
247 if (crypto_openssl_version_str
== NULL
) {
248 const char *raw_version
= OpenSSL_version(OPENSSL_VERSION
);
249 crypto_openssl_version_str
= parse_openssl_version_str(raw_version
);
251 return crypto_openssl_version_str
;
254 static char *crypto_openssl_header_version_str
= NULL
;
255 /* Return a human-readable version of the compile-time openssl version
258 crypto_openssl_get_header_version_str(void)
260 if (crypto_openssl_header_version_str
== NULL
) {
261 crypto_openssl_header_version_str
=
262 parse_openssl_version_str(OPENSSL_VERSION_TEXT
);
264 return crypto_openssl_header_version_str
;
267 /** Make sure that openssl is using its default PRNG. Return 1 if we had to
268 * adjust it; 0 otherwise. */
270 crypto_force_rand_ssleay(void)
272 RAND_METHOD
*default_method
;
273 default_method
= RAND_OpenSSL();
274 if (RAND_get_rand_method() != default_method
) {
275 log_notice(LD_CRYPTO
, "It appears that one of our engines has provided "
276 "a replacement the OpenSSL RNG. Resetting it to the default "
278 RAND_set_rand_method(default_method
);
284 /** Set up the siphash key if we haven't already done so. */
286 crypto_init_siphash_key(void)
288 static int have_seeded_siphash
= 0;
290 if (have_seeded_siphash
)
293 crypto_rand((char*) &key
, sizeof(key
));
294 siphash_set_global_key(&key
);
295 have_seeded_siphash
= 1;
299 /** Initialize the crypto library. Return 0 on success, -1 on failure.
302 crypto_early_init(void)
304 if (!crypto_early_initialized_
) {
306 crypto_early_initialized_
= 1;
308 ERR_load_crypto_strings();
309 OpenSSL_add_all_algorithms();
311 setup_openssl_threading();
313 unsigned long version_num
= OpenSSL_version_num();
314 const char *version_str
= OpenSSL_version(OPENSSL_VERSION
);
315 if (version_num
== OPENSSL_VERSION_NUMBER
&&
316 !strcmp(version_str
, OPENSSL_VERSION_TEXT
)) {
317 log_info(LD_CRYPTO
, "OpenSSL version matches version from headers "
318 "(%lx: %s).", version_num
, version_str
);
320 log_warn(LD_CRYPTO
, "OpenSSL version from headers does not match the "
321 "version we're running with. If you get weird crashes, that "
322 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
323 (unsigned long)OPENSSL_VERSION_NUMBER
, OPENSSL_VERSION_TEXT
,
324 version_num
, version_str
);
327 crypto_force_rand_ssleay();
329 if (crypto_seed_rng() < 0)
331 if (crypto_init_siphash_key() < 0)
340 /** Initialize the crypto library. Return 0 on success, -1 on failure.
343 crypto_global_init(int useAccel
, const char *accelName
, const char *accelDir
)
345 if (!crypto_global_initialized_
) {
346 if (crypto_early_init() < 0)
349 crypto_global_initialized_
= 1;
352 #ifdef DISABLE_ENGINES
355 log_warn(LD_CRYPTO
, "No OpenSSL hardware acceleration support enabled.");
359 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
360 ENGINE_load_builtin_engines();
361 ENGINE_register_all_complete();
365 log_info(LD_CRYPTO
, "Trying to load dynamic OpenSSL engine \"%s\""
366 " via path \"%s\".", accelName
, accelDir
);
367 e
= try_load_engine(accelName
, accelDir
);
369 log_info(LD_CRYPTO
, "Initializing dynamic OpenSSL engine \"%s\""
370 " acceleration support.", accelName
);
371 e
= ENGINE_by_id(accelName
);
374 log_warn(LD_CRYPTO
, "Unable to load dynamic OpenSSL engine \"%s\".",
377 log_info(LD_CRYPTO
, "Loaded dynamic OpenSSL engine \"%s\".",
382 log_info(LD_CRYPTO
, "Loaded OpenSSL hardware acceleration engine,"
383 " setting default ciphers.");
384 ENGINE_set_default(e
, ENGINE_METHOD_ALL
);
386 /* Log, if available, the intersection of the set of algorithms
387 used by Tor and the set of algorithms available in the engine */
388 log_engine("RSA", ENGINE_get_default_RSA());
389 log_engine("DH", ENGINE_get_default_DH());
390 #ifdef OPENSSL_1_1_API
391 log_engine("EC", ENGINE_get_default_EC());
393 log_engine("ECDH", ENGINE_get_default_ECDH());
394 log_engine("ECDSA", ENGINE_get_default_ECDSA());
396 log_engine("RAND", ENGINE_get_default_RAND());
397 log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
398 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
399 log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc
));
400 log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
401 log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc
));
402 #ifdef NID_aes_128_ctr
403 log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr
));
405 #ifdef NID_aes_128_gcm
406 log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm
));
408 log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc
));
409 #ifdef NID_aes_256_gcm
410 log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm
));
415 log_info(LD_CRYPTO
, "NOT using OpenSSL engine support.");
418 if (crypto_force_rand_ssleay()) {
419 if (crypto_seed_rng() < 0)
423 evaluate_evp_for_aes(-1);
424 evaluate_ctr_for_aes();
429 /** Free crypto resources held by this thread. */
431 crypto_thread_cleanup(void)
433 #ifdef NEW_THREAD_API
434 ERR_remove_thread_state();
436 ERR_remove_thread_state(NULL
);
440 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
442 crypto_new_pk_from_rsa_(RSA
*rsa
)
446 env
= tor_malloc(sizeof(crypto_pk_t
));
452 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
455 crypto_pk_get_rsa_(crypto_pk_t
*env
)
460 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
461 * private is set, include the private-key portion of the key. Return a valid
462 * pointer on success, and NULL on failure. */
463 MOCK_IMPL(EVP_PKEY
*,
464 crypto_pk_get_evp_pkey_
,(crypto_pk_t
*env
, int private))
467 EVP_PKEY
*pkey
= NULL
;
468 tor_assert(env
->key
);
470 if (!(key
= RSAPrivateKey_dup(env
->key
)))
473 if (!(key
= RSAPublicKey_dup(env
->key
)))
476 if (!(pkey
= EVP_PKEY_new()))
478 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
489 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
492 crypto_dh_get_dh_(crypto_dh_t
*dh
)
497 /** Allocate and return storage for a public key. The key itself will not yet
500 MOCK_IMPL(crypto_pk_t
*,
501 crypto_pk_new
,(void))
507 return crypto_new_pk_from_rsa_(rsa
);
510 /** Release a reference to an asymmetric key; when all the references
511 * are released, free the key.
514 crypto_pk_free(crypto_pk_t
*env
)
521 tor_assert(env
->refs
== 0);
529 /** Allocate and return a new symmetric cipher using the provided key and iv.
530 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
531 * provide NULL in place of either one, it is generated at random.
534 crypto_cipher_new_with_iv(const char *key
, const char *iv
)
536 crypto_cipher_t
*env
;
538 env
= tor_malloc_zero(sizeof(crypto_cipher_t
));
541 crypto_rand(env
->key
, CIPHER_KEY_LEN
);
543 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
545 crypto_rand(env
->iv
, CIPHER_IV_LEN
);
547 memcpy(env
->iv
, iv
, CIPHER_IV_LEN
);
549 env
->cipher
= aes_new_cipher(env
->key
, env
->iv
);
554 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
557 crypto_cipher_new(const char *key
)
559 char zeroiv
[CIPHER_IV_LEN
];
560 memset(zeroiv
, 0, sizeof(zeroiv
));
561 return crypto_cipher_new_with_iv(key
, zeroiv
);
564 /** Free a symmetric cipher.
567 crypto_cipher_free(crypto_cipher_t
*env
)
572 tor_assert(env
->cipher
);
573 aes_cipher_free(env
->cipher
);
574 memwipe(env
, 0, sizeof(crypto_cipher_t
));
578 /* public key crypto */
580 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
581 * Return 0 on success, -1 on failure.
584 crypto_pk_generate_key_with_bits
,(crypto_pk_t
*env
, int bits
))
594 BIGNUM
*e
= BN_new();
598 if (! BN_set_word(e
, 65537))
603 if (RSA_generate_key_ex(r
, bits
, e
, NULL
) == -1)
616 crypto_log_errors(LOG_WARN
, "generating RSA key");
623 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
624 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
625 * the string is nul-terminated.
627 /* Used here, and used for testing. */
629 crypto_pk_read_private_key_from_string(crypto_pk_t
*env
,
630 const char *s
, ssize_t len
)
636 tor_assert(len
< INT_MAX
&& len
< SSIZE_T_CEILING
);
638 /* Create a read-only memory BIO, backed by the string 's' */
639 b
= BIO_new_mem_buf((char*)s
, (int)len
);
646 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
651 crypto_log_errors(LOG_WARN
, "Error parsing private key");
657 /** Read a PEM-encoded private key from the file named by
658 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
661 crypto_pk_read_private_key_from_filename(crypto_pk_t
*env
,
667 /* Read the file into a string. */
668 contents
= read_file_to_str(keyfile
, 0, NULL
);
670 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
674 /* Try to parse it. */
675 r
= crypto_pk_read_private_key_from_string(env
, contents
, -1);
676 memwipe(contents
, 0, strlen(contents
));
679 return -1; /* read_private_key_from_string already warned, so we don't.*/
681 /* Make sure it's valid. */
682 if (crypto_pk_check_key(env
) <= 0)
688 /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
689 * success, -1 on failure. */
691 crypto_pk_write_key_to_string_impl(crypto_pk_t
*env
, char **dest
,
692 size_t *len
, int is_public
)
699 tor_assert(env
->key
);
702 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
706 /* Now you can treat b as if it were a file. Just use the
707 * PEM_*_bio_* functions instead of the non-bio variants.
710 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
712 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
715 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
720 BIO_get_mem_ptr(b
, &buf
);
721 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
724 *dest
= tor_malloc(buf
->length
+1);
725 memcpy(*dest
, buf
->data
, buf
->length
);
726 (*dest
)[buf
->length
] = 0; /* nul terminate it */
733 /** PEM-encode the public key portion of <b>env</b> and write it to a
734 * newly allocated string. On success, set *<b>dest</b> to the new
735 * string, *<b>len</b> to the string's length, and return 0. On
736 * failure, return -1.
739 crypto_pk_write_public_key_to_string(crypto_pk_t
*env
, char **dest
,
742 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
745 /** PEM-encode the private key portion of <b>env</b> and write it to a
746 * newly allocated string. On success, set *<b>dest</b> to the new
747 * string, *<b>len</b> to the string's length, and return 0. On
748 * failure, return -1.
751 crypto_pk_write_private_key_to_string(crypto_pk_t
*env
, char **dest
,
754 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
757 /** Read a PEM-encoded public key from the first <b>len</b> characters of
758 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
762 crypto_pk_read_public_key_from_string(crypto_pk_t
*env
, const char *src
,
769 tor_assert(len
<INT_MAX
);
771 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
775 BIO_write(b
, src
, (int)len
);
779 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
782 crypto_log_errors(LOG_WARN
, "reading public key from string");
789 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
790 * PEM-encoded. Return 0 on success, -1 on failure.
793 crypto_pk_write_private_key_to_filename(crypto_pk_t
*env
,
802 tor_assert(PRIVATE_KEY_OK(env
));
804 if (!(bio
= BIO_new(BIO_s_mem())))
806 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
808 crypto_log_errors(LOG_WARN
, "writing private key");
812 len
= BIO_get_mem_data(bio
, &cp
);
813 tor_assert(len
>= 0);
814 s
= tor_malloc(len
+1);
817 r
= write_str_to_file(fname
, s
, 0);
819 memwipe(s
, 0, strlen(s
));
824 /** Return true iff <b>env</b> has a valid key.
827 crypto_pk_check_key(crypto_pk_t
*env
)
832 r
= RSA_check_key(env
->key
);
834 crypto_log_errors(LOG_WARN
,"checking RSA key");
838 /** Return true iff <b>key</b> contains the private-key portion of the RSA
841 crypto_pk_key_is_private(const crypto_pk_t
*key
)
844 return PRIVATE_KEY_OK(key
);
847 /** Return true iff <b>env</b> contains a public key whose public exponent
851 crypto_pk_public_exponent_ok(crypto_pk_t
*env
)
854 tor_assert(env
->key
);
856 return BN_is_word(env
->key
->e
, 65537);
859 /** Compare the public-key components of a and b. Return less than 0
860 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
861 * considered to be less than all non-NULL keys, and equal to itself.
863 * Note that this may leak information about the keys through timing.
866 crypto_pk_cmp_keys(const crypto_pk_t
*a
, const crypto_pk_t
*b
)
869 char a_is_non_null
= (a
!= NULL
) && (a
->key
!= NULL
);
870 char b_is_non_null
= (b
!= NULL
) && (b
->key
!= NULL
);
871 char an_argument_is_null
= !a_is_non_null
| !b_is_non_null
;
873 result
= tor_memcmp(&a_is_non_null
, &b_is_non_null
, sizeof(a_is_non_null
));
874 if (an_argument_is_null
)
877 tor_assert(PUBLIC_KEY_OK(a
));
878 tor_assert(PUBLIC_KEY_OK(b
));
879 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
882 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
885 /** Compare the public-key components of a and b. Return non-zero iff
886 * a==b. A NULL key is considered to be distinct from all non-NULL
887 * keys, and equal to itself.
889 * Note that this may leak information about the keys through timing.
892 crypto_pk_eq_keys(const crypto_pk_t
*a
, const crypto_pk_t
*b
)
894 return (crypto_pk_cmp_keys(a
, b
) == 0);
897 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
899 crypto_pk_keysize(const crypto_pk_t
*env
)
902 tor_assert(env
->key
);
904 return (size_t) RSA_size((RSA
*)env
->key
);
907 /** Return the size of the public key modulus of <b>env</b>, in bits. */
909 crypto_pk_num_bits(crypto_pk_t
*env
)
912 tor_assert(env
->key
);
913 tor_assert(env
->key
->n
);
915 return BN_num_bits(env
->key
->n
);
918 /** Increase the reference count of <b>env</b>, and return it.
921 crypto_pk_dup_key(crypto_pk_t
*env
)
924 tor_assert(env
->key
);
930 /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
931 * Returns NULL on failure. */
933 crypto_pk_copy_full(crypto_pk_t
*env
)
938 tor_assert(env
->key
);
940 if (PRIVATE_KEY_OK(env
)) {
941 new_key
= RSAPrivateKey_dup(env
->key
);
944 new_key
= RSAPublicKey_dup(env
->key
);
947 log_err(LD_CRYPTO
, "Unable to duplicate a %s key: openssl failed.",
948 privatekey
?"private":"public");
949 crypto_log_errors(LOG_ERR
,
950 privatekey
? "Duplicating a private key" :
951 "Duplicating a public key");
952 tor_fragile_assert();
956 return crypto_new_pk_from_rsa_(new_key
);
959 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
960 * in <b>env</b>, using the padding method <b>padding</b>. On success,
961 * write the result to <b>to</b>, and return the number of bytes
962 * written. On failure, return -1.
964 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
965 * at least the length of the modulus of <b>env</b>.
968 crypto_pk_public_encrypt(crypto_pk_t
*env
, char *to
, size_t tolen
,
969 const char *from
, size_t fromlen
, int padding
)
975 tor_assert(fromlen
<INT_MAX
);
976 tor_assert(tolen
>= crypto_pk_keysize(env
));
978 r
= RSA_public_encrypt((int)fromlen
,
979 (unsigned char*)from
, (unsigned char*)to
,
980 env
->key
, crypto_get_rsa_padding(padding
));
982 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
988 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
989 * in <b>env</b>, using the padding method <b>padding</b>. On success,
990 * write the result to <b>to</b>, and return the number of bytes
991 * written. On failure, return -1.
993 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
994 * at least the length of the modulus of <b>env</b>.
997 crypto_pk_private_decrypt(crypto_pk_t
*env
, char *to
,
999 const char *from
, size_t fromlen
,
1000 int padding
, int warnOnFailure
)
1006 tor_assert(env
->key
);
1007 tor_assert(fromlen
<INT_MAX
);
1008 tor_assert(tolen
>= crypto_pk_keysize(env
));
1010 /* Not a private key */
1013 r
= RSA_private_decrypt((int)fromlen
,
1014 (unsigned char*)from
, (unsigned char*)to
,
1015 env
->key
, crypto_get_rsa_padding(padding
));
1018 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
1019 "performing RSA decryption");
1025 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
1026 * public key in <b>env</b>, using PKCS1 padding. On success, write the
1027 * signed data to <b>to</b>, and return the number of bytes written.
1028 * On failure, return -1.
1030 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1031 * at least the length of the modulus of <b>env</b>.
1034 crypto_pk_public_checksig(const crypto_pk_t
*env
, char *to
,
1036 const char *from
, size_t fromlen
)
1042 tor_assert(fromlen
< INT_MAX
);
1043 tor_assert(tolen
>= crypto_pk_keysize(env
));
1044 r
= RSA_public_decrypt((int)fromlen
,
1045 (unsigned char*)from
, (unsigned char*)to
,
1046 env
->key
, RSA_PKCS1_PADDING
);
1049 crypto_log_errors(LOG_INFO
, "checking RSA signature");
1055 /** Check a siglen-byte long signature at <b>sig</b> against
1056 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
1057 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
1058 * SHA1(data). Else return -1.
1061 crypto_pk_public_checksig_digest(crypto_pk_t
*env
, const char *data
,
1062 size_t datalen
, const char *sig
, size_t siglen
)
1064 char digest
[DIGEST_LEN
];
1072 tor_assert(datalen
< SIZE_T_CEILING
);
1073 tor_assert(siglen
< SIZE_T_CEILING
);
1075 if (crypto_digest(digest
,data
,datalen
)<0) {
1076 log_warn(LD_BUG
, "couldn't compute digest");
1079 buflen
= crypto_pk_keysize(env
);
1080 buf
= tor_malloc(buflen
);
1081 r
= crypto_pk_public_checksig(env
,buf
,buflen
,sig
,siglen
);
1082 if (r
!= DIGEST_LEN
) {
1083 log_warn(LD_CRYPTO
, "Invalid signature");
1087 if (tor_memneq(buf
, digest
, DIGEST_LEN
)) {
1088 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
1097 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
1098 * <b>env</b>, using PKCS1 padding. On success, write the signature to
1099 * <b>to</b>, and return the number of bytes written. On failure, return
1102 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1103 * at least the length of the modulus of <b>env</b>.
1106 crypto_pk_private_sign(const crypto_pk_t
*env
, char *to
, size_t tolen
,
1107 const char *from
, size_t fromlen
)
1113 tor_assert(fromlen
< INT_MAX
);
1114 tor_assert(tolen
>= crypto_pk_keysize(env
));
1116 /* Not a private key */
1119 r
= RSA_private_encrypt((int)fromlen
,
1120 (unsigned char*)from
, (unsigned char*)to
,
1121 (RSA
*)env
->key
, RSA_PKCS1_PADDING
);
1123 crypto_log_errors(LOG_WARN
, "generating RSA signature");
1129 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1130 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1131 * store it in <b>to</b>. Return the number of bytes written on
1132 * success, and -1 on failure.
1134 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1135 * at least the length of the modulus of <b>env</b>.
1138 crypto_pk_private_sign_digest(crypto_pk_t
*env
, char *to
, size_t tolen
,
1139 const char *from
, size_t fromlen
)
1142 char digest
[DIGEST_LEN
];
1143 if (crypto_digest(digest
,from
,fromlen
)<0)
1145 r
= crypto_pk_private_sign(env
,to
,tolen
,digest
,DIGEST_LEN
);
1146 memwipe(digest
, 0, sizeof(digest
));
1150 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1151 * bytes of data from <b>from</b>, with padding type 'padding',
1152 * storing the results on <b>to</b>.
1154 * Returns the number of bytes written on success, -1 on failure.
1156 * The encrypted data consists of:
1157 * - The source data, padded and encrypted with the public key, if the
1158 * padded source data is no longer than the public key, and <b>force</b>
1160 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1161 * padded and encrypted with the public key; followed by the rest of
1162 * the source data encrypted in AES-CTR mode with the symmetric key.
1165 crypto_pk_public_hybrid_encrypt(crypto_pk_t
*env
,
1166 char *to
, size_t tolen
,
1169 int padding
, int force
)
1171 int overhead
, outlen
, r
;
1172 size_t pkeylen
, symlen
;
1173 crypto_cipher_t
*cipher
= NULL
;
1179 tor_assert(fromlen
< SIZE_T_CEILING
);
1181 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
1182 pkeylen
= crypto_pk_keysize(env
);
1184 if (!force
&& fromlen
+overhead
<= pkeylen
) {
1185 /* It all fits in a single encrypt. */
1186 return crypto_pk_public_encrypt(env
,to
,
1188 from
,fromlen
,padding
);
1190 tor_assert(tolen
>= fromlen
+ overhead
+ CIPHER_KEY_LEN
);
1191 tor_assert(tolen
>= pkeylen
);
1193 cipher
= crypto_cipher_new(NULL
); /* generate a new key. */
1195 buf
= tor_malloc(pkeylen
+1);
1196 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
1197 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
1199 /* Length of symmetrically encrypted data. */
1200 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
1202 outlen
= crypto_pk_public_encrypt(env
,to
,tolen
,buf
,pkeylen
-overhead
,padding
);
1203 if (outlen
!=(int)pkeylen
) {
1206 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
1207 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
1210 memwipe(buf
, 0, pkeylen
);
1212 crypto_cipher_free(cipher
);
1213 tor_assert(outlen
+symlen
< INT_MAX
);
1214 return (int)(outlen
+ symlen
);
1217 memwipe(buf
, 0, pkeylen
);
1219 crypto_cipher_free(cipher
);
1223 /** Invert crypto_pk_public_hybrid_encrypt. Returns the number of bytes
1224 * written on success, -1 on failure. */
1226 crypto_pk_private_hybrid_decrypt(crypto_pk_t
*env
,
1231 int padding
, int warnOnFailure
)
1235 crypto_cipher_t
*cipher
= NULL
;
1238 tor_assert(fromlen
< SIZE_T_CEILING
);
1239 pkeylen
= crypto_pk_keysize(env
);
1241 if (fromlen
<= pkeylen
) {
1242 return crypto_pk_private_decrypt(env
,to
,tolen
,from
,fromlen
,padding
,
1246 buf
= tor_malloc(pkeylen
);
1247 outlen
= crypto_pk_private_decrypt(env
,buf
,pkeylen
,from
,pkeylen
,padding
,
1250 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
1251 "Error decrypting public-key data");
1254 if (outlen
< CIPHER_KEY_LEN
) {
1255 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1256 "No room for a symmetric key");
1259 cipher
= crypto_cipher_new(buf
);
1263 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1264 outlen
-= CIPHER_KEY_LEN
;
1265 tor_assert(tolen
- outlen
>= fromlen
- pkeylen
);
1266 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1269 memwipe(buf
,0,pkeylen
);
1271 crypto_cipher_free(cipher
);
1272 tor_assert(outlen
+ fromlen
< INT_MAX
);
1273 return (int)(outlen
+ (fromlen
-pkeylen
));
1275 memwipe(buf
,0,pkeylen
);
1277 crypto_cipher_free(cipher
);
1281 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1282 * Return -1 on error, or the number of characters used on success.
1285 crypto_pk_asn1_encode(crypto_pk_t
*pk
, char *dest
, size_t dest_len
)
1288 unsigned char *buf
= NULL
;
1290 len
= i2d_RSAPublicKey(pk
->key
, &buf
);
1291 if (len
< 0 || buf
== NULL
)
1294 if ((size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
) {
1298 /* We don't encode directly into 'dest', because that would be illegal
1299 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1301 memcpy(dest
,buf
,len
);
1306 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1307 * success and NULL on failure.
1310 crypto_pk_asn1_decode(const char *str
, size_t len
)
1314 const unsigned char *cp
;
1315 cp
= buf
= tor_malloc(len
);
1316 memcpy(buf
,str
,len
);
1317 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1320 crypto_log_errors(LOG_WARN
,"decoding public key");
1323 return crypto_new_pk_from_rsa_(rsa
);
1326 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1327 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1328 * Return 0 on success, -1 on failure.
1331 crypto_pk_get_digest(const crypto_pk_t
*pk
, char *digest_out
)
1333 unsigned char *buf
= NULL
;
1336 len
= i2d_RSAPublicKey((RSA
*)pk
->key
, &buf
);
1337 if (len
< 0 || buf
== NULL
)
1339 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1347 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1348 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1350 crypto_pk_get_common_digests(crypto_pk_t
*pk
, common_digests_t
*digests_out
)
1352 unsigned char *buf
= NULL
;
1355 len
= i2d_RSAPublicKey(pk
->key
, &buf
);
1356 if (len
< 0 || buf
== NULL
)
1358 if (crypto_common_digests(digests_out
, (char*)buf
, len
) < 0) {
1366 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1367 * every four characters. */
1369 crypto_add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1372 char *end
= out
+outlen
;
1373 tor_assert(outlen
< SIZE_T_CEILING
);
1375 while (*in
&& out
<end
) {
1377 if (++n
== 4 && *in
&& out
<end
) {
1382 tor_assert(out
<end
);
1386 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1387 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1388 * space). Return 0 on success, -1 on failure.
1390 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1391 * of the public key, converted to hexadecimal, in upper case, with a
1392 * space after every four digits.
1394 * If <b>add_space</b> is false, omit the spaces.
1397 crypto_pk_get_fingerprint(crypto_pk_t
*pk
, char *fp_out
, int add_space
)
1399 char digest
[DIGEST_LEN
];
1400 char hexdigest
[HEX_DIGEST_LEN
+1];
1401 if (crypto_pk_get_digest(pk
, digest
)) {
1404 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1406 crypto_add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1408 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1413 /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
1414 * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
1415 * bytes of space). Return 0 on success, -1 on failure.
1417 * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
1418 * of the ASN.1 encoding of the public key, converted to hexadecimal, in
1422 crypto_pk_get_hashed_fingerprint(crypto_pk_t
*pk
, char *fp_out
)
1424 char digest
[DIGEST_LEN
], hashed_digest
[DIGEST_LEN
];
1425 if (crypto_pk_get_digest(pk
, digest
)) {
1428 if (crypto_digest(hashed_digest
, digest
, DIGEST_LEN
)) {
1431 base16_encode(fp_out
, FINGERPRINT_LEN
+ 1, hashed_digest
, DIGEST_LEN
);
1435 /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
1436 * Base64 encoding of the DER representation of the private key as a NUL
1437 * terminated string, and return it via <b>priv_out</b>. Return 0 on
1438 * sucess, -1 on failure.
1440 * It is the caller's responsibility to sanitize and free the resulting buffer.
1443 crypto_pk_base64_encode(const crypto_pk_t
*pk
, char **priv_out
)
1445 unsigned char *der
= NULL
;
1451 der_len
= i2d_RSAPrivateKey(pk
->key
, &der
);
1452 if (der_len
< 0 || der
== NULL
)
1455 size_t priv_len
= base64_encode_size(der_len
, 0) + 1;
1456 char *priv
= tor_malloc_zero(priv_len
);
1457 if (base64_encode(priv
, priv_len
, (char *)der
, der_len
, 0) >= 0) {
1464 memwipe(der
, 0, der_len
);
1469 /** Given a string containing the Base64 encoded DER representation of the
1470 * private key <b>str</b>, decode and return the result on success, or NULL
1474 crypto_pk_base64_decode(const char *str
, size_t len
)
1476 crypto_pk_t
*pk
= NULL
;
1478 char *der
= tor_malloc_zero(len
+ 1);
1479 int der_len
= base64_decode(der
, len
, str
, len
);
1481 log_warn(LD_CRYPTO
, "Stored RSA private key seems corrupted (base64).");
1485 const unsigned char *dp
= (unsigned char*)der
; /* Shut the compiler up. */
1486 RSA
*rsa
= d2i_RSAPrivateKey(NULL
, &dp
, der_len
);
1488 crypto_log_errors(LOG_WARN
, "decoding private key");
1492 pk
= crypto_new_pk_from_rsa_(rsa
);
1494 /* Make sure it's valid. */
1495 if (crypto_pk_check_key(pk
) <= 0) {
1502 memwipe(der
, 0, len
+ 1);
1507 /* symmetric crypto */
1509 /** Return a pointer to the key set for the cipher in <b>env</b>.
1512 crypto_cipher_get_key(crypto_cipher_t
*env
)
1517 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1518 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1519 * Does not check for failure.
1522 crypto_cipher_encrypt(crypto_cipher_t
*env
, char *to
,
1523 const char *from
, size_t fromlen
)
1526 tor_assert(env
->cipher
);
1528 tor_assert(fromlen
);
1530 tor_assert(fromlen
< SIZE_T_CEILING
);
1532 memcpy(to
, from
, fromlen
);
1533 aes_crypt_inplace(env
->cipher
, to
, fromlen
);
1537 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1538 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1539 * Does not check for failure.
1542 crypto_cipher_decrypt(crypto_cipher_t
*env
, char *to
,
1543 const char *from
, size_t fromlen
)
1548 tor_assert(fromlen
< SIZE_T_CEILING
);
1550 memcpy(to
, from
, fromlen
);
1551 aes_crypt_inplace(env
->cipher
, to
, fromlen
);
1555 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1556 * on success. Does not check for failure.
1559 crypto_cipher_crypt_inplace(crypto_cipher_t
*env
, char *buf
, size_t len
)
1561 tor_assert(len
< SIZE_T_CEILING
);
1562 aes_crypt_inplace(env
->cipher
, buf
, len
);
1565 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1566 * <b>key</b> to the buffer in <b>to</b> of length
1567 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1568 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1569 * number of bytes written, on failure, return -1.
1572 crypto_cipher_encrypt_with_iv(const char *key
,
1573 char *to
, size_t tolen
,
1574 const char *from
, size_t fromlen
)
1576 crypto_cipher_t
*cipher
;
1579 tor_assert(fromlen
< INT_MAX
);
1583 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1586 cipher
= crypto_cipher_new_with_iv(key
, NULL
);
1588 memcpy(to
, cipher
->iv
, CIPHER_IV_LEN
);
1589 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1590 crypto_cipher_free(cipher
);
1591 return (int)(fromlen
+ CIPHER_IV_LEN
);
1594 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1595 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1596 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1597 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1598 * number of bytes written, on failure, return -1.
1601 crypto_cipher_decrypt_with_iv(const char *key
,
1602 char *to
, size_t tolen
,
1603 const char *from
, size_t fromlen
)
1605 crypto_cipher_t
*cipher
;
1609 tor_assert(fromlen
< INT_MAX
);
1611 if (fromlen
<= CIPHER_IV_LEN
)
1613 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1616 cipher
= crypto_cipher_new_with_iv(key
, from
);
1618 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1619 crypto_cipher_free(cipher
);
1620 return (int)(fromlen
- CIPHER_IV_LEN
);
1625 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1626 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1627 * Return 0 on success, 1 on failure.
1630 crypto_digest(char *digest
, const char *m
, size_t len
)
1634 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1637 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1638 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1639 * into <b>digest</b>. Return 0 on success, 1 on failure. */
1641 crypto_digest256(char *digest
, const char *m
, size_t len
,
1642 digest_algorithm_t algorithm
)
1646 tor_assert(algorithm
== DIGEST_SHA256
|| algorithm
== DIGEST_SHA3_256
);
1647 if (algorithm
== DIGEST_SHA256
)
1648 return (SHA256((const uint8_t*)m
,len
,(uint8_t*)digest
) == NULL
);
1650 return (sha3_256((uint8_t *)digest
, DIGEST256_LEN
,(const uint8_t *)m
, len
)
1654 /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1655 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
1656 * into <b>digest</b>. Return 0 on success, 1 on failure. */
1658 crypto_digest512(char *digest
, const char *m
, size_t len
,
1659 digest_algorithm_t algorithm
)
1663 tor_assert(algorithm
== DIGEST_SHA512
|| algorithm
== DIGEST_SHA3_512
);
1664 if (algorithm
== DIGEST_SHA512
)
1665 return (SHA512((const unsigned char*)m
,len
,(unsigned char*)digest
)
1668 return (sha3_512((uint8_t*)digest
, DIGEST512_LEN
, (const uint8_t*)m
, len
)
1672 /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
1673 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1674 * success, -1 on failure. */
1676 crypto_common_digests(common_digests_t
*ds_out
, const char *m
, size_t len
)
1679 memset(ds_out
, 0, sizeof(*ds_out
));
1680 if (crypto_digest(ds_out
->d
[DIGEST_SHA1
], m
, len
) < 0)
1682 if (crypto_digest256(ds_out
->d
[DIGEST_SHA256
], m
, len
, DIGEST_SHA256
) < 0)
1688 /** Return the name of an algorithm, as used in directory documents. */
1690 crypto_digest_algorithm_get_name(digest_algorithm_t alg
)
1699 case DIGEST_SHA3_256
:
1701 case DIGEST_SHA3_512
:
1704 tor_fragile_assert();
1705 return "??unknown_digest??";
1709 /** Given the name of a digest algorithm, return its integer value, or -1 if
1710 * the name is not recognized. */
1712 crypto_digest_algorithm_parse_name(const char *name
)
1714 if (!strcmp(name
, "sha1"))
1716 else if (!strcmp(name
, "sha256"))
1717 return DIGEST_SHA256
;
1718 else if (!strcmp(name
, "sha512"))
1719 return DIGEST_SHA512
;
1720 else if (!strcmp(name
, "sha3-256"))
1721 return DIGEST_SHA3_256
;
1722 else if (!strcmp(name
, "sha3-512"))
1723 return DIGEST_SHA3_512
;
1728 /** Given an algorithm, return the digest length in bytes. */
1729 static inline size_t
1730 crypto_digest_algorithm_get_length(digest_algorithm_t alg
)
1736 return DIGEST256_LEN
;
1738 return DIGEST512_LEN
;
1739 case DIGEST_SHA3_256
:
1740 return DIGEST256_LEN
;
1741 case DIGEST_SHA3_512
:
1742 return DIGEST512_LEN
;
1745 return 0; /* Unreachable */
1749 /** Intermediate information about the digest of a stream of data. */
1750 struct crypto_digest_t
{
1751 digest_algorithm_t algorithm
; /**< Which algorithm is in use? */
1752 /** State for the digest we're using. Only one member of the
1753 * union is usable, depending on the value of <b>algorithm</b>. Note also
1754 * that space for other members might not even be allocated!
1757 SHA_CTX sha1
; /**< state for SHA1 */
1758 SHA256_CTX sha2
; /**< state for SHA256 */
1759 SHA512_CTX sha512
; /**< state for SHA512 */
1760 keccak_state sha3
; /**< state for SHA3-[256,512] */
1765 * Return the number of bytes we need to malloc in order to get a
1766 * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
1770 crypto_digest_alloc_bytes(digest_algorithm_t alg
)
1772 /* Helper: returns the number of bytes in the 'f' field of 'st' */
1773 #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
1774 /* Gives the length of crypto_digest_t through the end of the field 'd' */
1775 #define END_OF_FIELD(f) (STRUCT_OFFSET(crypto_digest_t, f) + \
1776 STRUCT_FIELD_SIZE(crypto_digest_t, f))
1779 return END_OF_FIELD(d
.sha1
);
1781 return END_OF_FIELD(d
.sha2
);
1783 return END_OF_FIELD(d
.sha512
);
1784 case DIGEST_SHA3_256
:
1785 case DIGEST_SHA3_512
:
1786 return END_OF_FIELD(d
.sha3
);
1792 #undef STRUCT_FIELD_SIZE
1795 /** Allocate and return a new digest object to compute SHA1 digests.
1798 crypto_digest_new(void)
1801 r
= tor_malloc(crypto_digest_alloc_bytes(DIGEST_SHA1
));
1802 SHA1_Init(&r
->d
.sha1
);
1803 r
->algorithm
= DIGEST_SHA1
;
1807 /** Allocate and return a new digest object to compute 256-bit digests
1808 * using <b>algorithm</b>. */
1810 crypto_digest256_new(digest_algorithm_t algorithm
)
1813 tor_assert(algorithm
== DIGEST_SHA256
|| algorithm
== DIGEST_SHA3_256
);
1814 r
= tor_malloc(crypto_digest_alloc_bytes(algorithm
));
1815 if (algorithm
== DIGEST_SHA256
)
1816 SHA256_Init(&r
->d
.sha2
);
1818 keccak_digest_init(&r
->d
.sha3
, 256);
1819 r
->algorithm
= algorithm
;
1823 /** Allocate and return a new digest object to compute 512-bit digests
1824 * using <b>algorithm</b>. */
1826 crypto_digest512_new(digest_algorithm_t algorithm
)
1829 tor_assert(algorithm
== DIGEST_SHA512
|| algorithm
== DIGEST_SHA3_512
);
1830 r
= tor_malloc(crypto_digest_alloc_bytes(algorithm
));
1831 if (algorithm
== DIGEST_SHA512
)
1832 SHA512_Init(&r
->d
.sha512
);
1834 keccak_digest_init(&r
->d
.sha3
, 512);
1835 r
->algorithm
= algorithm
;
1839 /** Deallocate a digest object.
1842 crypto_digest_free(crypto_digest_t
*digest
)
1846 size_t bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
1847 memwipe(digest
, 0, bytes
);
1851 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1854 crypto_digest_add_bytes(crypto_digest_t
*digest
, const char *data
,
1859 /* Using the SHA*_*() calls directly means we don't support doing
1860 * SHA in hardware. But so far the delay of getting the question
1861 * to the hardware, and hearing the answer, is likely higher than
1862 * just doing it ourselves. Hashes are fast.
1864 switch (digest
->algorithm
) {
1866 SHA1_Update(&digest
->d
.sha1
, (void*)data
, len
);
1869 SHA256_Update(&digest
->d
.sha2
, (void*)data
, len
);
1872 SHA512_Update(&digest
->d
.sha512
, (void*)data
, len
);
1874 case DIGEST_SHA3_256
: /* FALLSTHROUGH */
1875 case DIGEST_SHA3_512
:
1876 keccak_digest_update(&digest
->d
.sha3
, (const uint8_t *)data
, len
);
1879 tor_fragile_assert();
1884 /** Compute the hash of the data that has been passed to the digest
1885 * object; write the first out_len bytes of the result to <b>out</b>.
1886 * <b>out_len</b> must be \<= DIGEST512_LEN.
1889 crypto_digest_get_digest(crypto_digest_t
*digest
,
1890 char *out
, size_t out_len
)
1892 unsigned char r
[DIGEST512_LEN
];
1893 crypto_digest_t tmpenv
;
1896 tor_assert(out_len
<= crypto_digest_algorithm_get_length(digest
->algorithm
));
1898 /* The SHA-3 code handles copying into a temporary ctx, and also can handle
1899 * short output buffers by truncating appropriately. */
1900 if (digest
->algorithm
== DIGEST_SHA3_256
||
1901 digest
->algorithm
== DIGEST_SHA3_512
) {
1902 keccak_digest_sum(&digest
->d
.sha3
, (uint8_t *)out
, out_len
);
1906 const size_t alloc_bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
1907 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1908 memcpy(&tmpenv
, digest
, alloc_bytes
);
1909 switch (digest
->algorithm
) {
1911 SHA1_Final(r
, &tmpenv
.d
.sha1
);
1914 SHA256_Final(r
, &tmpenv
.d
.sha2
);
1917 SHA512_Final(r
, &tmpenv
.d
.sha512
);
1919 case DIGEST_SHA3_256
: /* FALLSTHROUGH */
1920 case DIGEST_SHA3_512
:
1921 log_warn(LD_BUG
, "Handling unexpected algorithm %d", digest
->algorithm
);
1922 tor_assert(0); /* This is fatal, because it should never happen. */
1924 tor_assert(0); /* Unreachable. */
1927 memcpy(out
, r
, out_len
);
1928 memwipe(r
, 0, sizeof(r
));
1931 /** Allocate and return a new digest object with the same state as
1935 crypto_digest_dup(const crypto_digest_t
*digest
)
1938 const size_t alloc_bytes
= crypto_digest_alloc_bytes(digest
->algorithm
);
1939 return tor_memdup(digest
, alloc_bytes
);
1942 /** Replace the state of the digest object <b>into</b> with the state
1943 * of the digest object <b>from</b>. Requires that 'into' and 'from'
1944 * have the same digest type.
1947 crypto_digest_assign(crypto_digest_t
*into
,
1948 const crypto_digest_t
*from
)
1952 tor_assert(into
->algorithm
== from
->algorithm
);
1953 const size_t alloc_bytes
= crypto_digest_alloc_bytes(from
->algorithm
);
1954 memcpy(into
,from
,alloc_bytes
);
1957 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1958 * at <b>digest_out</b> to the hash of the concatenation of those strings,
1959 * plus the optional string <b>append</b>, computed with the algorithm
1961 * <b>out_len</b> must be \<= DIGEST512_LEN. */
1963 crypto_digest_smartlist(char *digest_out
, size_t len_out
,
1964 const smartlist_t
*lst
,
1966 digest_algorithm_t alg
)
1968 crypto_digest_smartlist_prefix(digest_out
, len_out
, NULL
, lst
, append
, alg
);
1971 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1972 * at <b>digest_out</b> to the hash of the concatenation of: the
1973 * optional string <b>prepend</b>, those strings,
1974 * and the optional string <b>append</b>, computed with the algorithm
1976 * <b>len_out</b> must be \<= DIGEST512_LEN. */
1978 crypto_digest_smartlist_prefix(char *digest_out
, size_t len_out
,
1979 const char *prepend
,
1980 const smartlist_t
*lst
,
1982 digest_algorithm_t alg
)
1984 crypto_digest_t
*d
= NULL
;
1987 d
= crypto_digest_new();
1989 case DIGEST_SHA256
: /* FALLSTHROUGH */
1990 case DIGEST_SHA3_256
:
1991 d
= crypto_digest256_new(alg
);
1993 case DIGEST_SHA512
: /* FALLSTHROUGH */
1994 case DIGEST_SHA3_512
:
1995 d
= crypto_digest512_new(alg
);
1998 log_warn(LD_BUG
, "Called with unknown algorithm %d", alg
);
1999 /* If fragile_assert is not enabled, wipe output and return
2000 * without running any calculations */
2001 memwipe(digest_out
, 0xff, len_out
);
2002 tor_fragile_assert();
2006 crypto_digest_add_bytes(d
, prepend
, strlen(prepend
));
2007 SMARTLIST_FOREACH(lst
, const char *, cp
,
2008 crypto_digest_add_bytes(d
, cp
, strlen(cp
)));
2010 crypto_digest_add_bytes(d
, append
, strlen(append
));
2011 crypto_digest_get_digest(d
, digest_out
, len_out
);
2014 crypto_digest_free(d
);
2017 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
2018 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
2019 * result in <b>hmac_out</b>. Asserts on failure.
2022 crypto_hmac_sha256(char *hmac_out
,
2023 const char *key
, size_t key_len
,
2024 const char *msg
, size_t msg_len
)
2026 unsigned char *rv
= NULL
;
2027 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
2028 tor_assert(key_len
< INT_MAX
);
2029 tor_assert(msg_len
< INT_MAX
);
2030 tor_assert(hmac_out
);
2031 rv
= HMAC(EVP_sha256(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
2032 (unsigned char*)hmac_out
, NULL
);
2036 /** Internal state for a eXtendable-Output Function (XOF). */
2037 struct crypto_xof_t
{
2041 /** Allocate a new XOF object backed by SHAKE-256. The security level
2042 * provided is a function of the length of the output used. Read and
2043 * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
2044 * Functions" before using this construct.
2047 crypto_xof_new(void)
2050 xof
= tor_malloc(sizeof(crypto_xof_t
));
2051 keccak_xof_init(&xof
->s
, 256);
2055 /** Absorb bytes into a XOF object. Must not be called after a call to
2056 * crypto_xof_squeeze_bytes() for the same instance, and will assert
2060 crypto_xof_add_bytes(crypto_xof_t
*xof
, const uint8_t *data
, size_t len
)
2062 int i
= keccak_xof_absorb(&xof
->s
, data
, len
);
2066 /** Squeeze bytes out of a XOF object. Calling this routine will render
2067 * the XOF instance ineligible to absorb further data.
2070 crypto_xof_squeeze_bytes(crypto_xof_t
*xof
, uint8_t *out
, size_t len
)
2072 int i
= keccak_xof_squeeze(&xof
->s
, out
, len
);
2076 /** Cleanse and deallocate a XOF object. */
2078 crypto_xof_free(crypto_xof_t
*xof
)
2082 memwipe(xof
, 0, sizeof(crypto_xof_t
));
2088 /** Our DH 'g' parameter */
2089 #define DH_GENERATOR 2
2091 /** Shared P parameter for our circuit-crypto DH key exchanges. */
2092 static BIGNUM
*dh_param_p
= NULL
;
2093 /** Shared P parameter for our TLS DH key exchanges. */
2094 static BIGNUM
*dh_param_p_tls
= NULL
;
2095 /** Shared G parameter for our DH key exchanges. */
2096 static BIGNUM
*dh_param_g
= NULL
;
2098 /** Validate a given set of Diffie-Hellman parameters. This is moderately
2099 * computationally expensive (milliseconds), so should only be called when
2100 * the DH parameters change. Returns 0 on success, * -1 on failure.
2103 crypto_validate_dh_params(const BIGNUM
*p
, const BIGNUM
*g
)
2108 /* Copy into a temporary DH object. */
2109 if (!(dh
= DH_new()))
2111 if (!(dh
->p
= BN_dup(p
)))
2113 if (!(dh
->g
= BN_dup(g
)))
2116 /* Perform the validation. */
2118 if (!DH_check(dh
, &codes
))
2120 if (BN_is_word(dh
->g
, DH_GENERATOR_2
)) {
2121 /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
2123 * OpenSSL checks the prime is congruent to 11 when g = 2; while the
2124 * IETF's primes are congruent to 23 when g = 2.
2126 BN_ULONG residue
= BN_mod_word(dh
->p
, 24);
2127 if (residue
== 11 || residue
== 23)
2128 codes
&= ~DH_NOT_SUITABLE_GENERATOR
;
2130 if (codes
!= 0) /* Specifics on why the params suck is irrelevant. */
2133 /* Things are probably not evil. */
2142 /** Set the global Diffie-Hellman generator, used for both TLS and internal
2146 crypto_set_dh_generator(void)
2154 generator
= BN_new();
2155 tor_assert(generator
);
2157 r
= BN_set_word(generator
, DH_GENERATOR
);
2160 dh_param_g
= generator
;
2163 /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
2166 crypto_set_tls_dh_prime(void)
2168 BIGNUM
*tls_prime
= NULL
;
2171 /* If the space is occupied, free the previous TLS DH prime */
2172 if (dh_param_p_tls
) {
2173 BN_clear_free(dh_param_p_tls
);
2174 dh_param_p_tls
= NULL
;
2177 tls_prime
= BN_new();
2178 tor_assert(tls_prime
);
2180 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
2181 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
2184 r
= BN_hex2bn(&tls_prime
,
2185 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
2186 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
2187 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
2188 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
2189 "B0E7393E0F24218EB3");
2192 tor_assert(tls_prime
);
2194 dh_param_p_tls
= tls_prime
;
2195 crypto_set_dh_generator();
2196 tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls
, dh_param_g
));
2199 /** Initialize dh_param_p and dh_param_g if they are not already
2204 BIGNUM
*circuit_dh_prime
;
2206 if (dh_param_p
&& dh_param_g
)
2209 circuit_dh_prime
= BN_new();
2210 tor_assert(circuit_dh_prime
);
2212 /* This is from rfc2409, section 6.2. It's a safe prime, and
2213 supposedly it equals:
2214 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
2216 r
= BN_hex2bn(&circuit_dh_prime
,
2217 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
2218 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
2219 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
2220 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
2221 "49286651ECE65381FFFFFFFFFFFFFFFF");
2224 /* Set the new values as the global DH parameters. */
2225 dh_param_p
= circuit_dh_prime
;
2226 crypto_set_dh_generator();
2227 tor_assert(0 == crypto_validate_dh_params(dh_param_p
, dh_param_g
));
2229 if (!dh_param_p_tls
) {
2230 crypto_set_tls_dh_prime();
2234 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
2235 * handshake. Since we exponentiate by this value, choosing a smaller one
2236 * lets our handhake go faster.
2238 #define DH_PRIVATE_KEY_BITS 320
2240 /** Allocate and return a new DH object for a key exchange. Returns NULL on
2244 crypto_dh_new(int dh_type
)
2246 crypto_dh_t
*res
= tor_malloc_zero(sizeof(crypto_dh_t
));
2248 tor_assert(dh_type
== DH_TYPE_CIRCUIT
|| dh_type
== DH_TYPE_TLS
||
2249 dh_type
== DH_TYPE_REND
);
2254 if (!(res
->dh
= DH_new()))
2257 if (dh_type
== DH_TYPE_TLS
) {
2258 if (!(res
->dh
->p
= BN_dup(dh_param_p_tls
)))
2261 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
2265 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
2268 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
2272 crypto_log_errors(LOG_WARN
, "creating DH object");
2273 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
2278 /** Return a copy of <b>dh</b>, sharing its internal state. */
2280 crypto_dh_dup(const crypto_dh_t
*dh
)
2282 crypto_dh_t
*dh_new
= tor_malloc_zero(sizeof(crypto_dh_t
));
2285 dh_new
->dh
= dh
->dh
;
2290 /** Return the length of the DH key in <b>dh</b>, in bytes.
2293 crypto_dh_get_bytes(crypto_dh_t
*dh
)
2296 return DH_size(dh
->dh
);
2299 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2300 * success, -1 on failure.
2303 crypto_dh_generate_public(crypto_dh_t
*dh
)
2306 if (!DH_generate_key(dh
->dh
)) {
2307 crypto_log_errors(LOG_WARN
, "generating DH key");
2310 if (tor_check_dh_key(LOG_WARN
, dh
->dh
->pub_key
)<0) {
2311 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
2312 "the-universe chances really do happen. Trying again.");
2313 /* Free and clear the keys, so OpenSSL will actually try again. */
2314 BN_clear_free(dh
->dh
->pub_key
);
2315 BN_clear_free(dh
->dh
->priv_key
);
2316 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
2322 /** Generate g^x as necessary, and write the g^x for the key exchange
2323 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2324 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2327 crypto_dh_get_public(crypto_dh_t
*dh
, char *pubkey
, size_t pubkey_len
)
2331 if (!dh
->dh
->pub_key
) {
2332 if (crypto_dh_generate_public(dh
)<0)
2336 tor_assert(dh
->dh
->pub_key
);
2337 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
2338 tor_assert(bytes
>= 0);
2339 if (pubkey_len
< (size_t)bytes
) {
2341 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2342 (int) pubkey_len
, bytes
);
2346 memset(pubkey
, 0, pubkey_len
);
2347 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
2352 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2353 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2354 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2357 tor_check_dh_key(int severity
, BIGNUM
*bn
)
2367 if (BN_cmp(bn
,x
)<=0) {
2368 log_fn(severity
, LD_CRYPTO
, "DH key must be at least 2.");
2371 BN_copy(x
,dh_param_p
);
2373 if (BN_cmp(bn
,x
)>=0) {
2374 log_fn(severity
, LD_CRYPTO
, "DH key must be at most p-2.");
2382 log_fn(severity
, LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
2388 #define MIN(a,b) ((a)<(b)?(a):(b))
2389 /** Given a DH key exchange object, and our peer's value of g^y (as a
2390 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2391 * <b>secret_bytes_out</b> bytes of shared key material and write them
2392 * to <b>secret_out</b>. Return the number of bytes generated on success,
2395 * (We generate key material by computing
2396 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2397 * where || is concatenation.)
2400 crypto_dh_compute_secret(int severity
, crypto_dh_t
*dh
,
2401 const char *pubkey
, size_t pubkey_len
,
2402 char *secret_out
, size_t secret_bytes_out
)
2404 char *secret_tmp
= NULL
;
2405 BIGNUM
*pubkey_bn
= NULL
;
2406 size_t secret_len
=0, secret_tmp_len
=0;
2409 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
2410 tor_assert(pubkey_len
< INT_MAX
);
2412 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
2413 (int)pubkey_len
, NULL
)))
2415 if (tor_check_dh_key(severity
, pubkey_bn
)<0) {
2416 /* Check for invalid public keys. */
2417 log_fn(severity
, LD_CRYPTO
,"Rejected invalid g^x");
2420 secret_tmp_len
= crypto_dh_get_bytes(dh
);
2421 secret_tmp
= tor_malloc(secret_tmp_len
);
2422 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
2424 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
2427 secret_len
= result
;
2428 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp
, secret_len
,
2429 (uint8_t*)secret_out
, secret_bytes_out
)<0)
2431 secret_len
= secret_bytes_out
;
2437 crypto_log_errors(LOG_WARN
, "completing DH handshake");
2439 BN_clear_free(pubkey_bn
);
2441 memwipe(secret_tmp
, 0, secret_tmp_len
);
2442 tor_free(secret_tmp
);
2450 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2451 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2452 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2453 * H(K | [00]) | H(K | [01]) | ....
2455 * This is the key expansion algorithm used in the "TAP" circuit extension
2456 * mechanism; it shouldn't be used for new protocols.
2458 * Return 0 on success, -1 on failure.
2461 crypto_expand_key_material_TAP(const uint8_t *key_in
, size_t key_in_len
,
2462 uint8_t *key_out
, size_t key_out_len
)
2465 uint8_t *cp
, *tmp
= tor_malloc(key_in_len
+1);
2466 uint8_t digest
[DIGEST_LEN
];
2468 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2469 tor_assert(key_out_len
<= DIGEST_LEN
*256);
2471 memcpy(tmp
, key_in
, key_in_len
);
2472 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
2473 ++i
, cp
+= DIGEST_LEN
) {
2474 tmp
[key_in_len
] = i
;
2475 if (crypto_digest((char*)digest
, (const char *)tmp
, key_in_len
+1))
2477 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
2482 memwipe(tmp
, 0, key_in_len
+1);
2484 memwipe(digest
, 0, sizeof(digest
));
2488 /** Expand some secret key material according to RFC5869, using SHA256 as the
2489 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2490 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2491 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2492 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2493 * bytes to <b>key_out</b> and return 0. Assert on failure.
2496 crypto_expand_key_material_rfc5869_sha256(
2497 const uint8_t *key_in
, size_t key_in_len
,
2498 const uint8_t *salt_in
, size_t salt_in_len
,
2499 const uint8_t *info_in
, size_t info_in_len
,
2500 uint8_t *key_out
, size_t key_out_len
)
2502 uint8_t prk
[DIGEST256_LEN
];
2503 uint8_t tmp
[DIGEST256_LEN
+ 128 + 1];
2504 uint8_t mac
[DIGEST256_LEN
];
2509 crypto_hmac_sha256((char*)prk
,
2510 (const char*)salt_in
, salt_in_len
,
2511 (const char*)key_in
, key_in_len
);
2513 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2514 tor_assert(key_out_len
<= DIGEST256_LEN
* 256);
2515 tor_assert(info_in_len
<= 128);
2516 memset(tmp
, 0, sizeof(tmp
));
2520 while (key_out_len
) {
2523 memcpy(tmp
, mac
, DIGEST256_LEN
);
2524 memcpy(tmp
+DIGEST256_LEN
, info_in
, info_in_len
);
2525 tmp
[DIGEST256_LEN
+info_in_len
] = i
;
2526 tmp_len
= DIGEST256_LEN
+ info_in_len
+ 1;
2528 memcpy(tmp
, info_in
, info_in_len
);
2529 tmp
[info_in_len
] = i
;
2530 tmp_len
= info_in_len
+ 1;
2532 crypto_hmac_sha256((char*)mac
,
2533 (const char*)prk
, DIGEST256_LEN
,
2534 (const char*)tmp
, tmp_len
);
2535 n
= key_out_len
< DIGEST256_LEN
? key_out_len
: DIGEST256_LEN
;
2536 memcpy(outp
, mac
, n
);
2542 memwipe(tmp
, 0, sizeof(tmp
));
2543 memwipe(mac
, 0, sizeof(mac
));
2547 /** Free a DH key exchange object.
2550 crypto_dh_free(crypto_dh_t
*dh
)
2559 /* random numbers */
2561 /** How many bytes of entropy we add at once.
2563 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2564 * work for us too. */
2565 #define ADD_ENTROPY 32
2567 /** Set the seed of the weak RNG to a random value. */
2569 crypto_seed_weak_rng(tor_weak_rng_t
*rng
)
2572 crypto_rand((void*)&seed
, sizeof(seed
));
2573 tor_init_weak_random(rng
, seed
);
2576 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2577 * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
2578 * failure. A maximum request size of 256 bytes is imposed.
2581 crypto_strongest_rand_syscall(uint8_t *out
, size_t out_len
)
2583 tor_assert(out_len
<= MAX_STRONGEST_RAND_SIZE
);
2586 static int provider_set
= 0;
2587 static HCRYPTPROV provider
;
2589 if (!provider_set
) {
2590 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
2591 CRYPT_VERIFYCONTEXT
)) {
2592 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
2597 if (!CryptGenRandom(provider
, out_len
, out
)) {
2598 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
2603 #elif defined(__linux__) && defined(SYS_getrandom)
2604 static int getrandom_works
= 1; /* Be optimitic about our chances... */
2606 /* getrandom() isn't as straight foward as getentropy(), and has
2609 * As far as I can tell from getrandom(2) and the source code, the
2610 * requests we issue will always succeed (though it will block on the
2611 * call if /dev/urandom isn't seeded yet), since we are NOT specifying
2612 * GRND_NONBLOCK and the request is <= 256 bytes.
2614 * The manpage is unclear on what happens if a signal interrupts the call
2615 * while the request is blocked due to lack of entropy....
2617 * We optimistically assume that getrandom() is available and functional
2618 * because it is the way of the future, and 2 branch mispredicts pale in
2619 * comparision to the overheads involved with failing to open
2620 * /dev/srandom followed by opening and reading from /dev/urandom.
2622 if (PREDICT_LIKELY(getrandom_works
)) {
2624 /* A flag of '0' here means to read from '/dev/urandom', and to
2625 * block if insufficient entropy is available to service the
2628 const unsigned int flags
= 0;
2630 ret
= syscall(SYS_getrandom
, out
, out_len
, flags
);
2631 } while (ret
== -1 && ((errno
== EINTR
) ||(errno
== EAGAIN
)));
2633 if (PREDICT_UNLIKELY(ret
== -1)) {
2634 tor_assert(errno
!= EAGAIN
);
2635 tor_assert(errno
!= EINTR
);
2637 /* Probably ENOSYS. */
2638 log_warn(LD_CRYPTO
, "Can't get entropy from getrandom().");
2639 getrandom_works
= 0; /* Don't bother trying again. */
2643 tor_assert(ret
== (long)out_len
);
2647 return -1; /* getrandom() previously failed unexpectedly. */
2648 #elif defined(HAVE_GETENTROPY)
2649 /* getentropy() is what Linux's getrandom() wants to be when it grows up.
2650 * the only gotcha is that requests are limited to 256 bytes.
2652 return getentropy(out
, out_len
);
2657 /* This platform doesn't have a supported syscall based random. */
2661 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2662 * via the per-platform fallback mechanism, storing it into <b>out</b>.
2663 * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
2667 crypto_strongest_rand_fallback(uint8_t *out
, size_t out_len
)
2670 /* Windows exclusively uses crypto_strongest_rand_syscall(). */
2675 static const char *filenames
[] = {
2676 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2681 for (i
= 0; filenames
[i
]; ++i
) {
2682 log_debug(LD_FS
, "Opening %s for entropy", filenames
[i
]);
2683 fd
= open(sandbox_intern_string(filenames
[i
]), O_RDONLY
, 0);
2685 log_info(LD_CRYPTO
, "Reading entropy from \"%s\"", filenames
[i
]);
2686 n
= read_all(fd
, (char*)out
, out_len
, 0);
2690 "Error reading from entropy source (read only %lu bytes).",
2702 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2703 * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
2704 * request size of 256 bytes is imposed.
2707 crypto_strongest_rand_raw(uint8_t *out
, size_t out_len
)
2709 static const size_t sanity_min_size
= 16;
2710 static const int max_attempts
= 3;
2711 tor_assert(out_len
<= MAX_STRONGEST_RAND_SIZE
);
2713 /* For buffers >= 16 bytes (128 bits), we sanity check the output by
2714 * zero filling the buffer and ensuring that it actually was at least
2715 * partially modified.
2717 * Checking that any individual byte is non-zero seems like it would
2718 * fail too often (p = out_len * 1/256) for comfort, but this is an
2719 * "adjust according to taste" sort of check.
2721 memwipe(out
, 0, out_len
);
2722 for (int i
= 0; i
< max_attempts
; i
++) {
2723 /* Try to use the syscall/OS favored mechanism to get strong entropy. */
2724 if (crypto_strongest_rand_syscall(out
, out_len
) != 0) {
2725 /* Try to use the less-favored mechanism to get strong entropy. */
2726 if (crypto_strongest_rand_fallback(out
, out_len
) != 0) {
2727 /* Welp, we tried. Hopefully the calling code terminates the process
2728 * since we're basically boned without good entropy.
2731 "Cannot get strong entropy: no entropy source found.");
2736 if ((out_len
< sanity_min_size
) || !tor_mem_is_zero((char*)out
, out_len
))
2740 /* We tried max_attempts times to fill a buffer >= 128 bits long,
2741 * and each time it returned all '0's. Either the system entropy
2742 * source is busted, or the user should go out and buy a ticket to
2743 * every lottery on the planet.
2745 log_warn(LD_CRYPTO
, "Strong OS entropy returned all zero buffer.");
2749 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2750 * storing it into <b>out</b>.
2753 crypto_strongest_rand(uint8_t *out
, size_t out_len
)
2755 #define DLEN SHA512_DIGEST_LENGTH
2756 /* We're going to hash DLEN bytes from the system RNG together with some
2757 * bytes from the openssl PRNG, in order to yield DLEN bytes.
2759 uint8_t inp
[DLEN
*2];
2763 crypto_rand((char*) inp
, DLEN
);
2764 if (crypto_strongest_rand_raw(inp
+DLEN
, DLEN
) < 0) {
2765 log_err(LD_CRYPTO
, "Failed to load strong entropy when generating an "
2766 "important key. Exiting.");
2767 /* Die with an assertion so we get a stack trace. */
2770 if (out_len
>= DLEN
) {
2771 SHA512(inp
, sizeof(inp
), out
);
2775 SHA512(inp
, sizeof(inp
), tmp
);
2776 memcpy(out
, tmp
, out_len
);
2780 memwipe(tmp
, 0, sizeof(tmp
));
2781 memwipe(inp
, 0, sizeof(inp
));
2785 /** Seed OpenSSL's random number generator with bytes from the operating
2786 * system. Return 0 on success, -1 on failure.
2789 crypto_seed_rng(void)
2791 int rand_poll_ok
= 0, load_entropy_ok
= 0;
2792 uint8_t buf
[ADD_ENTROPY
];
2794 /* OpenSSL has a RAND_poll function that knows about more kinds of
2795 * entropy than we do. We'll try calling that, *and* calling our own entropy
2796 * functions. If one succeeds, we'll accept the RNG as seeded. */
2797 rand_poll_ok
= RAND_poll();
2798 if (rand_poll_ok
== 0)
2799 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
2801 load_entropy_ok
= !crypto_strongest_rand_raw(buf
, sizeof(buf
));
2802 if (load_entropy_ok
) {
2803 RAND_seed(buf
, sizeof(buf
));
2806 memwipe(buf
, 0, sizeof(buf
));
2808 if ((rand_poll_ok
|| load_entropy_ok
) && RAND_status() == 1)
2814 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
2817 * This function is not allowed to fail; if it would fail to generate strong
2818 * entropy, it must terminate the process instead.
2821 crypto_rand
, (char *to
, size_t n
))
2823 crypto_rand_unmocked(to
, n
);
2826 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
2827 * will want crypto_rand instead.
2829 * This function is not allowed to fail; if it would fail to generate strong
2830 * entropy, it must terminate the process instead.
2833 crypto_rand_unmocked(char *to
, size_t n
)
2839 tor_assert(n
< INT_MAX
);
2841 r
= RAND_bytes((unsigned char*)to
, (int)n
);
2842 /* We consider a PRNG failure non-survivable. Let's assert so that we get a
2843 * stack trace about where it happened.
2848 /** Return a pseudorandom integer, chosen uniformly from the values
2849 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2850 * INT_MAX+1, inclusive. */
2852 crypto_rand_int(unsigned int max
)
2855 unsigned int cutoff
;
2856 tor_assert(max
<= ((unsigned int)INT_MAX
)+1);
2857 tor_assert(max
> 0); /* don't div by 0 */
2859 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2860 * distribution with clipping at the upper end of unsigned int's
2863 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
2865 crypto_rand((char*)&val
, sizeof(val
));
2871 /** Return a pseudorandom integer, chosen uniformly from the values i such
2872 * that min <= i < max.
2874 * <b>min</b> MUST be in range [0, <b>max</b>).
2875 * <b>max</b> MUST be in range (min, INT_MAX].
2878 crypto_rand_int_range(unsigned int min
, unsigned int max
)
2880 tor_assert(min
< max
);
2881 tor_assert(max
<= INT_MAX
);
2883 /* The overflow is avoided here because crypto_rand_int() returns a value
2884 * between 0 and (max - min) inclusive. */
2885 return min
+ crypto_rand_int(max
- min
);
2888 /** As crypto_rand_int_range, but supports uint64_t. */
2890 crypto_rand_uint64_range(uint64_t min
, uint64_t max
)
2892 tor_assert(min
< max
);
2893 return min
+ crypto_rand_uint64(max
- min
);
2896 /** As crypto_rand_int_range, but supports time_t. */
2898 crypto_rand_time_range(time_t min
, time_t max
)
2900 tor_assert(min
< max
);
2901 return min
+ (time_t)crypto_rand_uint64(max
- min
);
2904 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2905 * between 0 and <b>max</b>-1 inclusive. */
2907 crypto_rand_uint64(uint64_t max
)
2911 tor_assert(max
< UINT64_MAX
);
2912 tor_assert(max
> 0); /* don't div by 0 */
2914 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2915 * distribution with clipping at the upper end of unsigned int's
2918 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
2920 crypto_rand((char*)&val
, sizeof(val
));
2926 /** Return a pseudorandom double d, chosen uniformly from the range
2930 crypto_rand_double(void)
2932 /* We just use an unsigned int here; we don't really care about getting
2933 * more than 32 bits of resolution */
2935 crypto_rand((char*)&uint
, sizeof(uint
));
2937 #define UINT_MAX_AS_DOUBLE 4294967296.0
2938 #elif SIZEOF_INT == 8
2939 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2941 #error SIZEOF_INT is neither 4 nor 8
2943 return ((double)uint
) / UINT_MAX_AS_DOUBLE
;
2946 /** Generate and return a new random hostname starting with <b>prefix</b>,
2947 * ending with <b>suffix</b>, and containing no fewer than
2948 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2949 * characters. Does not check for failure.
2951 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2954 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
2957 char *result
, *rand_bytes
;
2958 int randlen
, rand_bytes_len
;
2959 size_t resultlen
, prefixlen
;
2961 if (max_rand_len
> MAX_DNS_LABEL_SIZE
)
2962 max_rand_len
= MAX_DNS_LABEL_SIZE
;
2963 if (min_rand_len
> max_rand_len
)
2964 min_rand_len
= max_rand_len
;
2966 randlen
= crypto_rand_int_range(min_rand_len
, max_rand_len
+1);
2968 prefixlen
= strlen(prefix
);
2969 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
2971 rand_bytes_len
= ((randlen
*5)+7)/8;
2972 if (rand_bytes_len
% 5)
2973 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
2974 rand_bytes
= tor_malloc(rand_bytes_len
);
2975 crypto_rand(rand_bytes
, rand_bytes_len
);
2977 result
= tor_malloc(resultlen
);
2978 memcpy(result
, prefix
, prefixlen
);
2979 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
2980 rand_bytes
, rand_bytes_len
);
2981 tor_free(rand_bytes
);
2982 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
2987 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2990 smartlist_choose(const smartlist_t
*sl
)
2992 int len
= smartlist_len(sl
);
2994 return smartlist_get(sl
,crypto_rand_int(len
));
2995 return NULL
; /* no elements to choose from */
2998 /** Scramble the elements of <b>sl</b> into a random order. */
3000 smartlist_shuffle(smartlist_t
*sl
)
3003 /* From the end of the list to the front, choose at random from the
3004 positions we haven't looked at yet, and swap that position into the
3005 current position. Remember to give "no swap" the same probability as
3007 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
3008 int j
= crypto_rand_int(i
+1);
3009 smartlist_swap(sl
, i
, j
);
3014 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
3015 * the value <b>byte</b>.
3016 * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
3018 * This function is preferable to memset, since many compilers will happily
3019 * optimize out memset() when they can convince themselves that the data being
3020 * cleared will never be read.
3022 * Right now, our convention is to use this function when we are wiping data
3023 * that's about to become inaccessible, such as stack buffers that are about
3024 * to go out of scope or structures that are about to get freed. (In
3025 * practice, it appears that the compilers we're currently using will optimize
3026 * out the memset()s for stack-allocated buffers, but not those for
3027 * about-to-be-freed structures. That could change, though, so we're being
3028 * wary.) If there are live reads for the data, then you can just use
3032 memwipe(void *mem
, uint8_t byte
, size_t sz
)
3037 /* If sz is nonzero, then mem must not be NULL. */
3038 tor_assert(mem
!= NULL
);
3040 /* Data this large is likely to be an underflow. */
3041 tor_assert(sz
< SIZE_T_CEILING
);
3043 /* Because whole-program-optimization exists, we may not be able to just
3044 * have this function call "memset". A smart compiler could inline it, then
3045 * eliminate dead memsets, and declare itself to be clever. */
3047 #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
3048 /* Here's what you do on windows. */
3049 SecureZeroMemory(mem
,sz
);
3050 #elif defined(HAVE_RTLSECUREZEROMEMORY)
3051 RtlSecureZeroMemory(mem
,sz
);
3052 #elif defined(HAVE_EXPLICIT_BZERO)
3053 /* The BSDs provide this. */
3054 explicit_bzero(mem
, sz
);
3055 #elif defined(HAVE_MEMSET_S)
3056 /* This is in the C99 standard. */
3057 memset_s(mem
, sz
, 0, sz
);
3059 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
3060 * based on the pointer value, then uses that junk to update a global
3061 * variable. It's an elaborate ruse to trick the compiler into not
3062 * optimizing out the "wipe this memory" code. Read it if you like zany
3063 * programming tricks! In later versions of Tor, we should look for better
3064 * not-optimized-out memory wiping stuff...
3066 * ...or maybe not. In practice, there are pure-asm implementations of
3067 * OPENSSL_cleanse() on most platforms, which ought to do the job.
3070 OPENSSL_cleanse(mem
, sz
);
3073 /* Just in case some caller of memwipe() is relying on getting a buffer
3074 * filled with a particular value, fill the buffer.
3076 * If this function gets inlined, this memset might get eliminated, but
3077 * that's okay: We only care about this particular memset in the case where
3078 * the caller should have been using memset(), and the memset() wouldn't get
3079 * eliminated. In other words, this is here so that we won't break anything
3080 * if somebody accidentally calls memwipe() instead of memset().
3082 memset(mem
, byte
, sz
);
3085 #ifndef OPENSSL_THREADS
3086 #error OpenSSL has been built without thread support. Tor requires an \
3087 OpenSSL library with thread support enabled.
3090 #ifndef NEW_THREAD_API
3091 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3093 openssl_locking_cb_(int mode
, int n
, const char *file
, int line
)
3097 if (!openssl_mutexes_
)
3098 /* This is not a really good fix for the
3099 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3102 if (mode
& CRYPTO_LOCK
)
3103 tor_mutex_acquire(openssl_mutexes_
[n
]);
3105 tor_mutex_release(openssl_mutexes_
[n
]);
3109 tor_set_openssl_thread_id(CRYPTO_THREADID
*threadid
)
3111 CRYPTO_THREADID_set_numeric(threadid
, tor_get_thread_id());
3116 /* This code is disabled, because OpenSSL never actually uses these callbacks.
3119 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3121 struct CRYPTO_dynlock_value
{
3125 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3126 * documentation in OpenSSL's docs for more info. */
3127 static struct CRYPTO_dynlock_value
*
3128 openssl_dynlock_create_cb_(const char *file
, int line
)
3130 struct CRYPTO_dynlock_value
*v
;
3133 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
3134 v
->lock
= tor_mutex_new();
3138 /** OpenSSL callback function to acquire or release a lock: see
3139 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3141 openssl_dynlock_lock_cb_(int mode
, struct CRYPTO_dynlock_value
*v
,
3142 const char *file
, int line
)
3146 if (mode
& CRYPTO_LOCK
)
3147 tor_mutex_acquire(v
->lock
);
3149 tor_mutex_release(v
->lock
);
3152 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3153 * documentation in OpenSSL's docs for more info. */
3155 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value
*v
,
3156 const char *file
, int line
)
3160 tor_mutex_free(v
->lock
);
3166 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3167 * multithreaded. Returns 0. */
3169 setup_openssl_threading(void)
3171 #ifndef NEW_THREAD_API
3173 int n
= CRYPTO_num_locks();
3174 n_openssl_mutexes_
= n
;
3175 openssl_mutexes_
= tor_calloc(n
, sizeof(tor_mutex_t
*));
3176 for (i
=0; i
< n
; ++i
)
3177 openssl_mutexes_
[i
] = tor_mutex_new();
3178 CRYPTO_set_locking_callback(openssl_locking_cb_
);
3179 CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id
);
3182 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_
);
3183 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_
);
3184 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_
);
3189 /** Uninitialize the crypto library. Return 0 on success. Does not detect
3193 crypto_global_cleanup(void)
3196 #ifdef NEW_THREAD_API
3197 ERR_remove_thread_state();
3199 ERR_remove_thread_state(NULL
);
3204 BN_clear_free(dh_param_p
);
3206 BN_clear_free(dh_param_p_tls
);
3208 BN_clear_free(dh_param_g
);
3210 #ifndef DISABLE_ENGINES
3214 CONF_modules_unload(1);
3215 CRYPTO_cleanup_all_ex_data();
3217 #ifndef NEW_THREAD_API
3218 if (n_openssl_mutexes_
) {
3219 int n
= n_openssl_mutexes_
;
3220 tor_mutex_t
**ms
= openssl_mutexes_
;
3222 openssl_mutexes_
= NULL
;
3223 n_openssl_mutexes_
= 0;
3225 tor_mutex_free(ms
[i
]);
3231 tor_free(crypto_openssl_version_str
);
3232 tor_free(crypto_openssl_header_version_str
);