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-2013, 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.
17 #define _WIN32_WINNT 0x0501
19 #define WIN32_LEAN_AND_MEAN
22 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
23 * use either definition. */
27 #include <openssl/err.h>
28 #include <openssl/rsa.h>
29 #include <openssl/pem.h>
30 #include <openssl/evp.h>
31 #include <openssl/engine.h>
32 #include <openssl/rand.h>
33 #include <openssl/opensslv.h>
34 #include <openssl/bn.h>
35 #include <openssl/dh.h>
36 #include <openssl/conf.h>
37 #include <openssl/hmac.h>
48 #ifdef HAVE_SYS_FCNTL_H
49 #include <sys/fcntl.h>
52 #define CRYPTO_PRIVATE
54 #include "../common/torlog.h"
56 #include "../common/util.h"
57 #include "container.h"
60 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
61 #error "We require OpenSSL >= 0.9.8"
65 /* Android's OpenSSL seems to have removed all of its Engine support. */
66 #define DISABLE_ENGINES
69 /** Longest recognized */
70 #define MAX_DNS_LABEL_SIZE 63
72 /** Macro: is k a valid RSA public or private key? */
73 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
74 /** Macro: is k a valid RSA private key? */
75 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
77 #ifdef TOR_IS_MULTITHREADED
78 /** A number of preallocated mutexes for use by OpenSSL. */
79 static tor_mutex_t
**openssl_mutexes_
= NULL
;
80 /** How many mutexes have we allocated for use by OpenSSL? */
81 static int n_openssl_mutexes_
= 0;
84 /** A public key, or a public/private key-pair. */
87 int refs
; /**< reference count, so we don't have to copy keys */
88 RSA
*key
; /**< The key itself */
91 /** Key and stream information for a stream cipher. */
92 struct crypto_cipher_t
94 char key
[CIPHER_KEY_LEN
]; /**< The raw key. */
95 char iv
[CIPHER_IV_LEN
]; /**< The initial IV. */
96 aes_cnt_cipher_t
*cipher
; /**< The key in format usable for counter-mode AES
100 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
101 * while we're waiting for the second.*/
103 DH
*dh
; /**< The openssl DH object */
106 static int setup_openssl_threading(void);
107 static int tor_check_dh_key(int severity
, BIGNUM
*bn
);
109 /** Return the number of bytes added by padding method <b>padding</b>.
112 crypto_get_rsa_padding_overhead(int padding
)
116 case RSA_PKCS1_OAEP_PADDING
: return 42;
117 case RSA_PKCS1_PADDING
: return 11;
118 default: tor_assert(0); return -1;
122 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
125 crypto_get_rsa_padding(int padding
)
129 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
130 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
131 default: tor_assert(0); return -1;
135 /** Boolean: has OpenSSL's crypto been initialized? */
136 static int crypto_global_initialized_
= 0;
138 /** Log all pending crypto errors at level <b>severity</b>. Use
139 * <b>doing</b> to describe our current activities.
142 crypto_log_errors(int severity
, const char *doing
)
145 const char *msg
, *lib
, *func
;
146 while ((err
= ERR_get_error()) != 0) {
147 msg
= (const char*)ERR_reason_error_string(err
);
148 lib
= (const char*)ERR_lib_error_string(err
);
149 func
= (const char*)ERR_func_error_string(err
);
150 if (!msg
) msg
= "(null)";
151 if (!lib
) lib
= "(null)";
152 if (!func
) func
= "(null)";
154 tor_log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
155 doing
, msg
, lib
, func
);
157 tor_log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)",
163 #ifndef DISABLE_ENGINES
164 /** Log any OpenSSL engines we're using at NOTICE. */
166 log_engine(const char *fn
, ENGINE
*e
)
169 const char *name
, *id
;
170 name
= ENGINE_get_name(e
);
171 id
= ENGINE_get_id(e
);
172 log_notice(LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
173 name
?name
:"?", id
?id
:"?", fn
);
175 log_info(LD_CRYPTO
, "Using default implementation for %s", fn
);
180 #ifndef DISABLE_ENGINES
181 /** Try to load an engine in a shared library via fully qualified path.
184 try_load_engine(const char *path
, const char *engine
)
186 ENGINE
*e
= ENGINE_by_id("dynamic");
188 if (!ENGINE_ctrl_cmd_string(e
, "ID", engine
, 0) ||
189 !ENGINE_ctrl_cmd_string(e
, "DIR_LOAD", "2", 0) ||
190 !ENGINE_ctrl_cmd_string(e
, "DIR_ADD", path
, 0) ||
191 !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
200 static char *crypto_openssl_version_str
= NULL
;
201 /* Return a human-readable version of the run-time openssl version number. */
203 crypto_openssl_get_version_str(void)
205 if (crypto_openssl_version_str
== NULL
) {
206 const char *raw_version
= SSLeay_version(SSLEAY_VERSION
);
207 const char *end_of_version
= NULL
;
208 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
210 if (!strcmpstart(raw_version
, "OpenSSL ")) {
211 raw_version
+= strlen("OpenSSL ");
212 end_of_version
= strchr(raw_version
, ' ');
216 crypto_openssl_version_str
= tor_strndup(raw_version
,
217 end_of_version
-raw_version
);
219 crypto_openssl_version_str
= tor_strdup(raw_version
);
221 return crypto_openssl_version_str
;
224 /** Initialize the crypto library. Return 0 on success, -1 on failure.
227 crypto_global_init(int useAccel
, const char *accelName
, const char *accelDir
)
229 if (!crypto_global_initialized_
) {
230 ERR_load_crypto_strings();
231 OpenSSL_add_all_algorithms();
232 crypto_global_initialized_
= 1;
233 setup_openssl_threading();
235 if (SSLeay() == OPENSSL_VERSION_NUMBER
&&
236 !strcmp(SSLeay_version(SSLEAY_VERSION
), OPENSSL_VERSION_TEXT
)) {
237 log_info(LD_CRYPTO
, "OpenSSL version matches version from headers "
238 "(%lx: %s).", SSLeay(), SSLeay_version(SSLEAY_VERSION
));
240 log_warn(LD_CRYPTO
, "OpenSSL version from headers does not match the "
241 "version we're running with. If you get weird crashes, that "
242 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
243 (unsigned long)OPENSSL_VERSION_NUMBER
, OPENSSL_VERSION_TEXT
,
244 SSLeay(), SSLeay_version(SSLEAY_VERSION
));
247 if (SSLeay() < OPENSSL_V_SERIES(1,0,0)) {
248 log_notice(LD_CRYPTO
,
249 "Your OpenSSL version seems to be %s. We recommend 1.0.0 "
251 crypto_openssl_get_version_str());
255 #ifdef DISABLE_ENGINES
258 log_warn(LD_CRYPTO
, "No OpenSSL hardware acceleration support enabled.");
262 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
263 ENGINE_load_builtin_engines();
264 ENGINE_register_all_complete();
268 log_info(LD_CRYPTO
, "Trying to load dynamic OpenSSL engine \"%s\""
269 " via path \"%s\".", accelName
, accelDir
);
270 e
= try_load_engine(accelName
, accelDir
);
272 log_info(LD_CRYPTO
, "Initializing dynamic OpenSSL engine \"%s\""
273 " acceleration support.", accelName
);
274 e
= ENGINE_by_id(accelName
);
277 log_warn(LD_CRYPTO
, "Unable to load dynamic OpenSSL engine \"%s\".",
280 log_info(LD_CRYPTO
, "Loaded dynamic OpenSSL engine \"%s\".",
285 log_info(LD_CRYPTO
, "Loaded OpenSSL hardware acceleration engine,"
286 " setting default ciphers.");
287 ENGINE_set_default(e
, ENGINE_METHOD_ALL
);
289 log_engine("RSA", ENGINE_get_default_RSA());
290 log_engine("DH", ENGINE_get_default_DH());
291 log_engine("RAND", ENGINE_get_default_RAND());
292 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
293 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
294 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
297 log_info(LD_CRYPTO
, "NOT using OpenSSL engine support.");
300 evaluate_evp_for_aes(-1);
301 evaluate_ctr_for_aes();
303 return crypto_seed_rng(1);
308 /** Free crypto resources held by this thread. */
310 crypto_thread_cleanup(void)
315 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
317 crypto_new_pk_from_rsa_(RSA
*rsa
)
321 env
= tor_malloc(sizeof(crypto_pk_t
));
327 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
330 crypto_pk_get_rsa_(crypto_pk_t
*env
)
335 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
336 * private is set, include the private-key portion of the key. */
338 crypto_pk_get_evp_pkey_(crypto_pk_t
*env
, int private)
341 EVP_PKEY
*pkey
= NULL
;
342 tor_assert(env
->key
);
344 if (!(key
= RSAPrivateKey_dup(env
->key
)))
347 if (!(key
= RSAPublicKey_dup(env
->key
)))
350 if (!(pkey
= EVP_PKEY_new()))
352 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
363 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
366 crypto_dh_get_dh_(crypto_dh_t
*dh
)
371 /** Allocate and return storage for a public key. The key itself will not yet
381 return crypto_new_pk_from_rsa_(rsa
);
384 /** Release a reference to an asymmetric key; when all the references
385 * are released, free the key.
388 crypto_pk_free(crypto_pk_t
*env
)
395 tor_assert(env
->refs
== 0);
403 /** Allocate and return a new symmetric cipher using the provided key and iv.
404 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
405 * provide NULL in place of either one, it is generated at random.
408 crypto_cipher_new_with_iv(const char *key
, const char *iv
)
410 crypto_cipher_t
*env
;
412 env
= tor_malloc_zero(sizeof(crypto_cipher_t
));
415 crypto_rand(env
->key
, CIPHER_KEY_LEN
);
417 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
419 crypto_rand(env
->iv
, CIPHER_IV_LEN
);
421 memcpy(env
->iv
, iv
, CIPHER_IV_LEN
);
423 env
->cipher
= aes_new_cipher(env
->key
, env
->iv
);
428 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
431 crypto_cipher_new(const char *key
)
433 char zeroiv
[CIPHER_IV_LEN
];
434 memset(zeroiv
, 0, sizeof(zeroiv
));
435 return crypto_cipher_new_with_iv(key
, zeroiv
);
438 /** Free a symmetric cipher.
441 crypto_cipher_free(crypto_cipher_t
*env
)
446 tor_assert(env
->cipher
);
447 aes_cipher_free(env
->cipher
);
448 memwipe(env
, 0, sizeof(crypto_cipher_t
));
452 /* public key crypto */
454 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
455 * Return 0 on success, -1 on failure.
458 crypto_pk_generate_key_with_bits(crypto_pk_t
*env
, int bits
)
466 BIGNUM
*e
= BN_new();
470 if (! BN_set_word(e
, 65537))
475 if (RSA_generate_key_ex(r
, bits
, e
, NULL
) == -1)
488 crypto_log_errors(LOG_WARN
, "generating RSA key");
495 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
496 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
497 * the string is nul-terminated.
499 /* Used here, and used for testing. */
501 crypto_pk_read_private_key_from_string(crypto_pk_t
*env
,
502 const char *s
, ssize_t len
)
508 tor_assert(len
< INT_MAX
&& len
< SSIZE_T_CEILING
);
510 /* Create a read-only memory BIO, backed by the string 's' */
511 b
= BIO_new_mem_buf((char*)s
, (int)len
);
518 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
523 crypto_log_errors(LOG_WARN
, "Error parsing private key");
529 /** Read a PEM-encoded private key from the file named by
530 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
533 crypto_pk_read_private_key_from_filename(crypto_pk_t
*env
,
539 /* Read the file into a string. */
540 contents
= read_file_to_str(keyfile
, 0, NULL
);
542 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
546 /* Try to parse it. */
547 r
= crypto_pk_read_private_key_from_string(env
, contents
, -1);
548 memwipe(contents
, 0, strlen(contents
));
551 return -1; /* read_private_key_from_string already warned, so we don't.*/
553 /* Make sure it's valid. */
554 if (crypto_pk_check_key(env
) <= 0)
560 /** Helper function to implement crypto_pk_write_*_key_to_string. */
562 crypto_pk_write_key_to_string_impl(crypto_pk_t
*env
, char **dest
,
563 size_t *len
, int is_public
)
570 tor_assert(env
->key
);
573 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
577 /* Now you can treat b as if it were a file. Just use the
578 * PEM_*_bio_* functions instead of the non-bio variants.
581 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
583 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
586 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
591 BIO_get_mem_ptr(b
, &buf
);
592 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
595 *dest
= tor_malloc(buf
->length
+1);
596 memcpy(*dest
, buf
->data
, buf
->length
);
597 (*dest
)[buf
->length
] = 0; /* nul terminate it */
604 /** PEM-encode the public key portion of <b>env</b> and write it to a
605 * newly allocated string. On success, set *<b>dest</b> to the new
606 * string, *<b>len</b> to the string's length, and return 0. On
607 * failure, return -1.
610 crypto_pk_write_public_key_to_string(crypto_pk_t
*env
, char **dest
,
613 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
616 /** PEM-encode the private key portion of <b>env</b> and write it to a
617 * newly allocated string. On success, set *<b>dest</b> to the new
618 * string, *<b>len</b> to the string's length, and return 0. On
619 * failure, return -1.
622 crypto_pk_write_private_key_to_string(crypto_pk_t
*env
, char **dest
,
625 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
628 /** Read a PEM-encoded public key from the first <b>len</b> characters of
629 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
633 crypto_pk_read_public_key_from_string(crypto_pk_t
*env
, const char *src
,
640 tor_assert(len
<INT_MAX
);
642 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
646 BIO_write(b
, src
, (int)len
);
650 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
653 crypto_log_errors(LOG_WARN
, "reading public key from string");
660 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
661 * PEM-encoded. Return 0 on success, -1 on failure.
664 crypto_pk_write_private_key_to_filename(crypto_pk_t
*env
,
673 tor_assert(PRIVATE_KEY_OK(env
));
675 if (!(bio
= BIO_new(BIO_s_mem())))
677 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
679 crypto_log_errors(LOG_WARN
, "writing private key");
683 len
= BIO_get_mem_data(bio
, &cp
);
684 tor_assert(len
>= 0);
685 s
= tor_malloc(len
+1);
688 r
= write_str_to_file(fname
, s
, 0);
690 memwipe(s
, 0, strlen(s
));
695 /** Return true iff <b>env</b> has a valid key.
698 crypto_pk_check_key(crypto_pk_t
*env
)
703 r
= RSA_check_key(env
->key
);
705 crypto_log_errors(LOG_WARN
,"checking RSA key");
709 /** Return true iff <b>key</b> contains the private-key portion of the RSA
712 crypto_pk_key_is_private(const crypto_pk_t
*key
)
715 return PRIVATE_KEY_OK(key
);
718 /** Return true iff <b>env</b> contains a public key whose public exponent
722 crypto_pk_public_exponent_ok(crypto_pk_t
*env
)
725 tor_assert(env
->key
);
727 return BN_is_word(env
->key
->e
, 65537);
730 /** Compare the public-key components of a and b. Return less than 0
731 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
732 * considered to be less than all non-NULL keys, and equal to itself.
734 * Note that this may leak information about the keys through timing.
737 crypto_pk_cmp_keys(crypto_pk_t
*a
, crypto_pk_t
*b
)
740 char a_is_non_null
= (a
!= NULL
) && (a
->key
!= NULL
);
741 char b_is_non_null
= (b
!= NULL
) && (b
->key
!= NULL
);
742 char an_argument_is_null
= !a_is_non_null
| !b_is_non_null
;
744 result
= tor_memcmp(&a_is_non_null
, &b_is_non_null
, sizeof(a_is_non_null
));
745 if (an_argument_is_null
)
748 tor_assert(PUBLIC_KEY_OK(a
));
749 tor_assert(PUBLIC_KEY_OK(b
));
750 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
753 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
756 /** Compare the public-key components of a and b. Return non-zero iff
757 * a==b. A NULL key is considered to be distinct from all non-NULL
758 * keys, and equal to itself.
760 * Note that this may leak information about the keys through timing.
763 crypto_pk_eq_keys(crypto_pk_t
*a
, crypto_pk_t
*b
)
765 return (crypto_pk_cmp_keys(a
, b
) == 0);
768 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
770 crypto_pk_keysize(crypto_pk_t
*env
)
773 tor_assert(env
->key
);
775 return (size_t) RSA_size(env
->key
);
778 /** Return the size of the public key modulus of <b>env</b>, in bits. */
780 crypto_pk_num_bits(crypto_pk_t
*env
)
783 tor_assert(env
->key
);
784 tor_assert(env
->key
->n
);
786 return BN_num_bits(env
->key
->n
);
789 /** Increase the reference count of <b>env</b>, and return it.
792 crypto_pk_dup_key(crypto_pk_t
*env
)
795 tor_assert(env
->key
);
801 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
803 crypto_pk_copy_full(crypto_pk_t
*env
)
808 tor_assert(env
->key
);
810 if (PRIVATE_KEY_OK(env
)) {
811 new_key
= RSAPrivateKey_dup(env
->key
);
814 new_key
= RSAPublicKey_dup(env
->key
);
817 log_err(LD_CRYPTO
, "Unable to duplicate a %s key: openssl failed.",
818 privatekey
?"private":"public");
819 crypto_log_errors(LOG_ERR
,
820 privatekey
? "Duplicating a private key" :
821 "Duplicating a public key");
822 tor_fragile_assert();
826 return crypto_new_pk_from_rsa_(new_key
);
829 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
830 * in <b>env</b>, using the padding method <b>padding</b>. On success,
831 * write the result to <b>to</b>, and return the number of bytes
832 * written. On failure, return -1.
834 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
835 * at least the length of the modulus of <b>env</b>.
838 crypto_pk_public_encrypt(crypto_pk_t
*env
, char *to
, size_t tolen
,
839 const char *from
, size_t fromlen
, int padding
)
845 tor_assert(fromlen
<INT_MAX
);
846 tor_assert(tolen
>= crypto_pk_keysize(env
));
848 r
= RSA_public_encrypt((int)fromlen
,
849 (unsigned char*)from
, (unsigned char*)to
,
850 env
->key
, crypto_get_rsa_padding(padding
));
852 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
858 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
859 * in <b>env</b>, using the padding method <b>padding</b>. On success,
860 * write the result to <b>to</b>, and return the number of bytes
861 * written. On failure, return -1.
863 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
864 * at least the length of the modulus of <b>env</b>.
867 crypto_pk_private_decrypt(crypto_pk_t
*env
, char *to
,
869 const char *from
, size_t fromlen
,
870 int padding
, int warnOnFailure
)
876 tor_assert(env
->key
);
877 tor_assert(fromlen
<INT_MAX
);
878 tor_assert(tolen
>= crypto_pk_keysize(env
));
880 /* Not a private key */
883 r
= RSA_private_decrypt((int)fromlen
,
884 (unsigned char*)from
, (unsigned char*)to
,
885 env
->key
, crypto_get_rsa_padding(padding
));
888 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
889 "performing RSA decryption");
895 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
896 * public key in <b>env</b>, using PKCS1 padding. On success, write the
897 * signed data to <b>to</b>, and return the number of bytes written.
898 * On failure, return -1.
900 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
901 * at least the length of the modulus of <b>env</b>.
904 crypto_pk_public_checksig(crypto_pk_t
*env
, char *to
,
906 const char *from
, size_t fromlen
)
912 tor_assert(fromlen
< INT_MAX
);
913 tor_assert(tolen
>= crypto_pk_keysize(env
));
914 r
= RSA_public_decrypt((int)fromlen
,
915 (unsigned char*)from
, (unsigned char*)to
,
916 env
->key
, RSA_PKCS1_PADDING
);
919 crypto_log_errors(LOG_WARN
, "checking RSA signature");
925 /** Check a siglen-byte long signature at <b>sig</b> against
926 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
927 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
928 * SHA1(data). Else return -1.
931 crypto_pk_public_checksig_digest(crypto_pk_t
*env
, const char *data
,
932 size_t datalen
, const char *sig
, size_t siglen
)
934 char digest
[DIGEST_LEN
];
942 tor_assert(datalen
< SIZE_T_CEILING
);
943 tor_assert(siglen
< SIZE_T_CEILING
);
945 if (crypto_digest(digest
,data
,datalen
)<0) {
946 log_warn(LD_BUG
, "couldn't compute digest");
949 buflen
= crypto_pk_keysize(env
);
950 buf
= tor_malloc(buflen
);
951 r
= crypto_pk_public_checksig(env
,buf
,buflen
,sig
,siglen
);
952 if (r
!= DIGEST_LEN
) {
953 log_warn(LD_CRYPTO
, "Invalid signature");
957 if (tor_memneq(buf
, digest
, DIGEST_LEN
)) {
958 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
967 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
968 * <b>env</b>, using PKCS1 padding. On success, write the signature to
969 * <b>to</b>, and return the number of bytes written. On failure, return
972 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
973 * at least the length of the modulus of <b>env</b>.
976 crypto_pk_private_sign(crypto_pk_t
*env
, char *to
, size_t tolen
,
977 const char *from
, size_t fromlen
)
983 tor_assert(fromlen
< INT_MAX
);
984 tor_assert(tolen
>= crypto_pk_keysize(env
));
986 /* Not a private key */
989 r
= RSA_private_encrypt((int)fromlen
,
990 (unsigned char*)from
, (unsigned char*)to
,
991 env
->key
, RSA_PKCS1_PADDING
);
993 crypto_log_errors(LOG_WARN
, "generating RSA signature");
999 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1000 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1001 * store it in <b>to</b>. Return the number of bytes written on
1002 * success, and -1 on failure.
1004 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1005 * at least the length of the modulus of <b>env</b>.
1008 crypto_pk_private_sign_digest(crypto_pk_t
*env
, char *to
, size_t tolen
,
1009 const char *from
, size_t fromlen
)
1012 char digest
[DIGEST_LEN
];
1013 if (crypto_digest(digest
,from
,fromlen
)<0)
1015 r
= crypto_pk_private_sign(env
,to
,tolen
,digest
,DIGEST_LEN
);
1016 memwipe(digest
, 0, sizeof(digest
));
1020 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1021 * bytes of data from <b>from</b>, with padding type 'padding',
1022 * storing the results on <b>to</b>.
1024 * Returns the number of bytes written on success, -1 on failure.
1026 * The encrypted data consists of:
1027 * - The source data, padded and encrypted with the public key, if the
1028 * padded source data is no longer than the public key, and <b>force</b>
1030 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1031 * padded and encrypted with the public key; followed by the rest of
1032 * the source data encrypted in AES-CTR mode with the symmetric key.
1035 crypto_pk_public_hybrid_encrypt(crypto_pk_t
*env
,
1036 char *to
, size_t tolen
,
1039 int padding
, int force
)
1041 int overhead
, outlen
, r
;
1042 size_t pkeylen
, symlen
;
1043 crypto_cipher_t
*cipher
= NULL
;
1049 tor_assert(fromlen
< SIZE_T_CEILING
);
1051 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
1052 pkeylen
= crypto_pk_keysize(env
);
1054 if (!force
&& fromlen
+overhead
<= pkeylen
) {
1055 /* It all fits in a single encrypt. */
1056 return crypto_pk_public_encrypt(env
,to
,
1058 from
,fromlen
,padding
);
1060 tor_assert(tolen
>= fromlen
+ overhead
+ CIPHER_KEY_LEN
);
1061 tor_assert(tolen
>= pkeylen
);
1063 cipher
= crypto_cipher_new(NULL
); /* generate a new key. */
1065 buf
= tor_malloc(pkeylen
+1);
1066 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
1067 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
1069 /* Length of symmetrically encrypted data. */
1070 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
1072 outlen
= crypto_pk_public_encrypt(env
,to
,tolen
,buf
,pkeylen
-overhead
,padding
);
1073 if (outlen
!=(int)pkeylen
) {
1076 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
1077 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
1080 memwipe(buf
, 0, pkeylen
);
1082 crypto_cipher_free(cipher
);
1083 tor_assert(outlen
+symlen
< INT_MAX
);
1084 return (int)(outlen
+ symlen
);
1087 memwipe(buf
, 0, pkeylen
);
1089 crypto_cipher_free(cipher
);
1093 /** Invert crypto_pk_public_hybrid_encrypt. */
1095 crypto_pk_private_hybrid_decrypt(crypto_pk_t
*env
,
1100 int padding
, int warnOnFailure
)
1104 crypto_cipher_t
*cipher
= NULL
;
1107 tor_assert(fromlen
< SIZE_T_CEILING
);
1108 pkeylen
= crypto_pk_keysize(env
);
1110 if (fromlen
<= pkeylen
) {
1111 return crypto_pk_private_decrypt(env
,to
,tolen
,from
,fromlen
,padding
,
1115 buf
= tor_malloc(pkeylen
);
1116 outlen
= crypto_pk_private_decrypt(env
,buf
,pkeylen
,from
,pkeylen
,padding
,
1119 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
1120 "Error decrypting public-key data");
1123 if (outlen
< CIPHER_KEY_LEN
) {
1124 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1125 "No room for a symmetric key");
1128 cipher
= crypto_cipher_new(buf
);
1132 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1133 outlen
-= CIPHER_KEY_LEN
;
1134 tor_assert(tolen
- outlen
>= fromlen
- pkeylen
);
1135 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1138 memwipe(buf
,0,pkeylen
);
1140 crypto_cipher_free(cipher
);
1141 tor_assert(outlen
+ fromlen
< INT_MAX
);
1142 return (int)(outlen
+ (fromlen
-pkeylen
));
1144 memwipe(buf
,0,pkeylen
);
1146 crypto_cipher_free(cipher
);
1150 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1151 * Return -1 on error, or the number of characters used on success.
1154 crypto_pk_asn1_encode(crypto_pk_t
*pk
, char *dest
, size_t dest_len
)
1157 unsigned char *buf
, *cp
;
1158 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1159 if (len
< 0 || (size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
)
1161 cp
= buf
= tor_malloc(len
+1);
1162 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1164 crypto_log_errors(LOG_WARN
,"encoding public key");
1168 /* We don't encode directly into 'dest', because that would be illegal
1169 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1171 memcpy(dest
,buf
,len
);
1176 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1177 * success and NULL on failure.
1180 crypto_pk_asn1_decode(const char *str
, size_t len
)
1184 const unsigned char *cp
;
1185 cp
= buf
= tor_malloc(len
);
1186 memcpy(buf
,str
,len
);
1187 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1190 crypto_log_errors(LOG_WARN
,"decoding public key");
1193 return crypto_new_pk_from_rsa_(rsa
);
1196 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1197 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1198 * Return 0 on success, -1 on failure.
1201 crypto_pk_get_digest(crypto_pk_t
*pk
, char *digest_out
)
1203 unsigned char *buf
, *bufp
;
1206 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1209 buf
= bufp
= tor_malloc(len
+1);
1210 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1212 crypto_log_errors(LOG_WARN
,"encoding public key");
1216 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1224 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1225 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1227 crypto_pk_get_all_digests(crypto_pk_t
*pk
, digests_t
*digests_out
)
1229 unsigned char *buf
, *bufp
;
1232 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1235 buf
= bufp
= tor_malloc(len
+1);
1236 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1238 crypto_log_errors(LOG_WARN
,"encoding public key");
1242 if (crypto_digest_all(digests_out
, (char*)buf
, len
) < 0) {
1250 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1251 * every four spaces. */
1253 add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1256 char *end
= out
+outlen
;
1257 tor_assert(outlen
< SIZE_T_CEILING
);
1259 while (*in
&& out
<end
) {
1261 if (++n
== 4 && *in
&& out
<end
) {
1266 tor_assert(out
<end
);
1270 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1271 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1272 * space). Return 0 on success, -1 on failure.
1274 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1275 * of the public key, converted to hexadecimal, in upper case, with a
1276 * space after every four digits.
1278 * If <b>add_space</b> is false, omit the spaces.
1281 crypto_pk_get_fingerprint(crypto_pk_t
*pk
, char *fp_out
, int add_space
)
1283 char digest
[DIGEST_LEN
];
1284 char hexdigest
[HEX_DIGEST_LEN
+1];
1285 if (crypto_pk_get_digest(pk
, digest
)) {
1288 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1290 add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1292 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1297 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1300 crypto_pk_check_fingerprint_syntax(const char *s
)
1303 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1305 if (!TOR_ISSPACE(s
[i
])) return 0;
1307 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1310 if (s
[FINGERPRINT_LEN
]) return 0;
1314 /* symmetric crypto */
1316 /** Return a pointer to the key set for the cipher in <b>env</b>.
1319 crypto_cipher_get_key(crypto_cipher_t
*env
)
1324 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1325 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1326 * On failure, return -1.
1329 crypto_cipher_encrypt(crypto_cipher_t
*env
, char *to
,
1330 const char *from
, size_t fromlen
)
1333 tor_assert(env
->cipher
);
1335 tor_assert(fromlen
);
1337 tor_assert(fromlen
< SIZE_T_CEILING
);
1339 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1343 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1344 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1345 * On failure, return -1.
1348 crypto_cipher_decrypt(crypto_cipher_t
*env
, char *to
,
1349 const char *from
, size_t fromlen
)
1354 tor_assert(fromlen
< SIZE_T_CEILING
);
1356 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1360 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1361 * on success, return 0. On failure, return -1.
1364 crypto_cipher_crypt_inplace(crypto_cipher_t
*env
, char *buf
, size_t len
)
1366 tor_assert(len
< SIZE_T_CEILING
);
1367 aes_crypt_inplace(env
->cipher
, buf
, len
);
1371 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1372 * <b>key</b> to the buffer in <b>to</b> of length
1373 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1374 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1375 * number of bytes written, on failure, return -1.
1378 crypto_cipher_encrypt_with_iv(const char *key
,
1379 char *to
, size_t tolen
,
1380 const char *from
, size_t fromlen
)
1382 crypto_cipher_t
*cipher
;
1385 tor_assert(fromlen
< INT_MAX
);
1389 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1392 cipher
= crypto_cipher_new_with_iv(key
, NULL
);
1394 memcpy(to
, cipher
->iv
, CIPHER_IV_LEN
);
1395 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1396 crypto_cipher_free(cipher
);
1397 return (int)(fromlen
+ CIPHER_IV_LEN
);
1400 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1401 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1402 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1403 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1404 * number of bytes written, on failure, return -1.
1407 crypto_cipher_decrypt_with_iv(const char *key
,
1408 char *to
, size_t tolen
,
1409 const char *from
, size_t fromlen
)
1411 crypto_cipher_t
*cipher
;
1415 tor_assert(fromlen
< INT_MAX
);
1417 if (fromlen
<= CIPHER_IV_LEN
)
1419 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1422 cipher
= crypto_cipher_new_with_iv(key
, from
);
1424 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1425 crypto_cipher_free(cipher
);
1426 return (int)(fromlen
- CIPHER_IV_LEN
);
1431 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1432 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1433 * Return 0 on success, -1 on failure.
1436 crypto_digest(char *digest
, const char *m
, size_t len
)
1440 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1443 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1444 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1445 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1447 crypto_digest256(char *digest
, const char *m
, size_t len
,
1448 digest_algorithm_t algorithm
)
1452 tor_assert(algorithm
== DIGEST_SHA256
);
1453 return (SHA256((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1456 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1457 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1458 * success, -1 on failure. */
1460 crypto_digest_all(digests_t
*ds_out
, const char *m
, size_t len
)
1464 memset(ds_out
, 0, sizeof(*ds_out
));
1465 if (crypto_digest(ds_out
->d
[DIGEST_SHA1
], m
, len
) < 0)
1467 for (i
= DIGEST_SHA256
; i
< N_DIGEST_ALGORITHMS
; ++i
) {
1468 if (crypto_digest256(ds_out
->d
[i
], m
, len
, i
) < 0)
1474 /** Return the name of an algorithm, as used in directory documents. */
1476 crypto_digest_algorithm_get_name(digest_algorithm_t alg
)
1484 tor_fragile_assert();
1485 return "??unknown_digest??";
1489 /** Given the name of a digest algorithm, return its integer value, or -1 if
1490 * the name is not recognized. */
1492 crypto_digest_algorithm_parse_name(const char *name
)
1494 if (!strcmp(name
, "sha1"))
1496 else if (!strcmp(name
, "sha256"))
1497 return DIGEST_SHA256
;
1502 /** Intermediate information about the digest of a stream of data. */
1503 struct crypto_digest_t
{
1505 SHA_CTX sha1
; /**< state for SHA1 */
1506 SHA256_CTX sha2
; /**< state for SHA256 */
1507 } d
; /**< State for the digest we're using. Only one member of the
1508 * union is usable, depending on the value of <b>algorithm</b>. */
1509 ENUM_BF(digest_algorithm_t
) algorithm
: 8; /**< Which algorithm is in use? */
1512 /** Allocate and return a new digest object to compute SHA1 digests.
1515 crypto_digest_new(void)
1518 r
= tor_malloc(sizeof(crypto_digest_t
));
1519 SHA1_Init(&r
->d
.sha1
);
1520 r
->algorithm
= DIGEST_SHA1
;
1524 /** Allocate and return a new digest object to compute 256-bit digests
1525 * using <b>algorithm</b>. */
1527 crypto_digest256_new(digest_algorithm_t algorithm
)
1530 tor_assert(algorithm
== DIGEST_SHA256
);
1531 r
= tor_malloc(sizeof(crypto_digest_t
));
1532 SHA256_Init(&r
->d
.sha2
);
1533 r
->algorithm
= algorithm
;
1537 /** Deallocate a digest object.
1540 crypto_digest_free(crypto_digest_t
*digest
)
1544 memwipe(digest
, 0, sizeof(crypto_digest_t
));
1548 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1551 crypto_digest_add_bytes(crypto_digest_t
*digest
, const char *data
,
1556 /* Using the SHA*_*() calls directly means we don't support doing
1557 * SHA in hardware. But so far the delay of getting the question
1558 * to the hardware, and hearing the answer, is likely higher than
1559 * just doing it ourselves. Hashes are fast.
1561 switch (digest
->algorithm
) {
1563 SHA1_Update(&digest
->d
.sha1
, (void*)data
, len
);
1566 SHA256_Update(&digest
->d
.sha2
, (void*)data
, len
);
1569 tor_fragile_assert();
1574 /** Compute the hash of the data that has been passed to the digest
1575 * object; write the first out_len bytes of the result to <b>out</b>.
1576 * <b>out_len</b> must be \<= DIGEST256_LEN.
1579 crypto_digest_get_digest(crypto_digest_t
*digest
,
1580 char *out
, size_t out_len
)
1582 unsigned char r
[DIGEST256_LEN
];
1583 crypto_digest_t tmpenv
;
1586 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1587 memcpy(&tmpenv
, digest
, sizeof(crypto_digest_t
));
1588 switch (digest
->algorithm
) {
1590 tor_assert(out_len
<= DIGEST_LEN
);
1591 SHA1_Final(r
, &tmpenv
.d
.sha1
);
1594 tor_assert(out_len
<= DIGEST256_LEN
);
1595 SHA256_Final(r
, &tmpenv
.d
.sha2
);
1598 log_warn(LD_BUG
, "Called with unknown algorithm %d", digest
->algorithm
);
1599 /* If fragile_assert is not enabled, then we should at least not
1601 memset(r
, 0xff, sizeof(r
));
1602 tor_fragile_assert();
1605 memcpy(out
, r
, out_len
);
1606 memwipe(r
, 0, sizeof(r
));
1609 /** Allocate and return a new digest object with the same state as
1613 crypto_digest_dup(const crypto_digest_t
*digest
)
1617 r
= tor_malloc(sizeof(crypto_digest_t
));
1618 memcpy(r
,digest
,sizeof(crypto_digest_t
));
1622 /** Replace the state of the digest object <b>into</b> with the state
1623 * of the digest object <b>from</b>.
1626 crypto_digest_assign(crypto_digest_t
*into
,
1627 const crypto_digest_t
*from
)
1631 memcpy(into
,from
,sizeof(crypto_digest_t
));
1634 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1635 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1636 * in <b>hmac_out</b>.
1639 crypto_hmac_sha1(char *hmac_out
,
1640 const char *key
, size_t key_len
,
1641 const char *msg
, size_t msg_len
)
1643 tor_assert(key_len
< INT_MAX
);
1644 tor_assert(msg_len
< INT_MAX
);
1645 HMAC(EVP_sha1(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1646 (unsigned char*)hmac_out
, NULL
);
1649 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1650 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
1651 * result in <b>hmac_out</b>.
1654 crypto_hmac_sha256(char *hmac_out
,
1655 const char *key
, size_t key_len
,
1656 const char *msg
, size_t msg_len
)
1658 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1659 tor_assert(key_len
< INT_MAX
);
1660 tor_assert(msg_len
< INT_MAX
);
1661 HMAC(EVP_sha256(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1662 (unsigned char*)hmac_out
, NULL
);
1667 /** Our DH 'g' parameter */
1668 #define DH_GENERATOR 2
1670 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1671 static BIGNUM
*dh_param_p
= NULL
;
1672 /** Shared P parameter for our TLS DH key exchanges. */
1673 static BIGNUM
*dh_param_p_tls
= NULL
;
1674 /** Shared G parameter for our DH key exchanges. */
1675 static BIGNUM
*dh_param_g
= NULL
;
1677 /** Generate and return a reasonable and safe DH parameter p. */
1679 crypto_generate_dynamic_dh_modulus(void)
1681 BIGNUM
*dynamic_dh_modulus
;
1686 dynamic_dh_modulus
= BN_new();
1687 tor_assert(dynamic_dh_modulus
);
1689 dh_parameters
= DH_generate_parameters(DH_BYTES
*8, DH_GENERATOR
, NULL
, NULL
);
1690 tor_assert(dh_parameters
);
1692 r
= DH_check(dh_parameters
, &dh_codes
);
1693 tor_assert(r
&& !dh_codes
);
1695 BN_copy(dynamic_dh_modulus
, dh_parameters
->p
);
1696 tor_assert(dynamic_dh_modulus
);
1698 DH_free(dh_parameters
);
1700 { /* log the dynamic DH modulus: */
1701 s
= BN_bn2hex(dynamic_dh_modulus
);
1703 log_info(LD_OR
, "Dynamic DH modulus generated: [%s]", s
);
1707 return dynamic_dh_modulus
;
1710 /** Store our dynamic DH modulus (and its group parameters) to
1711 <b>fname</b> for future use. */
1713 crypto_store_dynamic_dh_modulus(const char *fname
)
1717 unsigned char *dh_string_repr
= NULL
, *cp
= NULL
;
1718 char *base64_encoded_dh
= NULL
;
1719 char *file_string
= NULL
;
1721 static const char file_header
[] = "# This file contains stored Diffie-"
1722 "Hellman parameters for future use.\n# You *do not* need to edit this "
1727 if (!dh_param_p_tls
) {
1728 log_info(LD_CRYPTO
, "Tried to store a DH modulus that does not exist.");
1732 if (!(dh
= DH_new()))
1734 if (!(dh
->p
= BN_dup(dh_param_p_tls
)))
1736 if (!(dh
->g
= BN_new()))
1738 if (!BN_set_word(dh
->g
, DH_GENERATOR
))
1741 len
= i2d_DHparams(dh
, NULL
);
1743 log_warn(LD_CRYPTO
, "Error occured while DER encoding DH modulus (1).");
1747 cp
= dh_string_repr
= tor_malloc_zero(len
+1);
1748 len
= i2d_DHparams(dh
, &cp
);
1749 if ((len
< 0) || ((cp
- dh_string_repr
) != len
)) {
1750 log_warn(LD_CRYPTO
, "Error occured while DER encoding DH modulus (2).");
1754 base64_encoded_dh
= tor_malloc_zero(len
* 2); /* should be enough */
1755 new_len
= base64_encode(base64_encoded_dh
, len
* 2,
1756 (char *)dh_string_repr
, len
);
1758 log_warn(LD_CRYPTO
, "Error occured while base64-encoding DH modulus.");
1762 /* concatenate file header and the dh parameters blob */
1763 new_len
= tor_asprintf(&file_string
, "%s%s", file_header
, base64_encoded_dh
);
1766 if (write_bytes_to_new_file(fname
, file_string
, new_len
, 0) < 0) {
1767 log_info(LD_CRYPTO
, "'%s' was already occupied.", fname
);
1776 tor_free(dh_string_repr
);
1777 tor_free(base64_encoded_dh
);
1778 tor_free(file_string
);
1783 /** Return the dynamic DH modulus stored in <b>fname</b>. If there is no
1784 dynamic DH modulus stored in <b>fname</b>, return NULL. */
1786 crypto_get_stored_dynamic_dh_modulus(const char *fname
)
1789 char *contents
= NULL
;
1790 const char *contents_tmp
= NULL
;
1792 DH
*stored_dh
= NULL
;
1793 BIGNUM
*dynamic_dh_modulus
= NULL
;
1795 unsigned char *base64_decoded_dh
= NULL
;
1796 const unsigned char *cp
= NULL
;
1800 contents
= read_file_to_str(fname
, RFTS_IGNORE_MISSING
, NULL
);
1802 log_info(LD_CRYPTO
, "Could not open file '%s'", fname
);
1803 goto done
; /*usually means that ENOENT. don't try to move file to broken.*/
1806 /* skip the file header */
1807 contents_tmp
= eat_whitespace(contents
);
1808 if (!*contents_tmp
) {
1809 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus file "
1810 "seems corrupted (eat_whitespace).");
1814 /* 'fname' contains the DH parameters stored in base64-ed DER
1815 * format. We are only interested in the DH modulus.
1816 * NOTE: We allocate more storage here than we need. Since we're already
1817 * doing that, we can also add 1 byte extra to appease Coverity's
1820 cp
= base64_decoded_dh
= tor_malloc_zero(strlen(contents_tmp
) + 1);
1821 length
= base64_decode((char *)base64_decoded_dh
, strlen(contents_tmp
),
1822 contents_tmp
, strlen(contents_tmp
));
1824 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus seems corrupted (base64).");
1828 stored_dh
= d2i_DHparams(NULL
, &cp
, length
);
1829 if ((!stored_dh
) || (cp
- base64_decoded_dh
!= length
)) {
1830 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus seems corrupted (d2i).");
1834 { /* check the cryptographic qualities of the stored dynamic DH modulus: */
1835 retval
= DH_check(stored_dh
, &dh_codes
);
1836 if (!retval
|| dh_codes
) {
1837 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus is not a safe prime.");
1841 retval
= DH_size(stored_dh
);
1842 if (retval
< DH_BYTES
) {
1843 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus is smaller "
1844 "than '%d' bits.", DH_BYTES
*8);
1848 if (!BN_is_word(stored_dh
->g
, 2)) {
1849 log_warn(LD_CRYPTO
, "Stored dynamic DH parameters do not use '2' "
1850 "as the group generator.");
1855 { /* log the dynamic DH modulus: */
1856 char *s
= BN_bn2hex(stored_dh
->p
);
1858 log_info(LD_OR
, "Found stored dynamic DH modulus: [%s]", s
);
1867 /* move broken prime to $filename.broken */
1868 char *fname_new
=NULL
;
1869 tor_asprintf(&fname_new
, "%s.broken", fname
);
1871 log_warn(LD_CRYPTO
, "Moving broken dynamic DH prime to '%s'.", fname_new
);
1873 if (replace_file(fname
, fname_new
))
1874 log_notice(LD_CRYPTO
, "Error while moving '%s' to '%s'.",
1877 tor_free(fname_new
);
1887 tor_free(base64_decoded_dh
);
1890 dynamic_dh_modulus
= BN_dup(stored_dh
->p
);
1894 return dynamic_dh_modulus
;
1897 /** Set the global TLS Diffie-Hellman modulus.
1898 * If <b>dynamic_dh_modulus_fname</b> is set, try to read a dynamic DH modulus
1899 * off it and use it as the DH modulus. If that's not possible,
1900 * generate a new dynamic DH modulus.
1901 * If <b>dynamic_dh_modulus_fname</b> is NULL, use the Apache mod_ssl DH
1904 crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname
)
1906 BIGNUM
*tls_prime
= NULL
;
1907 int store_dh_prime_afterwards
= 0;
1910 /* If the space is occupied, free the previous TLS DH prime */
1911 if (dh_param_p_tls
) {
1912 BN_free(dh_param_p_tls
);
1913 dh_param_p_tls
= NULL
;
1916 if (dynamic_dh_modulus_fname
) { /* use dynamic DH modulus: */
1917 log_info(LD_OR
, "Using stored dynamic DH modulus.");
1918 tls_prime
= crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname
);
1921 log_notice(LD_OR
, "Generating fresh dynamic DH modulus. "
1922 "This might take a while...");
1923 tls_prime
= crypto_generate_dynamic_dh_modulus();
1925 store_dh_prime_afterwards
++;
1927 } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
1928 tls_prime
= BN_new();
1929 tor_assert(tls_prime
);
1931 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1932 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
1935 r
=BN_hex2bn(&tls_prime
,
1936 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1937 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1938 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1939 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1940 "B0E7393E0F24218EB3");
1944 tor_assert(tls_prime
);
1946 dh_param_p_tls
= tls_prime
;
1948 if (store_dh_prime_afterwards
)
1949 /* save the new dynamic DH modulus to disk. */
1950 if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname
)) {
1951 log_notice(LD_CRYPTO
, "Failed while storing dynamic DH modulus. "
1952 "Make sure your data directory is sane.");
1956 /** Initialize dh_param_p and dh_param_g if they are not already
1961 BIGNUM
*circuit_dh_prime
, *generator
;
1963 if (dh_param_p
&& dh_param_g
)
1966 circuit_dh_prime
= BN_new();
1967 generator
= BN_new();
1968 tor_assert(circuit_dh_prime
&& generator
);
1970 /* Set our generator for all DH parameters */
1971 r
= BN_set_word(generator
, DH_GENERATOR
);
1974 /* This is from rfc2409, section 6.2. It's a safe prime, and
1975 supposedly it equals:
1976 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1978 r
= BN_hex2bn(&circuit_dh_prime
,
1979 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1980 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1981 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1982 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1983 "49286651ECE65381FFFFFFFFFFFFFFFF");
1986 /* Set the new values as the global DH parameters. */
1987 dh_param_p
= circuit_dh_prime
;
1988 dh_param_g
= generator
;
1990 /* Ensure that we have TLS DH parameters set up, too, even if we're
1991 going to change them soon. */
1992 if (!dh_param_p_tls
) {
1993 crypto_set_tls_dh_prime(NULL
);
1997 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
1998 * handshake. Since we exponentiate by this value, choosing a smaller one
1999 * lets our handhake go faster.
2001 #define DH_PRIVATE_KEY_BITS 320
2003 /** Allocate and return a new DH object for a key exchange.
2006 crypto_dh_new(int dh_type
)
2008 crypto_dh_t
*res
= tor_malloc_zero(sizeof(crypto_dh_t
));
2010 tor_assert(dh_type
== DH_TYPE_CIRCUIT
|| dh_type
== DH_TYPE_TLS
||
2011 dh_type
== DH_TYPE_REND
);
2016 if (!(res
->dh
= DH_new()))
2019 if (dh_type
== DH_TYPE_TLS
) {
2020 if (!(res
->dh
->p
= BN_dup(dh_param_p_tls
)))
2023 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
2027 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
2030 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
2034 crypto_log_errors(LOG_WARN
, "creating DH object");
2035 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
2040 /** Return a copy of <b>dh</b>, sharing its internal state. */
2042 crypto_dh_dup(const crypto_dh_t
*dh
)
2044 crypto_dh_t
*dh_new
= tor_malloc_zero(sizeof(crypto_dh_t
));
2045 dh_new
->dh
= dh
->dh
;
2050 /** Return the length of the DH key in <b>dh</b>, in bytes.
2053 crypto_dh_get_bytes(crypto_dh_t
*dh
)
2056 return DH_size(dh
->dh
);
2059 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2060 * success, -1 on failure.
2063 crypto_dh_generate_public(crypto_dh_t
*dh
)
2066 if (!DH_generate_key(dh
->dh
)) {
2067 crypto_log_errors(LOG_WARN
, "generating DH key");
2070 if (tor_check_dh_key(LOG_WARN
, dh
->dh
->pub_key
)<0) {
2071 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
2072 "the-universe chances really do happen. Trying again.");
2073 /* Free and clear the keys, so OpenSSL will actually try again. */
2074 BN_free(dh
->dh
->pub_key
);
2075 BN_free(dh
->dh
->priv_key
);
2076 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
2082 /** Generate g^x as necessary, and write the g^x for the key exchange
2083 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2084 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2087 crypto_dh_get_public(crypto_dh_t
*dh
, char *pubkey
, size_t pubkey_len
)
2091 if (!dh
->dh
->pub_key
) {
2092 if (crypto_dh_generate_public(dh
)<0)
2096 tor_assert(dh
->dh
->pub_key
);
2097 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
2098 tor_assert(bytes
>= 0);
2099 if (pubkey_len
< (size_t)bytes
) {
2101 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2102 (int) pubkey_len
, bytes
);
2106 memset(pubkey
, 0, pubkey_len
);
2107 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
2112 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2113 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2114 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2117 tor_check_dh_key(int severity
, BIGNUM
*bn
)
2127 if (BN_cmp(bn
,x
)<=0) {
2128 log_fn(severity
, LD_CRYPTO
, "DH key must be at least 2.");
2131 BN_copy(x
,dh_param_p
);
2133 if (BN_cmp(bn
,x
)>=0) {
2134 log_fn(severity
, LD_CRYPTO
, "DH key must be at most p-2.");
2142 log_fn(severity
, LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
2148 #define MIN(a,b) ((a)<(b)?(a):(b))
2149 /** Given a DH key exchange object, and our peer's value of g^y (as a
2150 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2151 * <b>secret_bytes_out</b> bytes of shared key material and write them
2152 * to <b>secret_out</b>. Return the number of bytes generated on success,
2155 * (We generate key material by computing
2156 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2157 * where || is concatenation.)
2160 crypto_dh_compute_secret(int severity
, crypto_dh_t
*dh
,
2161 const char *pubkey
, size_t pubkey_len
,
2162 char *secret_out
, size_t secret_bytes_out
)
2164 char *secret_tmp
= NULL
;
2165 BIGNUM
*pubkey_bn
= NULL
;
2166 size_t secret_len
=0, secret_tmp_len
=0;
2169 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
2170 tor_assert(pubkey_len
< INT_MAX
);
2172 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
2173 (int)pubkey_len
, NULL
)))
2175 if (tor_check_dh_key(severity
, pubkey_bn
)<0) {
2176 /* Check for invalid public keys. */
2177 log_fn(severity
, LD_CRYPTO
,"Rejected invalid g^x");
2180 secret_tmp_len
= crypto_dh_get_bytes(dh
);
2181 secret_tmp
= tor_malloc(secret_tmp_len
);
2182 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
2184 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
2187 secret_len
= result
;
2188 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp
, secret_len
,
2189 (uint8_t*)secret_out
, secret_bytes_out
)<0)
2191 secret_len
= secret_bytes_out
;
2197 crypto_log_errors(LOG_WARN
, "completing DH handshake");
2201 memwipe(secret_tmp
, 0, secret_tmp_len
);
2202 tor_free(secret_tmp
);
2210 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2211 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2212 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2213 * H(K | [00]) | H(K | [01]) | ....
2215 * This is the key expansion algorithm used in the "TAP" circuit extension
2216 * mechanism; it shouldn't be used for new protocols.
2218 * Return 0 on success, -1 on failure.
2221 crypto_expand_key_material_TAP(const uint8_t *key_in
, size_t key_in_len
,
2222 uint8_t *key_out
, size_t key_out_len
)
2225 uint8_t *cp
, *tmp
= tor_malloc(key_in_len
+1);
2226 uint8_t digest
[DIGEST_LEN
];
2228 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2229 tor_assert(key_out_len
<= DIGEST_LEN
*256);
2231 memcpy(tmp
, key_in
, key_in_len
);
2232 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
2233 ++i
, cp
+= DIGEST_LEN
) {
2234 tmp
[key_in_len
] = i
;
2235 if (crypto_digest((char*)digest
, (const char *)tmp
, key_in_len
+1))
2237 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
2239 memwipe(tmp
, 0, key_in_len
+1);
2241 memwipe(digest
, 0, sizeof(digest
));
2245 memwipe(tmp
, 0, key_in_len
+1);
2247 memwipe(digest
, 0, sizeof(digest
));
2251 /** Expand some secret key material according to RFC5869, using SHA256 as the
2252 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2253 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2254 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2255 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2256 * bytes to <b>key_out</b> and return 0. On failure, return -1.
2259 crypto_expand_key_material_rfc5869_sha256(
2260 const uint8_t *key_in
, size_t key_in_len
,
2261 const uint8_t *salt_in
, size_t salt_in_len
,
2262 const uint8_t *info_in
, size_t info_in_len
,
2263 uint8_t *key_out
, size_t key_out_len
)
2265 uint8_t prk
[DIGEST256_LEN
];
2266 uint8_t tmp
[DIGEST256_LEN
+ 128 + 1];
2267 uint8_t mac
[DIGEST256_LEN
];
2272 crypto_hmac_sha256((char*)prk
,
2273 (const char*)salt_in
, salt_in_len
,
2274 (const char*)key_in
, key_in_len
);
2276 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2277 tor_assert(key_out_len
<= DIGEST256_LEN
* 256);
2278 tor_assert(info_in_len
<= 128);
2279 memset(tmp
, 0, sizeof(tmp
));
2283 while (key_out_len
) {
2286 memcpy(tmp
, mac
, DIGEST256_LEN
);
2287 memcpy(tmp
+DIGEST256_LEN
, info_in
, info_in_len
);
2288 tmp
[DIGEST256_LEN
+info_in_len
] = i
;
2289 tmp_len
= DIGEST256_LEN
+ info_in_len
+ 1;
2291 memcpy(tmp
, info_in
, info_in_len
);
2292 tmp
[info_in_len
] = i
;
2293 tmp_len
= info_in_len
+ 1;
2295 crypto_hmac_sha256((char*)mac
,
2296 (const char*)prk
, DIGEST256_LEN
,
2297 (const char*)tmp
, tmp_len
);
2298 n
= key_out_len
< DIGEST256_LEN
? key_out_len
: DIGEST256_LEN
;
2299 memcpy(outp
, mac
, n
);
2305 memwipe(tmp
, 0, sizeof(tmp
));
2306 memwipe(mac
, 0, sizeof(mac
));
2310 /** Free a DH key exchange object.
2313 crypto_dh_free(crypto_dh_t
*dh
)
2322 /* random numbers */
2324 /** How many bytes of entropy we add at once.
2326 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2327 * work for us too. */
2328 #define ADD_ENTROPY 32
2330 /** True iff it's safe to use RAND_poll after setup.
2332 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2333 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2334 * that fd without checking whether it fit in the fd_set. Thus, if the
2335 * system has not just been started up, it is unsafe to call */
2336 #define RAND_POLL_IS_SAFE \
2337 (OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2339 /** Set the seed of the weak RNG to a random value. */
2341 crypto_seed_weak_rng(tor_weak_rng_t
*rng
)
2344 crypto_rand((void*)&seed
, sizeof(seed
));
2345 tor_init_weak_random(rng
, seed
);
2348 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2349 * storing it into <b>out</b>.
2352 crypto_strongest_rand(uint8_t *out
, size_t out_len
)
2355 static int provider_set
= 0;
2356 static HCRYPTPROV provider
;
2358 static const char *filenames
[] = {
2359 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2366 if (!provider_set
) {
2367 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
2368 CRYPT_VERIFYCONTEXT
)) {
2369 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
2370 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
2376 if (!CryptGenRandom(provider
, out_len
, out
)) {
2377 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
2383 for (i
= 0; filenames
[i
]; ++i
) {
2384 fd
= open(filenames
[i
], O_RDONLY
, 0);
2386 log_info(LD_CRYPTO
, "Reading entropy from \"%s\"", filenames
[i
]);
2387 n
= read_all(fd
, (char*)out
, out_len
, 0);
2391 "Error reading from entropy source (read only %lu bytes).",
2399 log_warn(LD_CRYPTO
, "Cannot get strong entropy: no entropy source found.");
2404 /** Seed OpenSSL's random number generator with bytes from the operating
2405 * system. <b>startup</b> should be true iff we have just started Tor and
2406 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2409 crypto_seed_rng(int startup
)
2411 int rand_poll_ok
= 0, load_entropy_ok
= 0;
2412 uint8_t buf
[ADD_ENTROPY
];
2414 /* OpenSSL has a RAND_poll function that knows about more kinds of
2415 * entropy than we do. We'll try calling that, *and* calling our own entropy
2416 * functions. If one succeeds, we'll accept the RNG as seeded. */
2417 if (startup
|| RAND_POLL_IS_SAFE
) {
2418 rand_poll_ok
= RAND_poll();
2419 if (rand_poll_ok
== 0)
2420 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
2423 load_entropy_ok
= !crypto_strongest_rand(buf
, sizeof(buf
));
2424 if (load_entropy_ok
) {
2425 RAND_seed(buf
, sizeof(buf
));
2428 memwipe(buf
, 0, sizeof(buf
));
2430 if (rand_poll_ok
|| load_entropy_ok
)
2436 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2437 * success, -1 on failure.
2440 crypto_rand(char *to
, size_t n
)
2443 tor_assert(n
< INT_MAX
);
2445 r
= RAND_bytes((unsigned char*)to
, (int)n
);
2447 crypto_log_errors(LOG_WARN
, "generating random data");
2448 return (r
== 1) ? 0 : -1;
2451 /** Return a pseudorandom integer, chosen uniformly from the values
2452 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2453 * INT_MAX+1, inclusive. */
2455 crypto_rand_int(unsigned int max
)
2458 unsigned int cutoff
;
2459 tor_assert(max
<= ((unsigned int)INT_MAX
)+1);
2460 tor_assert(max
> 0); /* don't div by 0 */
2462 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2463 * distribution with clipping at the upper end of unsigned int's
2466 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
2468 crypto_rand((char*)&val
, sizeof(val
));
2474 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2475 * between 0 and <b>max</b>-1. */
2477 crypto_rand_uint64(uint64_t max
)
2481 tor_assert(max
< UINT64_MAX
);
2482 tor_assert(max
> 0); /* don't div by 0 */
2484 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2485 * distribution with clipping at the upper end of unsigned int's
2488 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
2490 crypto_rand((char*)&val
, sizeof(val
));
2496 /** Return a pseudorandom double d, chosen uniformly from the range
2500 crypto_rand_double(void)
2502 /* We just use an unsigned int here; we don't really care about getting
2503 * more than 32 bits of resolution */
2505 crypto_rand((char*)&uint
, sizeof(uint
));
2507 #define UINT_MAX_AS_DOUBLE 4294967296.0
2508 #elif SIZEOF_INT == 8
2509 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2511 #error SIZEOF_INT is neither 4 nor 8
2513 return ((double)uint
) / UINT_MAX_AS_DOUBLE
;
2516 /** Generate and return a new random hostname starting with <b>prefix</b>,
2517 * ending with <b>suffix</b>, and containing no fewer than
2518 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2519 * characters between.
2521 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2524 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
2527 char *result
, *rand_bytes
;
2528 int randlen
, rand_bytes_len
;
2529 size_t resultlen
, prefixlen
;
2531 if (max_rand_len
> MAX_DNS_LABEL_SIZE
)
2532 max_rand_len
= MAX_DNS_LABEL_SIZE
;
2533 if (min_rand_len
> max_rand_len
)
2534 min_rand_len
= max_rand_len
;
2536 randlen
= min_rand_len
+ crypto_rand_int(max_rand_len
- min_rand_len
+ 1);
2538 prefixlen
= strlen(prefix
);
2539 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
2541 rand_bytes_len
= ((randlen
*5)+7)/8;
2542 if (rand_bytes_len
% 5)
2543 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
2544 rand_bytes
= tor_malloc(rand_bytes_len
);
2545 crypto_rand(rand_bytes
, rand_bytes_len
);
2547 result
= tor_malloc(resultlen
);
2548 memcpy(result
, prefix
, prefixlen
);
2549 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
2550 rand_bytes
, rand_bytes_len
);
2551 tor_free(rand_bytes
);
2552 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
2557 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2560 smartlist_choose(const smartlist_t
*sl
)
2562 int len
= smartlist_len(sl
);
2564 return smartlist_get(sl
,crypto_rand_int(len
));
2565 return NULL
; /* no elements to choose from */
2568 /** Scramble the elements of <b>sl</b> into a random order. */
2570 smartlist_shuffle(smartlist_t
*sl
)
2573 /* From the end of the list to the front, choose at random from the
2574 positions we haven't looked at yet, and swap that position into the
2575 current position. Remember to give "no swap" the same probability as
2577 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
2578 int j
= crypto_rand_int(i
+1);
2579 smartlist_swap(sl
, i
, j
);
2583 /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2584 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2585 * bytes. Return the number of bytes written on success; -1 if
2586 * destlen is too short, or other failure.
2589 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2591 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2592 * it ever shows up in the profile. */
2595 tor_assert(srclen
< INT_MAX
);
2597 /* 48 bytes of input -> 64 bytes of output plus newline.
2598 Plus one more byte, in case I'm wrong.
2600 if (destlen
< ((srclen
/48)+1)*66)
2602 if (destlen
> SIZE_T_CEILING
)
2605 EVP_EncodeInit(&ctx
);
2606 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2607 (unsigned char*)src
, (int)srclen
);
2608 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
2614 /** Special values used for the base64_decode_table */
2619 /** Internal table mapping byte values to what they represent in base64.
2620 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2621 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2623 static const uint8_t base64_decode_table
[256] = {
2624 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
2625 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2626 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
2627 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
2628 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2629 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
2630 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2631 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
2632 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2633 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2634 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2635 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2636 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2637 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2638 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2639 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2642 /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2643 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2644 * bytes. Return the number of bytes written on success; -1 if
2645 * destlen is too short, or other failure.
2647 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2648 * spaces or padding.
2650 * NOTE 2: This implementation does not check for the correct number of
2651 * padding "=" characters at the end of the string, and does not check
2652 * for internal padding characters.
2655 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2657 #ifdef USE_OPENSSL_BASE64
2660 /* 64 bytes of input -> *up to* 48 bytes of output.
2661 Plus one more byte, in case I'm wrong.
2663 if (destlen
< ((srclen
/64)+1)*49)
2665 if (destlen
> SIZE_T_CEILING
)
2668 EVP_DecodeInit(&ctx
);
2669 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2670 (unsigned char*)src
, srclen
);
2671 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
2675 const char *eos
= src
+srclen
;
2678 char *dest_orig
= dest
;
2680 /* Max number of bits == srclen*6.
2681 * Number of bytes required to hold all bits == (srclen*6)/8.
2682 * Yes, we want to round down: anything that hangs over the end of a
2683 * byte is padding. */
2684 if (destlen
< (srclen
*3)/4)
2686 if (destlen
> SIZE_T_CEILING
)
2689 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2690 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2691 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2693 for ( ; src
< eos
; ++src
) {
2694 unsigned char c
= (unsigned char) *src
;
2695 uint8_t v
= base64_decode_table
[c
];
2698 /* This character isn't allowed in base64. */
2701 /* This character is whitespace, and has no effect. */
2704 /* We've hit an = character: the data is over. */
2707 /* We have an actual 6-bit value. Append it to the bits in n. */
2709 if ((++n_idx
) == 4) {
2710 /* We've accumulated 24 bits in n. Flush them. */
2712 *dest
++ = (n
>>8) & 0xff;
2713 *dest
++ = (n
) & 0xff;
2720 /* If we have leftover bits, we need to cope. */
2724 /* No leftover bits. We win. */
2727 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2730 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2734 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2739 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2740 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2742 return (int)(dest
-dest_orig
);
2749 /** Base64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2750 * and newline characters, and store the nul-terminated result in the first
2751 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2753 digest_to_base64(char *d64
, const char *digest
)
2756 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
2757 buf
[BASE64_DIGEST_LEN
] = '\0';
2758 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2762 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2763 * trailing newline or = characters), decode it and store the result in the
2764 * first DIGEST_LEN bytes at <b>digest</b>. */
2766 digest_from_base64(char *digest
, const char *d64
)
2768 #ifdef USE_OPENSSL_BASE64
2769 char buf_in
[BASE64_DIGEST_LEN
+3];
2771 if (strlen(d64
) != BASE64_DIGEST_LEN
)
2773 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
2774 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
2775 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
2777 memcpy(digest
, buf
, DIGEST_LEN
);
2780 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2787 /** Base64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2788 * trailing = and newline characters, and store the nul-terminated result in
2789 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2791 digest256_to_base64(char *d64
, const char *digest
)
2794 base64_encode(buf
, sizeof(buf
), digest
, DIGEST256_LEN
);
2795 buf
[BASE64_DIGEST256_LEN
] = '\0';
2796 memcpy(d64
, buf
, BASE64_DIGEST256_LEN
+1);
2800 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2801 * trailing newline or = characters), decode it and store the result in the
2802 * first DIGEST256_LEN bytes at <b>digest</b>. */
2804 digest256_from_base64(char *digest
, const char *d64
)
2806 #ifdef USE_OPENSSL_BASE64
2807 char buf_in
[BASE64_DIGEST256_LEN
+3];
2809 if (strlen(d64
) != BASE64_DIGEST256_LEN
)
2811 memcpy(buf_in
, d64
, BASE64_DIGEST256_LEN
);
2812 memcpy(buf_in
+BASE64_DIGEST256_LEN
, "=\n\0", 3);
2813 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST256_LEN
)
2815 memcpy(digest
, buf
, DIGEST256_LEN
);
2818 if (base64_decode(digest
, DIGEST256_LEN
, d64
, strlen(d64
)) == DIGEST256_LEN
)
2825 /** Implements base32 encoding as in RFC 4648. Limitation: Requires
2826 * that srclen*8 is a multiple of 5.
2829 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2831 unsigned int i
, v
, u
;
2832 size_t nbits
= srclen
* 8, bit
;
2834 tor_assert(srclen
< SIZE_T_CEILING
/8);
2835 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2836 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2837 tor_assert(destlen
< SIZE_T_CEILING
);
2839 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2840 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2841 v
= ((uint8_t)src
[bit
/8]) << 8;
2842 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2843 /* set u to the 5-bit value at the bit'th bit of src. */
2844 u
= (v
>> (11-(bit
%8))) & 0x1F;
2845 dest
[i
] = BASE32_CHARS
[u
];
2850 /** Implements base32 decoding as in RFC 4648. Limitation: Requires
2851 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2854 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2856 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2857 * it ever shows up in the profile. */
2859 size_t nbits
, j
, bit
;
2863 tor_assert(srclen
< SIZE_T_CEILING
/ 5);
2864 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2865 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2866 tor_assert(destlen
< SIZE_T_CEILING
);
2868 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2869 tmp
= tor_malloc_zero(srclen
);
2870 for (j
= 0; j
< srclen
; ++j
) {
2871 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2872 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2873 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2875 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2881 /* Assemble result byte-wise by applying five possible cases. */
2882 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2885 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2886 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2889 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2890 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2891 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2894 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2895 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2898 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2899 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2900 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2903 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2904 ((uint8_t)tmp
[(bit
/5)+1]);
2909 memwipe(tmp
, 0, srclen
);
2915 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2916 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2917 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2918 * are a salt; the 9th byte describes how much iteration to do.
2919 * Does not support <b>key_out_len</b> > DIGEST_LEN.
2922 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
2923 size_t secret_len
, const char *s2k_specifier
)
2927 size_t count
, tmplen
;
2929 tor_assert(key_out_len
< SIZE_T_CEILING
);
2932 c
= s2k_specifier
[8];
2933 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
2936 tor_assert(key_out_len
<= DIGEST_LEN
);
2938 d
= crypto_digest_new();
2939 tmplen
= 8+secret_len
;
2940 tmp
= tor_malloc(tmplen
);
2941 memcpy(tmp
,s2k_specifier
,8);
2942 memcpy(tmp
+8,secret
,secret_len
);
2945 if (count
>= secret_len
) {
2946 crypto_digest_add_bytes(d
, tmp
, secret_len
);
2947 count
-= secret_len
;
2949 crypto_digest_add_bytes(d
, tmp
, count
);
2953 crypto_digest_get_digest(d
, key_out
, key_out_len
);
2954 memwipe(tmp
, 0, tmplen
);
2956 crypto_digest_free(d
);
2960 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
2961 * the value <b>byte</b>.
2963 * This function is preferable to memset, since many compilers will happily
2964 * optimize out memset() when they can convince themselves that the data being
2965 * cleared will never be read.
2967 * Right now, our convention is to use this function when we are wiping data
2968 * that's about to become inaccessible, such as stack buffers that are about
2969 * to go out of scope or structures that are about to get freed. (In
2970 * practice, it appears that the compilers we're currently using will optimize
2971 * out the memset()s for stack-allocated buffers, but not those for
2972 * about-to-be-freed structures. That could change, though, so we're being
2973 * wary.) If there are live reads for the data, then you can just use
2977 memwipe(void *mem
, uint8_t byte
, size_t sz
)
2979 /* Because whole-program-optimization exists, we may not be able to just
2980 * have this function call "memset". A smart compiler could inline it, then
2981 * eliminate dead memsets, and declare itself to be clever. */
2983 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
2984 * based on the pointer value, then uses that junk to update a global
2985 * variable. It's an elaborate ruse to trick the compiler into not
2986 * optimizing out the "wipe this memory" code. Read it if you like zany
2987 * programming tricks! In later versions of Tor, we should look for better
2988 * not-optimized-out memory wiping stuff. */
2989 OPENSSL_cleanse(mem
, sz
);
2990 /* Just in case some caller of memwipe() is relying on getting a buffer
2991 * filled with a particular value, fill the buffer.
2993 * If this function gets inlined, this memset might get eliminated, but
2994 * that's okay: We only care about this particular memset in the case where
2995 * the caller should have been using memset(), and the memset() wouldn't get
2996 * eliminated. In other words, this is here so that we won't break anything
2997 * if somebody accidentally calls memwipe() instead of memset().
2999 memset(mem
, byte
, sz
);
3002 #ifdef TOR_IS_MULTITHREADED
3004 #ifndef OPENSSL_THREADS
3005 #error OpenSSL has been built without thread support. Tor requires an \
3006 OpenSSL library with thread support enabled.
3009 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3011 openssl_locking_cb_(int mode
, int n
, const char *file
, int line
)
3015 if (!openssl_mutexes_
)
3016 /* This is not a really good fix for the
3017 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3020 if (mode
& CRYPTO_LOCK
)
3021 tor_mutex_acquire(openssl_mutexes_
[n
]);
3023 tor_mutex_release(openssl_mutexes_
[n
]);
3026 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3028 struct CRYPTO_dynlock_value
{
3032 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3033 * documentation in OpenSSL's docs for more info. */
3034 static struct CRYPTO_dynlock_value
*
3035 openssl_dynlock_create_cb_(const char *file
, int line
)
3037 struct CRYPTO_dynlock_value
*v
;
3040 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
3041 v
->lock
= tor_mutex_new();
3045 /** OpenSSL callback function to acquire or release a lock: see
3046 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3048 openssl_dynlock_lock_cb_(int mode
, struct CRYPTO_dynlock_value
*v
,
3049 const char *file
, int line
)
3053 if (mode
& CRYPTO_LOCK
)
3054 tor_mutex_acquire(v
->lock
);
3056 tor_mutex_release(v
->lock
);
3059 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3060 * documentation in OpenSSL's docs for more info. */
3062 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value
*v
,
3063 const char *file
, int line
)
3067 tor_mutex_free(v
->lock
);
3072 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3075 setup_openssl_threading(void)
3078 int n
= CRYPTO_num_locks();
3079 n_openssl_mutexes_
= n
;
3080 openssl_mutexes_
= tor_malloc(n
*sizeof(tor_mutex_t
*));
3081 for (i
=0; i
< n
; ++i
)
3082 openssl_mutexes_
[i
] = tor_mutex_new();
3083 CRYPTO_set_locking_callback(openssl_locking_cb_
);
3084 CRYPTO_set_id_callback(tor_get_thread_id
);
3085 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_
);
3086 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_
);
3087 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_
);
3092 setup_openssl_threading(void)
3098 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3101 crypto_global_cleanup(void)
3104 ERR_remove_state(0);
3108 BN_free(dh_param_p
);
3110 BN_free(dh_param_p_tls
);
3112 BN_free(dh_param_g
);
3114 #ifndef DISABLE_ENGINES
3118 CONF_modules_unload(1);
3119 CRYPTO_cleanup_all_ex_data();
3120 #ifdef TOR_IS_MULTITHREADED
3121 if (n_openssl_mutexes_
) {
3122 int n
= n_openssl_mutexes_
;
3123 tor_mutex_t
**ms
= openssl_mutexes_
;
3125 openssl_mutexes_
= NULL
;
3126 n_openssl_mutexes_
= 0;
3128 tor_mutex_free(ms
[i
]);
3133 tor_free(crypto_openssl_version_str
);