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-2011, 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 0x400
20 #define _WIN32_WINNT 0x400
22 #define WIN32_LEAN_AND_MEAN
25 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
26 * use either definition. */
30 #include <openssl/err.h>
31 #include <openssl/rsa.h>
32 #include <openssl/pem.h>
33 #include <openssl/evp.h>
34 #include <openssl/engine.h>
35 #include <openssl/rand.h>
36 #include <openssl/opensslv.h>
37 #include <openssl/bn.h>
38 #include <openssl/dh.h>
39 #include <openssl/conf.h>
40 #include <openssl/hmac.h>
51 #ifdef HAVE_SYS_FCNTL_H
52 #include <sys/fcntl.h>
55 #define CRYPTO_PRIVATE
57 #include "../common/torlog.h"
59 #include "../common/util.h"
60 #include "container.h"
63 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,7)
64 #error "We require OpenSSL >= 0.9.7"
68 /* Android's OpenSSL seems to have removed all of its Engine support. */
69 #define DISABLE_ENGINES
72 /** Longest recognized */
73 #define MAX_DNS_LABEL_SIZE 63
75 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
77 /** On OpenSSL versions before 0.9.8, there is no working SHA256
78 * implementation, so we use Tom St Denis's nice speedy one, slightly adapted
79 * to our needs. These macros make it usable by us. */
80 #define SHA256_CTX sha256_state
81 #define SHA256_Init sha256_init
82 #define SHA256_Update sha256_process
83 #define LTC_ARGCHK(x) tor_assert(x)
86 #define SHA256_Final(a,b) sha256_done(b,a)
88 static unsigned char *
89 SHA256(const unsigned char *m
, size_t len
, unsigned char *d
)
93 SHA256_Update(&ctx
, m
, len
);
94 SHA256_Final(d
, &ctx
);
99 /** Macro: is k a valid RSA public or private key? */
100 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
101 /** Macro: is k a valid RSA private key? */
102 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
104 #ifdef TOR_IS_MULTITHREADED
105 /** A number of preallocated mutexes for use by OpenSSL. */
106 static tor_mutex_t
**_openssl_mutexes
= NULL
;
107 /** How many mutexes have we allocated for use by OpenSSL? */
108 static int _n_openssl_mutexes
= 0;
111 /** A public key, or a public/private key-pair. */
112 struct crypto_pk_env_t
114 int refs
; /**< reference count, so we don't have to copy keys */
115 RSA
*key
; /**< The key itself */
118 /** Key and stream information for a stream cipher. */
119 struct crypto_cipher_env_t
121 char key
[CIPHER_KEY_LEN
]; /**< The raw key. */
122 aes_cnt_cipher_t
*cipher
; /**< The key in format usable for counter-mode AES
126 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
127 * while we're waiting for the second.*/
128 struct crypto_dh_env_t
{
129 DH
*dh
; /**< The openssl DH object */
132 static int setup_openssl_threading(void);
133 static int tor_check_dh_key(int severity
, BIGNUM
*bn
);
135 /** Return the number of bytes added by padding method <b>padding</b>.
138 crypto_get_rsa_padding_overhead(int padding
)
142 case RSA_NO_PADDING
: return 0;
143 case RSA_PKCS1_OAEP_PADDING
: return 42;
144 case RSA_PKCS1_PADDING
: return 11;
145 default: tor_assert(0); return -1;
149 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
152 crypto_get_rsa_padding(int padding
)
156 case PK_NO_PADDING
: return RSA_NO_PADDING
;
157 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
158 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
159 default: tor_assert(0); return -1;
163 /** Boolean: has OpenSSL's crypto been initialized? */
164 static int _crypto_global_initialized
= 0;
166 /** Log all pending crypto errors at level <b>severity</b>. Use
167 * <b>doing</b> to describe our current activities.
170 crypto_log_errors(int severity
, const char *doing
)
173 const char *msg
, *lib
, *func
;
174 while ((err
= ERR_get_error()) != 0) {
175 msg
= (const char*)ERR_reason_error_string(err
);
176 lib
= (const char*)ERR_lib_error_string(err
);
177 func
= (const char*)ERR_func_error_string(err
);
178 if (!msg
) msg
= "(null)";
179 if (!lib
) lib
= "(null)";
180 if (!func
) func
= "(null)";
182 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
183 doing
, msg
, lib
, func
);
185 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
190 #ifndef DISABLE_ENGINES
191 /** Log any OpenSSL engines we're using at NOTICE. */
193 log_engine(const char *fn
, ENGINE
*e
)
196 const char *name
, *id
;
197 name
= ENGINE_get_name(e
);
198 id
= ENGINE_get_id(e
);
199 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
200 name
?name
:"?", id
?id
:"?", fn
);
202 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
207 #ifndef DISABLE_ENGINES
208 /** Try to load an engine in a shared library via fully qualified path.
211 try_load_engine(const char *path
, const char *engine
)
213 ENGINE
*e
= ENGINE_by_id("dynamic");
215 if (!ENGINE_ctrl_cmd_string(e
, "ID", engine
, 0) ||
216 !ENGINE_ctrl_cmd_string(e
, "DIR_LOAD", "2", 0) ||
217 !ENGINE_ctrl_cmd_string(e
, "DIR_ADD", path
, 0) ||
218 !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
227 /** Initialize the crypto library. Return 0 on success, -1 on failure.
230 crypto_global_init(int useAccel
, const char *accelName
, const char *accelDir
)
232 if (!_crypto_global_initialized
) {
233 ERR_load_crypto_strings();
234 OpenSSL_add_all_algorithms();
235 _crypto_global_initialized
= 1;
236 setup_openssl_threading();
238 #ifdef DISABLE_ENGINES
241 log_warn(LD_CRYPTO
, "No OpenSSL hardware acceleration support enabled.");
245 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
246 ENGINE_load_builtin_engines();
247 ENGINE_register_all_complete();
251 log_info(LD_CRYPTO
, "Trying to load dynamic OpenSSL engine \"%s\""
252 " via path \"%s\".", accelName
, accelDir
);
253 e
= try_load_engine(accelName
, accelDir
);
255 log_info(LD_CRYPTO
, "Initializing dynamic OpenSSL engine \"%s\""
256 " acceleration support.", accelName
);
257 e
= ENGINE_by_id(accelName
);
260 log_warn(LD_CRYPTO
, "Unable to load dynamic OpenSSL engine \"%s\".",
263 log_info(LD_CRYPTO
, "Loaded dynamic OpenSSL engine \"%s\".",
268 log_info(LD_CRYPTO
, "Loaded OpenSSL hardware acceleration engine,"
269 " setting default ciphers.");
270 ENGINE_set_default(e
, ENGINE_METHOD_ALL
);
272 log_engine("RSA", ENGINE_get_default_RSA());
273 log_engine("DH", ENGINE_get_default_DH());
274 log_engine("RAND", ENGINE_get_default_RAND());
275 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
276 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
277 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
280 log_info(LD_CRYPTO
, "NOT using OpenSSL engine support.");
283 evaluate_evp_for_aes(-1);
284 evaluate_ctr_for_aes();
286 return crypto_seed_rng(1);
291 /** Free crypto resources held by this thread. */
293 crypto_thread_cleanup(void)
298 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
300 _crypto_new_pk_env_rsa(RSA
*rsa
)
302 crypto_pk_env_t
*env
;
304 env
= tor_malloc(sizeof(crypto_pk_env_t
));
310 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
311 * crypto_pk_env_t. */
313 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
318 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
319 * private is set, include the private-key portion of the key. */
321 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
324 EVP_PKEY
*pkey
= NULL
;
325 tor_assert(env
->key
);
327 if (!(key
= RSAPrivateKey_dup(env
->key
)))
330 if (!(key
= RSAPublicKey_dup(env
->key
)))
333 if (!(pkey
= EVP_PKEY_new()))
335 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
346 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
349 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
354 /** Allocate and return storage for a public key. The key itself will not yet
358 crypto_new_pk_env(void)
364 return _crypto_new_pk_env_rsa(rsa
);
367 /** Release a reference to an asymmetric key; when all the references
368 * are released, free the key.
371 crypto_free_pk_env(crypto_pk_env_t
*env
)
378 tor_assert(env
->refs
== 0);
386 /** Create a new symmetric cipher for a given key and encryption flag
387 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
390 crypto_cipher_env_t
*
391 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
394 crypto_cipher_env_t
*crypto
= NULL
;
396 if (! (crypto
= crypto_new_cipher_env())) {
397 log_warn(LD_CRYPTO
, "Unable to allocate crypto object");
401 crypto_cipher_set_key(crypto
, key
);
404 r
= crypto_cipher_encrypt_init_cipher(crypto
);
406 r
= crypto_cipher_decrypt_init_cipher(crypto
);
414 crypto_free_cipher_env(crypto
);
418 /** Allocate and return a new symmetric cipher.
420 crypto_cipher_env_t
*
421 crypto_new_cipher_env(void)
423 crypto_cipher_env_t
*env
;
425 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
426 env
->cipher
= aes_new_cipher();
430 /** Free a symmetric cipher.
433 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
438 tor_assert(env
->cipher
);
439 aes_free_cipher(env
->cipher
);
440 memset(env
, 0, sizeof(crypto_cipher_env_t
));
444 /* public key crypto */
446 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
447 * Return 0 on success, -1 on failure.
450 crypto_pk_generate_key_with_bits(crypto_pk_env_t
*env
, int bits
)
456 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
457 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
458 env
->key
= RSA_generate_key(bits
, 65537, NULL
, NULL
);
460 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
462 BIGNUM
*e
= BN_new();
466 if (! BN_set_word(e
, 65537))
471 if (RSA_generate_key_ex(r
, bits
, e
, NULL
) == -1)
484 crypto_log_errors(LOG_WARN
, "generating RSA key");
491 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
492 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
493 * the string is nul-terminated.
495 /* Used here, and used for testing. */
497 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
498 const char *s
, ssize_t len
)
504 tor_assert(len
< INT_MAX
&& len
< SSIZE_T_CEILING
);
506 /* Create a read-only memory BIO, backed by the string 's' */
507 b
= BIO_new_mem_buf((char*)s
, (int)len
);
514 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
519 crypto_log_errors(LOG_WARN
, "Error parsing private key");
525 /** Read a PEM-encoded private key from the file named by
526 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
529 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
535 /* Read the file into a string. */
536 contents
= read_file_to_str(keyfile
, 0, NULL
);
538 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
542 /* Try to parse it. */
543 r
= crypto_pk_read_private_key_from_string(env
, contents
, -1);
544 memset(contents
, 0, strlen(contents
));
547 return -1; /* read_private_key_from_string already warned, so we don't.*/
549 /* Make sure it's valid. */
550 if (crypto_pk_check_key(env
) <= 0)
556 /** Helper function to implement crypto_pk_write_*_key_to_string. */
558 crypto_pk_write_key_to_string_impl(crypto_pk_env_t
*env
, char **dest
,
559 size_t *len
, int is_public
)
566 tor_assert(env
->key
);
569 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
573 /* Now you can treat b as if it were a file. Just use the
574 * PEM_*_bio_* functions instead of the non-bio variants.
577 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
579 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
582 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
587 BIO_get_mem_ptr(b
, &buf
);
588 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
591 *dest
= tor_malloc(buf
->length
+1);
592 memcpy(*dest
, buf
->data
, buf
->length
);
593 (*dest
)[buf
->length
] = 0; /* nul terminate it */
600 /** PEM-encode the public key portion of <b>env</b> and write it to a
601 * newly allocated string. On success, set *<b>dest</b> to the new
602 * string, *<b>len</b> to the string's length, and return 0. On
603 * failure, return -1.
606 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
609 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
612 /** PEM-encode the private key portion of <b>env</b> and write it to a
613 * newly allocated string. On success, set *<b>dest</b> to the new
614 * string, *<b>len</b> to the string's length, and return 0. On
615 * failure, return -1.
618 crypto_pk_write_private_key_to_string(crypto_pk_env_t
*env
, char **dest
,
621 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
624 /** Read a PEM-encoded public key from the first <b>len</b> characters of
625 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
629 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
636 tor_assert(len
<INT_MAX
);
638 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
642 BIO_write(b
, src
, (int)len
);
646 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
649 crypto_log_errors(LOG_WARN
, "reading public key from string");
656 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
657 * PEM-encoded. Return 0 on success, -1 on failure.
660 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
669 tor_assert(PRIVATE_KEY_OK(env
));
671 if (!(bio
= BIO_new(BIO_s_mem())))
673 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
675 crypto_log_errors(LOG_WARN
, "writing private key");
679 len
= BIO_get_mem_data(bio
, &cp
);
680 tor_assert(len
>= 0);
681 s
= tor_malloc(len
+1);
684 r
= write_str_to_file(fname
, s
, 0);
686 memset(s
, 0, strlen(s
));
691 /** Return true iff <b>env</b> has a valid key.
694 crypto_pk_check_key(crypto_pk_env_t
*env
)
699 r
= RSA_check_key(env
->key
);
701 crypto_log_errors(LOG_WARN
,"checking RSA key");
705 /** Return true iff <b>key</b> contains the private-key portion of the RSA
708 crypto_pk_key_is_private(const crypto_pk_env_t
*key
)
711 return PRIVATE_KEY_OK(key
);
714 /** Return true iff <b>env</b> contains a public key whose public exponent
718 crypto_pk_public_exponent_ok(crypto_pk_env_t
*env
)
721 tor_assert(env
->key
);
723 return BN_is_word(env
->key
->e
, 65537);
726 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
727 * if a==b, and 1 if a\>b.
730 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
737 if (!a
->key
|| !b
->key
)
740 tor_assert(PUBLIC_KEY_OK(a
));
741 tor_assert(PUBLIC_KEY_OK(b
));
742 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
745 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
748 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
750 crypto_pk_keysize(crypto_pk_env_t
*env
)
753 tor_assert(env
->key
);
755 return (size_t) RSA_size(env
->key
);
758 /** Return the size of the public key modulus of <b>env</b>, in bits. */
760 crypto_pk_num_bits(crypto_pk_env_t
*env
)
763 tor_assert(env
->key
);
764 tor_assert(env
->key
->n
);
766 return BN_num_bits(env
->key
->n
);
769 /** Increase the reference count of <b>env</b>, and return it.
772 crypto_pk_dup_key(crypto_pk_env_t
*env
)
775 tor_assert(env
->key
);
781 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
783 crypto_pk_copy_full(crypto_pk_env_t
*env
)
788 tor_assert(env
->key
);
790 if (PRIVATE_KEY_OK(env
)) {
791 new_key
= RSAPrivateKey_dup(env
->key
);
794 new_key
= RSAPublicKey_dup(env
->key
);
797 log_err(LD_CRYPTO
, "Unable to duplicate a %s key: openssl failed.",
798 privatekey
?"private":"public");
799 crypto_log_errors(LOG_ERR
,
800 privatekey
? "Duplicating a private key" :
801 "Duplicating a public key");
802 tor_fragile_assert();
806 return _crypto_new_pk_env_rsa(new_key
);
809 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
810 * in <b>env</b>, using the padding method <b>padding</b>. On success,
811 * write the result to <b>to</b>, and return the number of bytes
812 * written. On failure, return -1.
814 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
815 * at least the length of the modulus of <b>env</b>.
818 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
819 const char *from
, size_t fromlen
, int padding
)
825 tor_assert(fromlen
<INT_MAX
);
826 tor_assert(tolen
>= crypto_pk_keysize(env
));
828 r
= RSA_public_encrypt((int)fromlen
,
829 (unsigned char*)from
, (unsigned char*)to
,
830 env
->key
, crypto_get_rsa_padding(padding
));
832 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
838 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
839 * in <b>env</b>, using the padding method <b>padding</b>. On success,
840 * write the result to <b>to</b>, and return the number of bytes
841 * written. On failure, return -1.
843 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
844 * at least the length of the modulus of <b>env</b>.
847 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
849 const char *from
, size_t fromlen
,
850 int padding
, int warnOnFailure
)
856 tor_assert(env
->key
);
857 tor_assert(fromlen
<INT_MAX
);
858 tor_assert(tolen
>= crypto_pk_keysize(env
));
860 /* Not a private key */
863 r
= RSA_private_decrypt((int)fromlen
,
864 (unsigned char*)from
, (unsigned char*)to
,
865 env
->key
, crypto_get_rsa_padding(padding
));
868 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
869 "performing RSA decryption");
875 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
876 * public key in <b>env</b>, using PKCS1 padding. On success, write the
877 * signed data to <b>to</b>, and return the number of bytes written.
878 * On failure, return -1.
880 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
881 * at least the length of the modulus of <b>env</b>.
884 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
886 const char *from
, size_t fromlen
)
892 tor_assert(fromlen
< INT_MAX
);
893 tor_assert(tolen
>= crypto_pk_keysize(env
));
894 r
= RSA_public_decrypt((int)fromlen
,
895 (unsigned char*)from
, (unsigned char*)to
,
896 env
->key
, RSA_PKCS1_PADDING
);
899 crypto_log_errors(LOG_WARN
, "checking RSA signature");
905 /** Check a siglen-byte long signature at <b>sig</b> against
906 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
907 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
908 * SHA1(data). Else return -1.
911 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
912 size_t datalen
, const char *sig
, size_t siglen
)
914 char digest
[DIGEST_LEN
];
922 tor_assert(datalen
< SIZE_T_CEILING
);
923 tor_assert(siglen
< SIZE_T_CEILING
);
925 if (crypto_digest(digest
,data
,datalen
)<0) {
926 log_warn(LD_BUG
, "couldn't compute digest");
929 buflen
= crypto_pk_keysize(env
);
930 buf
= tor_malloc(buflen
);
931 r
= crypto_pk_public_checksig(env
,buf
,buflen
,sig
,siglen
);
932 if (r
!= DIGEST_LEN
) {
933 log_warn(LD_CRYPTO
, "Invalid signature");
937 if (tor_memneq(buf
, digest
, DIGEST_LEN
)) {
938 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
947 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
948 * <b>env</b>, using PKCS1 padding. On success, write the signature to
949 * <b>to</b>, and return the number of bytes written. On failure, return
952 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
953 * at least the length of the modulus of <b>env</b>.
956 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
957 const char *from
, size_t fromlen
)
963 tor_assert(fromlen
< INT_MAX
);
964 tor_assert(tolen
>= crypto_pk_keysize(env
));
966 /* Not a private key */
969 r
= RSA_private_encrypt((int)fromlen
,
970 (unsigned char*)from
, (unsigned char*)to
,
971 env
->key
, RSA_PKCS1_PADDING
);
973 crypto_log_errors(LOG_WARN
, "generating RSA signature");
979 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
980 * <b>from</b>; sign the data with the private key in <b>env</b>, and
981 * store it in <b>to</b>. Return the number of bytes written on
982 * success, and -1 on failure.
984 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
985 * at least the length of the modulus of <b>env</b>.
988 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
989 const char *from
, size_t fromlen
)
992 char digest
[DIGEST_LEN
];
993 if (crypto_digest(digest
,from
,fromlen
)<0)
995 r
= crypto_pk_private_sign(env
,to
,tolen
,digest
,DIGEST_LEN
);
996 memset(digest
, 0, sizeof(digest
));
1000 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1001 * bytes of data from <b>from</b>, with padding type 'padding',
1002 * storing the results on <b>to</b>.
1004 * If no padding is used, the public key must be at least as large as
1007 * Returns the number of bytes written on success, -1 on failure.
1009 * The encrypted data consists of:
1010 * - The source data, padded and encrypted with the public key, if the
1011 * padded source data is no longer than the public key, and <b>force</b>
1013 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1014 * padded and encrypted with the public key; followed by the rest of
1015 * the source data encrypted in AES-CTR mode with the symmetric key.
1018 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
1019 char *to
, size_t tolen
,
1022 int padding
, int force
)
1024 int overhead
, outlen
, r
;
1025 size_t pkeylen
, symlen
;
1026 crypto_cipher_env_t
*cipher
= NULL
;
1032 tor_assert(fromlen
< SIZE_T_CEILING
);
1034 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
1035 pkeylen
= crypto_pk_keysize(env
);
1037 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
1040 if (!force
&& fromlen
+overhead
<= pkeylen
) {
1041 /* It all fits in a single encrypt. */
1042 return crypto_pk_public_encrypt(env
,to
,
1044 from
,fromlen
,padding
);
1046 tor_assert(tolen
>= fromlen
+ overhead
+ CIPHER_KEY_LEN
);
1047 tor_assert(tolen
>= pkeylen
);
1049 cipher
= crypto_new_cipher_env();
1050 if (!cipher
) return -1;
1051 if (crypto_cipher_generate_key(cipher
)<0)
1053 /* You can't just run around RSA-encrypting any bitstream: if it's
1054 * greater than the RSA key, then OpenSSL will happily encrypt, and
1055 * later decrypt to the wrong value. So we set the first bit of
1056 * 'cipher->key' to 0 if we aren't padding. This means that our
1057 * symmetric key is really only 127 bits.
1059 if (padding
== PK_NO_PADDING
)
1060 cipher
->key
[0] &= 0x7f;
1061 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
1063 buf
= tor_malloc(pkeylen
+1);
1064 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
1065 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
1067 /* Length of symmetrically encrypted data. */
1068 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
1070 outlen
= crypto_pk_public_encrypt(env
,to
,tolen
,buf
,pkeylen
-overhead
,padding
);
1071 if (outlen
!=(int)pkeylen
) {
1074 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
1075 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
1078 memset(buf
, 0, pkeylen
);
1080 crypto_free_cipher_env(cipher
);
1081 tor_assert(outlen
+symlen
< INT_MAX
);
1082 return (int)(outlen
+ symlen
);
1085 memset(buf
, 0, pkeylen
);
1088 if (cipher
) crypto_free_cipher_env(cipher
);
1092 /** Invert crypto_pk_public_hybrid_encrypt. */
1094 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
1099 int padding
, int warnOnFailure
)
1103 crypto_cipher_env_t
*cipher
= NULL
;
1106 tor_assert(fromlen
< SIZE_T_CEILING
);
1107 pkeylen
= crypto_pk_keysize(env
);
1109 if (fromlen
<= pkeylen
) {
1110 return crypto_pk_private_decrypt(env
,to
,tolen
,from
,fromlen
,padding
,
1114 buf
= tor_malloc(pkeylen
);
1115 outlen
= crypto_pk_private_decrypt(env
,buf
,pkeylen
,from
,pkeylen
,padding
,
1118 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
1119 "Error decrypting public-key data");
1122 if (outlen
< CIPHER_KEY_LEN
) {
1123 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1124 "No room for a symmetric key");
1127 cipher
= crypto_create_init_cipher(buf
, 0);
1131 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1132 outlen
-= CIPHER_KEY_LEN
;
1133 tor_assert(tolen
- outlen
>= fromlen
- pkeylen
);
1134 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1137 memset(buf
,0,pkeylen
);
1139 crypto_free_cipher_env(cipher
);
1140 tor_assert(outlen
+ fromlen
< INT_MAX
);
1141 return (int)(outlen
+ (fromlen
-pkeylen
));
1143 memset(buf
,0,pkeylen
);
1145 if (cipher
) crypto_free_cipher_env(cipher
);
1149 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1150 * Return -1 on error, or the number of characters used on success.
1153 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, size_t dest_len
)
1156 unsigned char *buf
, *cp
;
1157 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1158 if (len
< 0 || (size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
)
1160 cp
= buf
= tor_malloc(len
+1);
1161 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1163 crypto_log_errors(LOG_WARN
,"encoding public key");
1167 /* We don't encode directly into 'dest', because that would be illegal
1168 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1170 memcpy(dest
,buf
,len
);
1175 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1176 * success and NULL on failure.
1179 crypto_pk_asn1_decode(const char *str
, size_t len
)
1183 const unsigned char *cp
;
1184 cp
= buf
= tor_malloc(len
);
1185 memcpy(buf
,str
,len
);
1186 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1189 crypto_log_errors(LOG_WARN
,"decoding public key");
1192 return _crypto_new_pk_env_rsa(rsa
);
1195 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1196 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1197 * Return 0 on success, -1 on failure.
1200 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1202 unsigned char *buf
, *bufp
;
1205 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1208 buf
= bufp
= tor_malloc(len
+1);
1209 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1211 crypto_log_errors(LOG_WARN
,"encoding public key");
1215 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1223 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1224 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1226 crypto_pk_get_all_digests(crypto_pk_env_t
*pk
, digests_t
*digests_out
)
1228 unsigned char *buf
, *bufp
;
1231 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1234 buf
= bufp
= tor_malloc(len
+1);
1235 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1237 crypto_log_errors(LOG_WARN
,"encoding public key");
1241 if (crypto_digest_all(digests_out
, (char*)buf
, len
) < 0) {
1249 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1250 * every four spaces. */
1252 add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1255 char *end
= out
+outlen
;
1256 tor_assert(outlen
< SIZE_T_CEILING
);
1258 while (*in
&& out
<end
) {
1260 if (++n
== 4 && *in
&& out
<end
) {
1265 tor_assert(out
<end
);
1269 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1270 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1271 * space). Return 0 on success, -1 on failure.
1273 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1274 * of the public key, converted to hexadecimal, in upper case, with a
1275 * space after every four digits.
1277 * If <b>add_space</b> is false, omit the spaces.
1280 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1282 char digest
[DIGEST_LEN
];
1283 char hexdigest
[HEX_DIGEST_LEN
+1];
1284 if (crypto_pk_get_digest(pk
, digest
)) {
1287 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1289 add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1291 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1296 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1299 crypto_pk_check_fingerprint_syntax(const char *s
)
1302 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1304 if (!TOR_ISSPACE(s
[i
])) return 0;
1306 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1309 if (s
[FINGERPRINT_LEN
]) return 0;
1313 /* symmetric crypto */
1315 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1316 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1319 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1323 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1326 /** Set the symmetric key for the cipher in <b>env</b> to the first
1327 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1330 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1335 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1338 /** Generate an initialization vector for our AES-CTR cipher; store it
1339 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1341 crypto_cipher_generate_iv(char *iv_out
)
1343 crypto_rand(iv_out
, CIPHER_IV_LEN
);
1346 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1347 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1350 crypto_cipher_set_iv(crypto_cipher_env_t
*env
, const char *iv
)
1354 aes_set_iv(env
->cipher
, iv
);
1358 /** Return a pointer to the key set for the cipher in <b>env</b>.
1361 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1366 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1367 * success, -1 on failure.
1370 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1374 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1378 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1379 * success, -1 on failure.
1382 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1386 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1390 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1391 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1392 * On failure, return -1.
1395 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1396 const char *from
, size_t fromlen
)
1399 tor_assert(env
->cipher
);
1401 tor_assert(fromlen
);
1403 tor_assert(fromlen
< SIZE_T_CEILING
);
1405 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1409 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1410 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1411 * On failure, return -1.
1414 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1415 const char *from
, size_t fromlen
)
1420 tor_assert(fromlen
< SIZE_T_CEILING
);
1422 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1426 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1427 * on success, return 0. On failure, return -1.
1430 crypto_cipher_crypt_inplace(crypto_cipher_env_t
*env
, char *buf
, size_t len
)
1432 tor_assert(len
< SIZE_T_CEILING
);
1433 aes_crypt_inplace(env
->cipher
, buf
, len
);
1437 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1438 * <b>cipher</b> to the buffer in <b>to</b> of length
1439 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1440 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1441 * number of bytes written, on failure, return -1.
1443 * This function adjusts the current position of the counter in <b>cipher</b>
1444 * to immediately after the encrypted data.
1447 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t
*cipher
,
1448 char *to
, size_t tolen
,
1449 const char *from
, size_t fromlen
)
1454 tor_assert(fromlen
< INT_MAX
);
1458 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1461 crypto_cipher_generate_iv(to
);
1462 if (crypto_cipher_set_iv(cipher
, to
)<0)
1464 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1465 return (int)(fromlen
+ CIPHER_IV_LEN
);
1468 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1469 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1470 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1471 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1472 * number of bytes written, on failure, return -1.
1474 * This function adjusts the current position of the counter in <b>cipher</b>
1475 * to immediately after the decrypted data.
1478 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t
*cipher
,
1479 char *to
, size_t tolen
,
1480 const char *from
, size_t fromlen
)
1485 tor_assert(fromlen
< INT_MAX
);
1487 if (fromlen
<= CIPHER_IV_LEN
)
1489 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1492 if (crypto_cipher_set_iv(cipher
, from
)<0)
1494 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1495 return (int)(fromlen
- CIPHER_IV_LEN
);
1500 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1501 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1502 * Return 0 on success, -1 on failure.
1505 crypto_digest(char *digest
, const char *m
, size_t len
)
1509 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1512 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1513 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1514 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1516 crypto_digest256(char *digest
, const char *m
, size_t len
,
1517 digest_algorithm_t algorithm
)
1521 tor_assert(algorithm
== DIGEST_SHA256
);
1522 return (SHA256((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1525 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1526 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1527 * success, -1 on failure. */
1529 crypto_digest_all(digests_t
*ds_out
, const char *m
, size_t len
)
1531 digest_algorithm_t i
;
1533 memset(ds_out
, 0, sizeof(*ds_out
));
1534 if (crypto_digest(ds_out
->d
[DIGEST_SHA1
], m
, len
) < 0)
1536 for (i
= DIGEST_SHA256
; i
< N_DIGEST_ALGORITHMS
; ++i
) {
1537 if (crypto_digest256(ds_out
->d
[i
], m
, len
, i
) < 0)
1543 /** Return the name of an algorithm, as used in directory documents. */
1545 crypto_digest_algorithm_get_name(digest_algorithm_t alg
)
1553 tor_fragile_assert();
1554 return "??unknown_digest??";
1558 /** Given the name of a digest algorithm, return its integer value, or -1 if
1559 * the name is not recognized. */
1561 crypto_digest_algorithm_parse_name(const char *name
)
1563 if (!strcmp(name
, "sha1"))
1565 else if (!strcmp(name
, "sha256"))
1566 return DIGEST_SHA256
;
1571 /** Intermediate information about the digest of a stream of data. */
1572 struct crypto_digest_env_t
{
1574 SHA_CTX sha1
; /**< state for SHA1 */
1575 SHA256_CTX sha2
; /**< state for SHA256 */
1576 } d
; /**< State for the digest we're using. Only one member of the
1577 * union is usable, depending on the value of <b>algorithm</b>. */
1578 digest_algorithm_t algorithm
: 8; /**< Which algorithm is in use? */
1581 /** Allocate and return a new digest object to compute SHA1 digests.
1583 crypto_digest_env_t
*
1584 crypto_new_digest_env(void)
1586 crypto_digest_env_t
*r
;
1587 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1588 SHA1_Init(&r
->d
.sha1
);
1589 r
->algorithm
= DIGEST_SHA1
;
1593 /** Allocate and return a new digest object to compute 256-bit digests
1594 * using <b>algorithm</b>. */
1595 crypto_digest_env_t
*
1596 crypto_new_digest256_env(digest_algorithm_t algorithm
)
1598 crypto_digest_env_t
*r
;
1599 tor_assert(algorithm
== DIGEST_SHA256
);
1600 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1601 SHA256_Init(&r
->d
.sha2
);
1602 r
->algorithm
= algorithm
;
1606 /** Deallocate a digest object.
1609 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1613 memset(digest
, 0, sizeof(crypto_digest_env_t
));
1617 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1620 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1625 /* Using the SHA*_*() calls directly means we don't support doing
1626 * SHA in hardware. But so far the delay of getting the question
1627 * to the hardware, and hearing the answer, is likely higher than
1628 * just doing it ourselves. Hashes are fast.
1630 switch (digest
->algorithm
) {
1632 SHA1_Update(&digest
->d
.sha1
, (void*)data
, len
);
1635 SHA256_Update(&digest
->d
.sha2
, (void*)data
, len
);
1638 tor_fragile_assert();
1643 /** Compute the hash of the data that has been passed to the digest
1644 * object; write the first out_len bytes of the result to <b>out</b>.
1645 * <b>out_len</b> must be \<= DIGEST256_LEN.
1648 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1649 char *out
, size_t out_len
)
1651 unsigned char r
[DIGEST256_LEN
];
1652 crypto_digest_env_t tmpenv
;
1655 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1656 memcpy(&tmpenv
, digest
, sizeof(crypto_digest_env_t
));
1657 switch (digest
->algorithm
) {
1659 tor_assert(out_len
<= DIGEST_LEN
);
1660 SHA1_Final(r
, &tmpenv
.d
.sha1
);
1663 tor_assert(out_len
<= DIGEST256_LEN
);
1664 SHA256_Final(r
, &tmpenv
.d
.sha2
);
1667 log_warn(LD_BUG
, "Called with unknown algorithm %d", digest
->algorithm
);
1668 /* If fragile_assert is not enabled, then we should at least not
1670 memset(r
, 0xff, sizeof(r
));
1671 tor_fragile_assert();
1674 memcpy(out
, r
, out_len
);
1675 memset(r
, 0, sizeof(r
));
1678 /** Allocate and return a new digest object with the same state as
1681 crypto_digest_env_t
*
1682 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1684 crypto_digest_env_t
*r
;
1686 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1687 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1691 /** Replace the state of the digest object <b>into</b> with the state
1692 * of the digest object <b>from</b>.
1695 crypto_digest_assign(crypto_digest_env_t
*into
,
1696 const crypto_digest_env_t
*from
)
1700 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1703 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1704 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1705 * in <b>hmac_out</b>.
1708 crypto_hmac_sha1(char *hmac_out
,
1709 const char *key
, size_t key_len
,
1710 const char *msg
, size_t msg_len
)
1712 tor_assert(key_len
< INT_MAX
);
1713 tor_assert(msg_len
< INT_MAX
);
1714 HMAC(EVP_sha1(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1715 (unsigned char*)hmac_out
, NULL
);
1718 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1719 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1720 * in <b>hmac_out</b>.
1723 crypto_hmac_sha256(char *hmac_out
,
1724 const char *key
, size_t key_len
,
1725 const char *msg
, size_t msg_len
)
1727 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(0,9,8)
1728 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1729 tor_assert(key_len
< INT_MAX
);
1730 tor_assert(msg_len
< INT_MAX
);
1731 HMAC(EVP_sha256(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1732 (unsigned char*)hmac_out
, NULL
);
1734 /* OpenSSL doesn't have an EVP implementation for SHA256. We'll need
1735 to do HMAC on our own.
1737 HMAC isn't so hard: To compute HMAC(key, msg):
1738 1. If len(key) > blocksize, key = H(key).
1739 2. If len(key) < blocksize, right-pad key up to blocksize with 0 bytes.
1740 3. let ipad = key xor 0x363636363636....36
1741 let opad = key xor 0x5c5c5c5c5c5c....5c
1742 The result is H(opad | H( ipad | msg ) )
1744 #define BLOCKSIZE 64
1745 #define DIGESTSIZE 32
1746 uint8_t k
[BLOCKSIZE
];
1747 uint8_t pad
[BLOCKSIZE
];
1748 uint8_t d
[DIGESTSIZE
];
1752 tor_assert(key_len
< INT_MAX
);
1753 tor_assert(msg_len
< INT_MAX
);
1755 if (key_len
<= BLOCKSIZE
) {
1756 memset(k
, 0, sizeof(k
));
1757 memcpy(k
, key
, key_len
); /* not time invariant in key_len */
1759 SHA256((const uint8_t *)key
, key_len
, k
);
1760 memset(k
+DIGESTSIZE
, 0, sizeof(k
)-DIGESTSIZE
);
1762 for (i
= 0; i
< BLOCKSIZE
; ++i
)
1763 pad
[i
] = k
[i
] ^ 0x36;
1765 SHA256_Update(&st
, pad
, BLOCKSIZE
);
1766 SHA256_Update(&st
, (uint8_t*)msg
, msg_len
);
1767 SHA256_Final(d
, &st
);
1769 for (i
= 0; i
< BLOCKSIZE
; ++i
)
1770 pad
[i
] = k
[i
] ^ 0x5c;
1772 SHA256_Update(&st
, pad
, BLOCKSIZE
);
1773 SHA256_Update(&st
, d
, DIGESTSIZE
);
1774 SHA256_Final((uint8_t*)hmac_out
, &st
);
1776 /* Now clear everything. */
1777 memset(k
, 0, sizeof(k
));
1778 memset(pad
, 0, sizeof(pad
));
1779 memset(d
, 0, sizeof(d
));
1780 memset(&st
, 0, sizeof(st
));
1788 /** Our DH 'g' parameter */
1789 #define DH_GENERATOR 2
1791 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1792 static BIGNUM
*dh_param_p
= NULL
;
1793 /** Shared P parameter for our TLS DH key exchanges. */
1794 static BIGNUM
*dh_param_p_tls
= NULL
;
1795 /** Shared G parameter for our DH key exchanges. */
1796 static BIGNUM
*dh_param_g
= NULL
;
1798 /** Generate and return a reasonable and safe DH parameter p. */
1800 crypto_generate_dynamic_dh_modulus(void)
1802 BIGNUM
*dynamic_dh_modulus
;
1807 dynamic_dh_modulus
= BN_new();
1808 tor_assert(dynamic_dh_modulus
);
1810 dh_parameters
= DH_generate_parameters(DH_BYTES
*8, DH_GENERATOR
, NULL
, NULL
);
1811 tor_assert(dh_parameters
);
1813 r
= DH_check(dh_parameters
, &dh_codes
);
1814 tor_assert(r
&& !dh_codes
);
1816 BN_copy(dynamic_dh_modulus
, dh_parameters
->p
);
1817 tor_assert(dynamic_dh_modulus
);
1819 DH_free(dh_parameters
);
1821 { /* log the dynamic DH modulus: */
1822 s
= BN_bn2hex(dynamic_dh_modulus
);
1824 log_info(LD_OR
, "Dynamic DH modulus generated: [%s]", s
);
1828 return dynamic_dh_modulus
;
1831 /** Store our dynamic DH modulus (and its group parameters) to
1832 <b>fname</b> for future use. */
1834 crypto_store_dynamic_dh_modulus(const char *fname
)
1838 unsigned char *dh_string_repr
= NULL
, *cp
= NULL
;
1839 char *base64_encoded_dh
= NULL
;
1840 char *file_string
= NULL
;
1842 static const char file_header
[] = "# This file contains stored Diffie-"
1843 "Hellman parameters for future use.\n# You *do not* need to edit this "
1848 if (!dh_param_p_tls
) {
1849 log_info(LD_CRYPTO
, "Tried to store a DH modulus that does not exist.");
1853 if (!(dh
= DH_new()))
1855 if (!(dh
->p
= BN_dup(dh_param_p_tls
)))
1857 if (!(dh
->g
= BN_new()))
1859 if (!BN_set_word(dh
->g
, DH_GENERATOR
))
1862 len
= i2d_DHparams(dh
, NULL
);
1864 log_warn(LD_CRYPTO
, "Error occured while DER encoding DH modulus (1).");
1868 cp
= dh_string_repr
= tor_malloc_zero(len
+1);
1869 len
= i2d_DHparams(dh
, &cp
);
1870 if ((len
< 0) || ((cp
- dh_string_repr
) != len
)) {
1871 log_warn(LD_CRYPTO
, "Error occured while DER encoding DH modulus (2).");
1875 base64_encoded_dh
= tor_malloc_zero(len
* 2); /* should be enough */
1876 new_len
= base64_encode(base64_encoded_dh
, len
* 2,
1877 (char *)dh_string_repr
, len
);
1879 log_warn(LD_CRYPTO
, "Error occured while base64-encoding DH modulus.");
1883 /* concatenate file header and the dh parameters blob */
1884 new_len
= tor_asprintf(&file_string
, "%s%s", file_header
, base64_encoded_dh
);
1887 if (write_bytes_to_new_file(fname
, file_string
, new_len
, 0) < 0) {
1888 log_info(LD_CRYPTO
, "'%s' was already occupied.", fname
);
1897 tor_free(dh_string_repr
);
1898 tor_free(base64_encoded_dh
);
1899 tor_free(file_string
);
1904 /** Return the dynamic DH modulus stored in <b>fname</b>. If there is no
1905 dynamic DH modulus stored in <b>fname</b>, return NULL. */
1907 crypto_get_stored_dynamic_dh_modulus(const char *fname
)
1910 char *contents
= NULL
;
1911 const char *contents_tmp
= NULL
;
1913 char *fname_new
= NULL
;
1914 DH
*stored_dh
= NULL
;
1915 BIGNUM
*dynamic_dh_modulus
= NULL
;
1917 unsigned char *base64_decoded_dh
= NULL
;
1918 const unsigned char *cp
= NULL
;
1922 contents
= read_file_to_str(fname
, RFTS_IGNORE_MISSING
, NULL
);
1924 log_info(LD_CRYPTO
, "Could not open file '%s'", fname
);
1925 goto done
; /*usually means that ENOENT. don't try to move file to broken.*/
1928 /* skip the file header */
1929 contents_tmp
= eat_whitespace(contents
);
1930 if (!*contents_tmp
) {
1931 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus file "
1932 "seems corrupted (eat_whitespace).");
1936 /* 'fname' contains the DH parameters stored in base64-ed DER
1937 * format. We are only interested in the DH modulus.
1938 * NOTE: We allocate more storage here than we need. Since we're already
1939 * doing that, we can also add 1 byte extra to appease Coverity's
1942 cp
= base64_decoded_dh
= tor_malloc_zero(strlen(contents_tmp
) + 1);
1943 length
= base64_decode((char *)base64_decoded_dh
, strlen(contents_tmp
),
1944 contents_tmp
, strlen(contents_tmp
));
1946 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus seems corrupted (base64).");
1950 stored_dh
= d2i_DHparams(NULL
, &cp
, length
);
1951 if ((!stored_dh
) || (cp
- base64_decoded_dh
!= length
)) {
1952 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus seems corrupted (d2i).");
1956 { /* check the cryptographic qualities of the stored dynamic DH modulus: */
1957 retval
= DH_check(stored_dh
, &dh_codes
);
1958 if (!retval
|| dh_codes
) {
1959 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus is not a safe prime.");
1963 retval
= DH_size(stored_dh
);
1964 if (retval
< DH_BYTES
) {
1965 log_warn(LD_CRYPTO
, "Stored dynamic DH modulus is smaller "
1966 "than '%d' bits.", DH_BYTES
*8);
1970 if (!BN_is_word(stored_dh
->g
, 2)) {
1971 log_warn(LD_CRYPTO
, "Stored dynamic DH parameters do not use '2' "
1972 "as the group generator.");
1977 { /* log the dynamic DH modulus: */
1978 char *s
= BN_bn2hex(stored_dh
->p
);
1980 log_info(LD_OR
, "Found stored dynamic DH modulus: [%s]", s
);
1988 { /* move broken prime to $filename.broken */
1989 fname_new
= tor_malloc(strlen(fname
) + 8);
1991 /* no can do if these functions return error */
1992 strlcpy(fname_new
, fname
, strlen(fname
) + 8);
1993 strlcat(fname_new
, ".broken", strlen(fname
) + 8);
1995 log_warn(LD_CRYPTO
, "Moving broken dynamic DH prime to '%s'.", fname_new
);
1997 if (replace_file(fname
, fname_new
))
1998 log_notice(LD_CRYPTO
, "Error while moving '%s' to '%s'.",
2001 tor_free(fname_new
);
2011 tor_free(base64_decoded_dh
);
2014 dynamic_dh_modulus
= BN_dup(stored_dh
->p
);
2018 return dynamic_dh_modulus
;
2021 /** Set the global TLS Diffie-Hellman modulus.
2022 * If <b>dynamic_dh_modulus_fname</b> is set, try to read a dynamic DH modulus
2023 * off it and use it as the DH modulus. If that's not possible,
2024 * generate a new dynamic DH modulus.
2025 * If <b>dynamic_dh_modulus_fname</b> is NULL, use the Apache mod_ssl DH
2028 crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname
)
2030 BIGNUM
*tls_prime
= NULL
;
2031 int store_dh_prime_afterwards
= 0;
2034 /* If the space is occupied, free the previous TLS DH prime */
2035 if (dh_param_p_tls
) {
2036 BN_free(dh_param_p_tls
);
2037 dh_param_p_tls
= NULL
;
2040 if (dynamic_dh_modulus_fname
) { /* use dynamic DH modulus: */
2041 log_info(LD_OR
, "Using stored dynamic DH modulus.");
2042 tls_prime
= crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname
);
2045 log_notice(LD_OR
, "Generating fresh dynamic DH modulus. "
2046 "This might take a while...");
2047 tls_prime
= crypto_generate_dynamic_dh_modulus();
2049 store_dh_prime_afterwards
++;
2051 } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
2052 tls_prime
= BN_new();
2053 tor_assert(tls_prime
);
2055 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
2056 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
2059 r
=BN_hex2bn(&tls_prime
,
2060 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
2061 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
2062 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
2063 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
2064 "B0E7393E0F24218EB3");
2068 tor_assert(tls_prime
);
2070 dh_param_p_tls
= tls_prime
;
2072 if (store_dh_prime_afterwards
)
2073 /* save the new dynamic DH modulus to disk. */
2074 if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname
)) {
2075 log_notice(LD_CRYPTO
, "Failed while storing dynamic DH modulus. "
2076 "Make sure your data directory is sane.");
2080 /** Initialize dh_param_p and dh_param_g if they are not already
2085 BIGNUM
*circuit_dh_prime
, *generator
;
2087 if (dh_param_p
&& dh_param_g
)
2090 circuit_dh_prime
= BN_new();
2091 generator
= BN_new();
2092 tor_assert(circuit_dh_prime
&& generator
);
2094 /* Set our generator for all DH parameters */
2095 r
= BN_set_word(generator
, DH_GENERATOR
);
2098 /* This is from rfc2409, section 6.2. It's a safe prime, and
2099 supposedly it equals:
2100 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
2102 r
= BN_hex2bn(&circuit_dh_prime
,
2103 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
2104 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
2105 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
2106 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
2107 "49286651ECE65381FFFFFFFFFFFFFFFF");
2110 /* Set the new values as the global DH parameters. */
2111 dh_param_p
= circuit_dh_prime
;
2112 dh_param_g
= generator
;
2114 /* Ensure that we have TLS DH parameters set up, too, even if we're
2115 going to change them soon. */
2116 if (!dh_param_p_tls
) {
2117 crypto_set_tls_dh_prime(NULL
);
2121 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
2122 * handshake. Since we exponentiate by this value, choosing a smaller one
2123 * lets our handhake go faster.
2125 #define DH_PRIVATE_KEY_BITS 320
2127 /** Allocate and return a new DH object for a key exchange.
2130 crypto_dh_new(int dh_type
)
2132 crypto_dh_env_t
*res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
2134 tor_assert(dh_type
== DH_TYPE_CIRCUIT
|| dh_type
== DH_TYPE_TLS
||
2135 dh_type
== DH_TYPE_REND
);
2140 if (!(res
->dh
= DH_new()))
2143 if (dh_type
== DH_TYPE_TLS
) {
2144 if (!(res
->dh
->p
= BN_dup(dh_param_p_tls
)))
2147 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
2151 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
2154 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
2158 crypto_log_errors(LOG_WARN
, "creating DH object");
2159 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
2164 /** Return the length of the DH key in <b>dh</b>, in bytes.
2167 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
2170 return DH_size(dh
->dh
);
2173 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2174 * success, -1 on failure.
2177 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
2180 if (!DH_generate_key(dh
->dh
)) {
2181 crypto_log_errors(LOG_WARN
, "generating DH key");
2184 if (tor_check_dh_key(LOG_WARN
, dh
->dh
->pub_key
)<0) {
2185 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
2186 "the-universe chances really do happen. Trying again.");
2187 /* Free and clear the keys, so OpenSSL will actually try again. */
2188 BN_free(dh
->dh
->pub_key
);
2189 BN_free(dh
->dh
->priv_key
);
2190 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
2196 /** Generate g^x as necessary, and write the g^x for the key exchange
2197 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2198 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2201 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
2205 if (!dh
->dh
->pub_key
) {
2206 if (crypto_dh_generate_public(dh
)<0)
2210 tor_assert(dh
->dh
->pub_key
);
2211 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
2212 tor_assert(bytes
>= 0);
2213 if (pubkey_len
< (size_t)bytes
) {
2215 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2216 (int) pubkey_len
, bytes
);
2220 memset(pubkey
, 0, pubkey_len
);
2221 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
2226 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2227 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2228 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2231 tor_check_dh_key(int severity
, BIGNUM
*bn
)
2241 if (BN_cmp(bn
,x
)<=0) {
2242 log_fn(severity
, LD_CRYPTO
, "DH key must be at least 2.");
2245 BN_copy(x
,dh_param_p
);
2247 if (BN_cmp(bn
,x
)>=0) {
2248 log_fn(severity
, LD_CRYPTO
, "DH key must be at most p-2.");
2256 log_fn(severity
, LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
2262 #define MIN(a,b) ((a)<(b)?(a):(b))
2263 /** Given a DH key exchange object, and our peer's value of g^y (as a
2264 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2265 * <b>secret_bytes_out</b> bytes of shared key material and write them
2266 * to <b>secret_out</b>. Return the number of bytes generated on success,
2269 * (We generate key material by computing
2270 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2271 * where || is concatenation.)
2274 crypto_dh_compute_secret(int severity
, crypto_dh_env_t
*dh
,
2275 const char *pubkey
, size_t pubkey_len
,
2276 char *secret_out
, size_t secret_bytes_out
)
2278 char *secret_tmp
= NULL
;
2279 BIGNUM
*pubkey_bn
= NULL
;
2280 size_t secret_len
=0, secret_tmp_len
=0;
2283 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
2284 tor_assert(pubkey_len
< INT_MAX
);
2286 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
2287 (int)pubkey_len
, NULL
)))
2289 if (tor_check_dh_key(severity
, pubkey_bn
)<0) {
2290 /* Check for invalid public keys. */
2291 log_fn(severity
, LD_CRYPTO
,"Rejected invalid g^x");
2294 secret_tmp_len
= crypto_dh_get_bytes(dh
);
2295 secret_tmp
= tor_malloc(secret_tmp_len
);
2296 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
2298 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
2301 secret_len
= result
;
2302 if (crypto_expand_key_material(secret_tmp
, secret_len
,
2303 secret_out
, secret_bytes_out
)<0)
2305 secret_len
= secret_bytes_out
;
2311 crypto_log_errors(LOG_WARN
, "completing DH handshake");
2315 memset(secret_tmp
, 0, secret_tmp_len
);
2316 tor_free(secret_tmp
);
2324 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2325 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2326 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2327 * H(K | [00]) | H(K | [01]) | ....
2329 * Return 0 on success, -1 on failure.
2332 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
2333 char *key_out
, size_t key_out_len
)
2336 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
2337 char digest
[DIGEST_LEN
];
2339 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2340 tor_assert(key_out_len
<= DIGEST_LEN
*256);
2342 memcpy(tmp
, key_in
, key_in_len
);
2343 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
2344 ++i
, cp
+= DIGEST_LEN
) {
2345 tmp
[key_in_len
] = i
;
2346 if (crypto_digest(digest
, tmp
, key_in_len
+1))
2348 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
2350 memset(tmp
, 0, key_in_len
+1);
2352 memset(digest
, 0, sizeof(digest
));
2356 memset(tmp
, 0, key_in_len
+1);
2358 memset(digest
, 0, sizeof(digest
));
2362 /** Free a DH key exchange object.
2365 crypto_dh_free(crypto_dh_env_t
*dh
)
2374 /* random numbers */
2376 /** How many bytes of entropy we add at once.
2378 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2379 * work for us too. */
2380 #define ADD_ENTROPY 32
2382 /** True iff it's safe to use RAND_poll after setup.
2384 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2385 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2386 * that fd without checking whether it fit in the fd_set. Thus, if the
2387 * system has not just been started up, it is unsafe to call */
2388 #define RAND_POLL_IS_SAFE \
2389 ((OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,7,'j') && \
2390 OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)) || \
2391 OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2393 /** Set the seed of the weak RNG to a random value. */
2398 crypto_rand((void*)&seed
, sizeof(seed
));
2399 tor_init_weak_random(seed
);
2402 /** Seed OpenSSL's random number generator with bytes from the operating
2403 * system. <b>startup</b> should be true iff we have just started Tor and
2404 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2407 crypto_seed_rng(int startup
)
2409 int rand_poll_status
= 0;
2411 /* local variables */
2413 unsigned char buf
[ADD_ENTROPY
];
2414 static int provider_set
= 0;
2415 static HCRYPTPROV provider
;
2417 char buf
[ADD_ENTROPY
];
2418 static const char *filenames
[] = {
2419 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2425 /* OpenSSL has a RAND_poll function that knows about more kinds of
2426 * entropy than we do. We'll try calling that, *and* calling our own entropy
2427 * functions. If one succeeds, we'll accept the RNG as seeded. */
2428 if (startup
|| RAND_POLL_IS_SAFE
) {
2429 rand_poll_status
= RAND_poll();
2430 if (rand_poll_status
== 0)
2431 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
2435 if (!provider_set
) {
2436 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
2437 CRYPT_VERIFYCONTEXT
)) {
2438 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
2439 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
2440 return rand_poll_status
? 0 : -1;
2445 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
2446 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
2447 return rand_poll_status
? 0 : -1;
2449 RAND_seed(buf
, sizeof(buf
));
2450 memset(buf
, 0, sizeof(buf
));
2454 for (i
= 0; filenames
[i
]; ++i
) {
2455 fd
= open(filenames
[i
], O_RDONLY
, 0);
2457 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
2458 n
= read_all(fd
, buf
, sizeof(buf
), 0);
2460 if (n
!= sizeof(buf
)) {
2462 "Error reading from entropy source (read only %lu bytes).",
2466 RAND_seed(buf
, (int)sizeof(buf
));
2467 memset(buf
, 0, sizeof(buf
));
2472 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
2473 return rand_poll_status
? 0 : -1;
2477 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2478 * success, -1 on failure.
2481 crypto_rand(char *to
, size_t n
)
2484 tor_assert(n
< INT_MAX
);
2486 r
= RAND_bytes((unsigned char*)to
, (int)n
);
2488 crypto_log_errors(LOG_WARN
, "generating random data");
2489 return (r
== 1) ? 0 : -1;
2492 /** Return a pseudorandom integer, chosen uniformly from the values
2493 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2494 * INT_MAX+1, inclusive. */
2496 crypto_rand_int(unsigned int max
)
2499 unsigned int cutoff
;
2500 tor_assert(max
<= ((unsigned int)INT_MAX
)+1);
2501 tor_assert(max
> 0); /* don't div by 0 */
2503 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2504 * distribution with clipping at the upper end of unsigned int's
2507 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
2509 crypto_rand((char*)&val
, sizeof(val
));
2515 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2516 * between 0 and <b>max</b>-1. */
2518 crypto_rand_uint64(uint64_t max
)
2522 tor_assert(max
< UINT64_MAX
);
2523 tor_assert(max
> 0); /* don't div by 0 */
2525 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2526 * distribution with clipping at the upper end of unsigned int's
2529 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
2531 crypto_rand((char*)&val
, sizeof(val
));
2537 /** Return a pseudorandom double d, chosen uniformly from the range
2541 crypto_rand_double(void)
2543 /* We just use an unsigned int here; we don't really care about getting
2544 * more than 32 bits of resolution */
2546 crypto_rand((char*)&uint
, sizeof(uint
));
2548 #define UINT_MAX_AS_DOUBLE 4294967296.0
2549 #elif SIZEOF_INT == 8
2550 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2552 #error SIZEOF_INT is neither 4 nor 8
2554 return ((double)uint
) / UINT_MAX_AS_DOUBLE
;
2557 /** Generate and return a new random hostname starting with <b>prefix</b>,
2558 * ending with <b>suffix</b>, and containing no fewer than
2559 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2560 * characters between.
2562 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2565 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
2568 char *result
, *rand_bytes
;
2569 int randlen
, rand_bytes_len
;
2570 size_t resultlen
, prefixlen
;
2572 if (max_rand_len
> MAX_DNS_LABEL_SIZE
)
2573 max_rand_len
= MAX_DNS_LABEL_SIZE
;
2574 if (min_rand_len
> max_rand_len
)
2575 min_rand_len
= max_rand_len
;
2577 randlen
= min_rand_len
+ crypto_rand_int(max_rand_len
- min_rand_len
+ 1);
2579 prefixlen
= strlen(prefix
);
2580 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
2582 rand_bytes_len
= ((randlen
*5)+7)/8;
2583 if (rand_bytes_len
% 5)
2584 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
2585 rand_bytes
= tor_malloc(rand_bytes_len
);
2586 crypto_rand(rand_bytes
, rand_bytes_len
);
2588 result
= tor_malloc(resultlen
);
2589 memcpy(result
, prefix
, prefixlen
);
2590 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
2591 rand_bytes
, rand_bytes_len
);
2592 tor_free(rand_bytes
);
2593 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
2598 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2601 smartlist_choose(const smartlist_t
*sl
)
2603 int len
= smartlist_len(sl
);
2605 return smartlist_get(sl
,crypto_rand_int(len
));
2606 return NULL
; /* no elements to choose from */
2609 /** Scramble the elements of <b>sl</b> into a random order. */
2611 smartlist_shuffle(smartlist_t
*sl
)
2614 /* From the end of the list to the front, choose at random from the
2615 positions we haven't looked at yet, and swap that position into the
2616 current position. Remember to give "no swap" the same probability as
2618 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
2619 int j
= crypto_rand_int(i
+1);
2620 smartlist_swap(sl
, i
, j
);
2624 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2625 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2626 * bytes. Return the number of bytes written on success; -1 if
2627 * destlen is too short, or other failure.
2630 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2632 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2633 * it ever shows up in the profile. */
2636 tor_assert(srclen
< INT_MAX
);
2638 /* 48 bytes of input -> 64 bytes of output plus newline.
2639 Plus one more byte, in case I'm wrong.
2641 if (destlen
< ((srclen
/48)+1)*66)
2643 if (destlen
> SIZE_T_CEILING
)
2646 EVP_EncodeInit(&ctx
);
2647 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2648 (unsigned char*)src
, (int)srclen
);
2649 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
2655 /** Special values used for the base64_decode_table */
2660 /** Internal table mapping byte values to what they represent in base64.
2661 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2662 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2664 static const uint8_t base64_decode_table
[256] = {
2665 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
2666 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2667 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
2668 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
2669 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2670 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
2671 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2672 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
2673 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2674 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2675 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2676 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2677 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2678 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2679 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2680 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2683 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2684 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2685 * bytes. Return the number of bytes written on success; -1 if
2686 * destlen is too short, or other failure.
2688 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2689 * spaces or padding.
2691 * NOTE 2: This implementation does not check for the correct number of
2692 * padding "=" characters at the end of the string, and does not check
2693 * for internal padding characters.
2696 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2698 #ifdef USE_OPENSSL_BASE64
2701 /* 64 bytes of input -> *up to* 48 bytes of output.
2702 Plus one more byte, in case I'm wrong.
2704 if (destlen
< ((srclen
/64)+1)*49)
2706 if (destlen
> SIZE_T_CEILING
)
2709 EVP_DecodeInit(&ctx
);
2710 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2711 (unsigned char*)src
, srclen
);
2712 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
2716 const char *eos
= src
+srclen
;
2719 char *dest_orig
= dest
;
2721 /* Max number of bits == srclen*6.
2722 * Number of bytes required to hold all bits == (srclen*6)/8.
2723 * Yes, we want to round down: anything that hangs over the end of a
2724 * byte is padding. */
2725 if (destlen
< (srclen
*3)/4)
2727 if (destlen
> SIZE_T_CEILING
)
2730 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2731 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2732 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2734 for ( ; src
< eos
; ++src
) {
2735 unsigned char c
= (unsigned char) *src
;
2736 uint8_t v
= base64_decode_table
[c
];
2739 /* This character isn't allowed in base64. */
2742 /* This character is whitespace, and has no effect. */
2745 /* We've hit an = character: the data is over. */
2748 /* We have an actual 6-bit value. Append it to the bits in n. */
2750 if ((++n_idx
) == 4) {
2751 /* We've accumulated 24 bits in n. Flush them. */
2753 *dest
++ = (n
>>8) & 0xff;
2754 *dest
++ = (n
) & 0xff;
2761 /* If we have leftover bits, we need to cope. */
2765 /* No leftover bits. We win. */
2768 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2771 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2775 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2780 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2781 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2783 return (int)(dest
-dest_orig
);
2790 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2791 * and newline characters, and store the nul-terminated result in the first
2792 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2794 digest_to_base64(char *d64
, const char *digest
)
2797 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
2798 buf
[BASE64_DIGEST_LEN
] = '\0';
2799 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2803 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2804 * trailing newline or = characters), decode it and store the result in the
2805 * first DIGEST_LEN bytes at <b>digest</b>. */
2807 digest_from_base64(char *digest
, const char *d64
)
2809 #ifdef USE_OPENSSL_BASE64
2810 char buf_in
[BASE64_DIGEST_LEN
+3];
2812 if (strlen(d64
) != BASE64_DIGEST_LEN
)
2814 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
2815 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
2816 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
2818 memcpy(digest
, buf
, DIGEST_LEN
);
2821 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2828 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2829 * trailing = and newline characters, and store the nul-terminated result in
2830 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2832 digest256_to_base64(char *d64
, const char *digest
)
2835 base64_encode(buf
, sizeof(buf
), digest
, DIGEST256_LEN
);
2836 buf
[BASE64_DIGEST256_LEN
] = '\0';
2837 memcpy(d64
, buf
, BASE64_DIGEST256_LEN
+1);
2841 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2842 * trailing newline or = characters), decode it and store the result in the
2843 * first DIGEST256_LEN bytes at <b>digest</b>. */
2845 digest256_from_base64(char *digest
, const char *d64
)
2847 #ifdef USE_OPENSSL_BASE64
2848 char buf_in
[BASE64_DIGEST256_LEN
+3];
2850 if (strlen(d64
) != BASE64_DIGEST256_LEN
)
2852 memcpy(buf_in
, d64
, BASE64_DIGEST256_LEN
);
2853 memcpy(buf_in
+BASE64_DIGEST256_LEN
, "=\n\0", 3);
2854 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST256_LEN
)
2856 memcpy(digest
, buf
, DIGEST256_LEN
);
2859 if (base64_decode(digest
, DIGEST256_LEN
, d64
, strlen(d64
)) == DIGEST256_LEN
)
2866 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2867 * that srclen*8 is a multiple of 5.
2870 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2872 unsigned int i
, v
, u
;
2873 size_t nbits
= srclen
* 8, bit
;
2875 tor_assert(srclen
< SIZE_T_CEILING
/8);
2876 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2877 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2878 tor_assert(destlen
< SIZE_T_CEILING
);
2880 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2881 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2882 v
= ((uint8_t)src
[bit
/8]) << 8;
2883 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2884 /* set u to the 5-bit value at the bit'th bit of src. */
2885 u
= (v
>> (11-(bit
%8))) & 0x1F;
2886 dest
[i
] = BASE32_CHARS
[u
];
2891 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2892 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2895 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2897 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2898 * it ever shows up in the profile. */
2900 size_t nbits
, j
, bit
;
2904 tor_assert(srclen
< SIZE_T_CEILING
/ 5);
2905 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2906 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2907 tor_assert(destlen
< SIZE_T_CEILING
);
2909 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2910 tmp
= tor_malloc_zero(srclen
);
2911 for (j
= 0; j
< srclen
; ++j
) {
2912 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2913 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2914 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2916 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2922 /* Assemble result byte-wise by applying five possible cases. */
2923 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2926 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2927 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2930 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2931 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2932 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2935 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2936 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2939 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2940 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2941 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2944 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2945 ((uint8_t)tmp
[(bit
/5)+1]);
2950 memset(tmp
, 0, srclen
);
2956 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2957 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2958 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2959 * are a salt; the 9th byte describes how much iteration to do.
2960 * Does not support <b>key_out_len</b> > DIGEST_LEN.
2963 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
2964 size_t secret_len
, const char *s2k_specifier
)
2966 crypto_digest_env_t
*d
;
2968 size_t count
, tmplen
;
2970 tor_assert(key_out_len
< SIZE_T_CEILING
);
2973 c
= s2k_specifier
[8];
2974 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
2977 tor_assert(key_out_len
<= DIGEST_LEN
);
2979 d
= crypto_new_digest_env();
2980 tmplen
= 8+secret_len
;
2981 tmp
= tor_malloc(tmplen
);
2982 memcpy(tmp
,s2k_specifier
,8);
2983 memcpy(tmp
+8,secret
,secret_len
);
2986 if (count
>= secret_len
) {
2987 crypto_digest_add_bytes(d
, tmp
, secret_len
);
2988 count
-= secret_len
;
2990 crypto_digest_add_bytes(d
, tmp
, count
);
2994 crypto_digest_get_digest(d
, key_out
, key_out_len
);
2995 memset(tmp
, 0, tmplen
);
2997 crypto_free_digest_env(d
);
3000 #ifdef TOR_IS_MULTITHREADED
3001 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3003 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
3007 if (!_openssl_mutexes
)
3008 /* This is not a really good fix for the
3009 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3012 if (mode
& CRYPTO_LOCK
)
3013 tor_mutex_acquire(_openssl_mutexes
[n
]);
3015 tor_mutex_release(_openssl_mutexes
[n
]);
3018 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3020 struct CRYPTO_dynlock_value
{
3024 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3025 * documentation in OpenSSL's docs for more info. */
3026 static struct CRYPTO_dynlock_value
*
3027 _openssl_dynlock_create_cb(const char *file
, int line
)
3029 struct CRYPTO_dynlock_value
*v
;
3032 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
3033 v
->lock
= tor_mutex_new();
3037 /** OpenSSL callback function to acquire or release a lock: see
3038 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3040 _openssl_dynlock_lock_cb(int mode
, struct CRYPTO_dynlock_value
*v
,
3041 const char *file
, int line
)
3045 if (mode
& CRYPTO_LOCK
)
3046 tor_mutex_acquire(v
->lock
);
3048 tor_mutex_release(v
->lock
);
3051 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3052 * documentation in OpenSSL's docs for more info. */
3054 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value
*v
,
3055 const char *file
, int line
)
3059 tor_mutex_free(v
->lock
);
3064 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3067 setup_openssl_threading(void)
3070 int n
= CRYPTO_num_locks();
3071 _n_openssl_mutexes
= n
;
3072 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
3073 for (i
=0; i
< n
; ++i
)
3074 _openssl_mutexes
[i
] = tor_mutex_new();
3075 CRYPTO_set_locking_callback(_openssl_locking_cb
);
3076 CRYPTO_set_id_callback(tor_get_thread_id
);
3077 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb
);
3078 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb
);
3079 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb
);
3084 setup_openssl_threading(void)
3090 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3093 crypto_global_cleanup(void)
3096 ERR_remove_state(0);
3100 BN_free(dh_param_p
);
3102 BN_free(dh_param_p_tls
);
3104 BN_free(dh_param_g
);
3106 #ifndef DISABLE_ENGINES
3110 CONF_modules_unload(1);
3111 CRYPTO_cleanup_all_ex_data();
3112 #ifdef TOR_IS_MULTITHREADED
3113 if (_n_openssl_mutexes
) {
3114 int n
= _n_openssl_mutexes
;
3115 tor_mutex_t
**ms
= _openssl_mutexes
;
3117 _openssl_mutexes
= NULL
;
3118 _n_openssl_mutexes
= 0;
3120 tor_mutex_free(ms
[i
]);