1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char crypto_c_id
[] =
11 * \brief Wrapper functions to present a consistent interface to
12 * public-key and symmetric cryptography operations from OpenSSL.
18 #define WIN32_WINNT 0x400
19 #define _WIN32_WINNT 0x400
20 #define WIN32_LEAN_AND_MEAN
27 #include <openssl/err.h>
28 #include <openssl/rsa.h>
29 #include <openssl/pem.h>
30 #include <openssl/evp.h>
31 #include <openssl/rand.h>
32 #include <openssl/opensslv.h>
33 #include <openssl/bn.h>
34 #include <openssl/dh.h>
35 #include <openssl/rsa.h>
36 #include <openssl/dh.h>
37 #include <openssl/conf.h>
53 #ifdef HAVE_SYS_FCNTL_H
54 #include <sys/fcntl.h>
61 #include "container.h"
64 #if OPENSSL_VERSION_NUMBER < 0x00905000l
65 #error "We require openssl >= 0.9.5"
68 #if OPENSSL_VERSION_NUMBER < 0x00907000l
71 #include <openssl/engine.h>
74 /** Macro: is k a valid RSA public or private key? */
75 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
76 /** Macro: is k a valid RSA private key? */
77 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
79 #ifdef TOR_IS_MULTITHREADED
80 /** A number of prealloced mutexes for use by openssl. */
81 static tor_mutex_t
**_openssl_mutexes
= NULL
;
82 /** How many mutexes have we allocated for use by openssl? */
83 static int _n_openssl_mutexes
= 0;
86 /** A public key, or a public/private keypair. */
87 struct crypto_pk_env_t
89 int refs
; /* reference counting so we don't have to copy keys */
93 /** Key and stream information for a stream cipher. */
94 struct crypto_cipher_env_t
96 char key
[CIPHER_KEY_LEN
];
97 aes_cnt_cipher_t
*cipher
;
100 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
101 * while we're waiting for the second.*/
102 struct crypto_dh_env_t
{
106 /* Prototypes for functions only used by tortls.c */
107 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
108 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
109 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
111 static int setup_openssl_threading(void);
112 static int tor_check_dh_key(BIGNUM
*bn
);
114 /** Return the number of bytes added by padding method <b>padding</b>.
117 crypto_get_rsa_padding_overhead(int padding
)
121 case RSA_NO_PADDING
: return 0;
122 case RSA_PKCS1_OAEP_PADDING
: return 42;
123 case RSA_PKCS1_PADDING
: return 11;
124 default: tor_assert(0); return -1;
128 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
131 crypto_get_rsa_padding(int padding
)
135 case PK_NO_PADDING
: return RSA_NO_PADDING
;
136 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
137 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
138 default: tor_assert(0); return -1;
142 /** Boolean: has OpenSSL's crypto been initialized? */
143 static int _crypto_global_initialized
= 0;
145 /** Log all pending crypto errors at level <b>severity</b>. Use
146 * <b>doing</b> to describe our current activities.
149 crypto_log_errors(int severity
, const char *doing
)
152 const char *msg
, *lib
, *func
;
153 while ((err
= ERR_get_error()) != 0) {
154 msg
= (const char*)ERR_reason_error_string(err
);
155 lib
= (const char*)ERR_lib_error_string(err
);
156 func
= (const char*)ERR_func_error_string(err
);
157 if (!msg
) msg
= "(null)";
158 if (!lib
) lib
= "(null)";
159 if (!func
) func
= "(null)";
161 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
162 doing
, msg
, lib
, func
);
164 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
170 /** Log any OpenSSL engines we're using at NOTICE. */
172 log_engine(const char *fn
, ENGINE
*e
)
175 const char *name
, *id
;
176 name
= ENGINE_get_name(e
);
177 id
= ENGINE_get_id(e
);
178 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
179 name
?name
:"?", id
?id
:"?", fn
);
181 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
186 /** Initialize the crypto library. Return 0 on success, -1 on failure.
189 crypto_global_init(int useAccel
)
191 if (!_crypto_global_initialized
) {
192 ERR_load_crypto_strings();
193 OpenSSL_add_all_algorithms();
194 _crypto_global_initialized
= 1;
195 setup_openssl_threading();
196 /* XXX the below is a bug, since we can't know if we're supposed
197 * to be using hardware acceleration or not. we should arrange
198 * for this function to be called before init_keys. But make it
199 * not complain loudly, at least until we make acceleration work. */
201 log_info(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
205 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
206 ENGINE_load_builtin_engines();
207 if (!ENGINE_register_all_complete())
210 /* XXXX make sure this isn't leaking. */
211 log_engine("RSA", ENGINE_get_default_RSA());
212 log_engine("DH", ENGINE_get_default_DH());
213 log_engine("RAND", ENGINE_get_default_RAND());
214 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
215 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
216 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
223 /** Free crypto resources held by this thread. */
225 crypto_thread_cleanup(void)
230 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
233 crypto_global_cleanup(void)
240 CONF_modules_unload(1);
241 CRYPTO_cleanup_all_ex_data();
243 #ifdef TOR_IS_MULTITHREADED
244 if (_n_openssl_mutexes
) {
245 int n
= _n_openssl_mutexes
;
246 tor_mutex_t
**ms
= _openssl_mutexes
;
248 _openssl_mutexes
= NULL
;
249 _n_openssl_mutexes
= 0;
251 tor_mutex_free(ms
[i
]);
259 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
261 _crypto_new_pk_env_rsa(RSA
*rsa
)
263 crypto_pk_env_t
*env
;
265 env
= tor_malloc(sizeof(crypto_pk_env_t
));
271 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
272 * private is set, include the private-key portion of the key. */
274 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
277 EVP_PKEY
*pkey
= NULL
;
278 tor_assert(env
->key
);
280 if (!(key
= RSAPrivateKey_dup(env
->key
)))
283 if (!(key
= RSAPublicKey_dup(env
->key
)))
286 if (!(pkey
= EVP_PKEY_new()))
288 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
299 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
302 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
307 /** Allocate and return storage for a public key. The key itself will not yet
311 crypto_new_pk_env(void)
316 if (!rsa
) return NULL
;
317 return _crypto_new_pk_env_rsa(rsa
);
320 /** Release a reference to an asymmetric key; when all the references
321 * are released, free the key.
324 crypto_free_pk_env(crypto_pk_env_t
*env
)
337 /** Create a new symmetric cipher for a given key and encryption flag
338 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
341 crypto_cipher_env_t
*
342 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
345 crypto_cipher_env_t
*crypto
= NULL
;
347 if (! (crypto
= crypto_new_cipher_env())) {
348 log_warn(LD_CRYPTO
, "Unable to allocate crypto object");
352 if (crypto_cipher_set_key(crypto
, key
)) {
353 crypto_log_errors(LOG_WARN
, "setting symmetric key");
358 r
= crypto_cipher_encrypt_init_cipher(crypto
);
360 r
= crypto_cipher_decrypt_init_cipher(crypto
);
368 crypto_free_cipher_env(crypto
);
372 /** Allocate and return a new symmetric cipher.
374 crypto_cipher_env_t
*
375 crypto_new_cipher_env(void)
377 crypto_cipher_env_t
*env
;
379 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
380 env
->cipher
= aes_new_cipher();
384 /** Free a symmetric cipher.
387 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
391 tor_assert(env
->cipher
);
392 aes_free_cipher(env
->cipher
);
396 /* public key crypto */
398 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
399 * success, -1 on failure.
402 crypto_pk_generate_key(crypto_pk_env_t
*env
)
408 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
410 crypto_log_errors(LOG_WARN
, "generating RSA key");
417 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
418 * Return 0 on success, -1 on failure.
421 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
429 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
430 b
= BIO_new_mem_buf((char*)s
, -1);
435 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
440 crypto_log_errors(LOG_WARN
, "Error parsing private key");
446 /** Read a PEM-encoded private key from the file named by
447 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
450 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
456 /* Read the file into a string. */
457 contents
= read_file_to_str(keyfile
, 0, NULL
);
459 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
463 /* Try to parse it. */
464 r
= crypto_pk_read_private_key_from_string(env
, contents
);
467 return -1; /* read_private_key_from_string already warned, so we don't.*/
469 /* Make sure it's valid. */
470 if (crypto_pk_check_key(env
) <= 0)
476 /** PEM-encode the public key portion of <b>env</b> and write it to a
477 * newly allocated string. On success, set *<b>dest</b> to the new
478 * string, *<b>len</b> to the string's length, and return 0. On
479 * failure, return -1.
482 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
489 tor_assert(env
->key
);
492 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
494 /* Now you can treat b as if it were a file. Just use the
495 * PEM_*_bio_* functions instead of the non-bio variants.
497 if (!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
498 crypto_log_errors(LOG_WARN
, "writing public key to string");
502 BIO_get_mem_ptr(b
, &buf
);
503 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
506 tor_assert(buf
->length
>= 0);
507 *dest
= tor_malloc(buf
->length
+1);
508 memcpy(*dest
, buf
->data
, buf
->length
);
509 (*dest
)[buf
->length
] = 0; /* nul terminate it */
516 /** Read a PEM-encoded public key from the first <b>len</b> characters of
517 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
521 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
529 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
531 BIO_write(b
, src
, len
);
535 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
538 crypto_log_errors(LOG_WARN
, "reading public key from string");
545 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
546 * PEM-encoded. Return 0 on success, -1 on failure.
549 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
558 tor_assert(PRIVATE_KEY_OK(env
));
560 if (!(bio
= BIO_new(BIO_s_mem())))
562 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
564 crypto_log_errors(LOG_WARN
, "writing private key");
568 len
= BIO_get_mem_data(bio
, &cp
);
569 tor_assert(len
>= 0);
570 s
= tor_malloc(len
+1);
573 r
= write_str_to_file(fname
, s
, 0);
579 /** Return true iff <b>env</b> has a valid key.
582 crypto_pk_check_key(crypto_pk_env_t
*env
)
587 r
= RSA_check_key(env
->key
);
589 crypto_log_errors(LOG_WARN
,"checking RSA key");
593 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
594 * if a==b, and 1 if a\>b.
597 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
604 if (!a
->key
|| !b
->key
)
607 tor_assert(PUBLIC_KEY_OK(a
));
608 tor_assert(PUBLIC_KEY_OK(b
));
609 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
612 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
615 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
617 crypto_pk_keysize(crypto_pk_env_t
*env
)
620 tor_assert(env
->key
);
622 return (size_t) RSA_size(env
->key
);
625 /** Increase the reference count of <b>env</b>, and return it.
628 crypto_pk_dup_key(crypto_pk_env_t
*env
)
631 tor_assert(env
->key
);
637 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
638 * in <b>env</b>, using the padding method <b>padding</b>. On success,
639 * write the result to <b>to</b>, and return the number of bytes
640 * written. On failure, return -1.
643 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
644 const char *from
, size_t fromlen
, int padding
)
651 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
652 env
->key
, crypto_get_rsa_padding(padding
));
654 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
660 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
661 * in <b>env</b>, using the padding method <b>padding</b>. On success,
662 * write the result to <b>to</b>, and return the number of bytes
663 * written. On failure, return -1.
666 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
667 const char *from
, size_t fromlen
,
668 int padding
, int warnOnFailure
)
674 tor_assert(env
->key
);
676 /* Not a private key */
679 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
680 env
->key
, crypto_get_rsa_padding(padding
));
683 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
684 "performing RSA decryption");
690 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
691 * public key in <b>env</b>, using PKCS1 padding. On success, write the
692 * signed data to <b>to</b>, and return the number of bytes written.
693 * On failure, return -1.
696 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
697 const char *from
, size_t fromlen
)
703 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
704 env
->key
, RSA_PKCS1_PADDING
);
707 crypto_log_errors(LOG_WARN
, "checking RSA signature");
713 /** Check a siglen-byte long signature at <b>sig</b> against
714 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
715 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
716 * SHA1(data). Else return -1.
719 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
720 int datalen
, const char *sig
, int siglen
)
722 char digest
[DIGEST_LEN
];
723 char buf
[PK_BYTES
+1];
730 if (crypto_digest(digest
,data
,datalen
)<0) {
731 log_warn(LD_BUG
, "couldn't compute digest");
734 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
735 if (r
!= DIGEST_LEN
) {
736 log_warn(LD_CRYPTO
, "Invalid signature");
739 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
740 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
747 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
748 * <b>env</b>, using PKCS1 padding. On success, write the signature to
749 * <b>to</b>, and return the number of bytes written. On failure, return
753 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
754 const char *from
, size_t fromlen
)
761 /* Not a private key */
764 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
765 env
->key
, RSA_PKCS1_PADDING
);
767 crypto_log_errors(LOG_WARN
, "generating RSA signature");
773 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
774 * <b>from</b>; sign the data with the private key in <b>env</b>, and
775 * store it in <b>to</b>. Return the number of bytes written on
776 * success, and -1 on failure.
779 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
780 const char *from
, size_t fromlen
)
782 char digest
[DIGEST_LEN
];
783 if (crypto_digest(digest
,from
,fromlen
)<0)
785 return crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
788 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
789 * bytes of data from <b>from</b>, with padding type 'padding',
790 * storing the results on <b>to</b>.
792 * If no padding is used, the public key must be at least as large as
795 * Returns the number of bytes written on success, -1 on failure.
797 * The encrypted data consists of:
798 * - The source data, padded and encrypted with the public key, if the
799 * padded source data is no longer than the public key, and <b>force</b>
801 * - The beginning of the source data prefixed with a 16-byte symmetric key,
802 * padded and encrypted with the public key; followed by the rest of
803 * the source data encrypted in AES-CTR mode with the symmetric key.
806 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
810 int padding
, int force
)
812 int overhead
, outlen
, r
, symlen
;
814 crypto_cipher_env_t
*cipher
= NULL
;
815 char buf
[PK_BYTES
+1];
821 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
822 pkeylen
= crypto_pk_keysize(env
);
824 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
827 if (!force
&& fromlen
+overhead
<= pkeylen
) {
828 /* It all fits in a single encrypt. */
829 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
831 cipher
= crypto_new_cipher_env();
832 if (!cipher
) return -1;
833 if (crypto_cipher_generate_key(cipher
)<0)
835 /* You can't just run around RSA-encrypting any bitstream: if it's
836 * greater than the RSA key, then OpenSSL will happily encrypt, and
837 * later decrypt to the wrong value. So we set the first bit of
838 * 'cipher->key' to 0 if we aren't padding. This means that our
839 * symmetric key is really only 127 bits.
841 if (padding
== PK_NO_PADDING
)
842 cipher
->key
[0] &= 0x7f;
843 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
845 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
846 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
848 /* Length of symmetrically encrypted data. */
849 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
851 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
852 if (outlen
!=(int)pkeylen
) {
855 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
856 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
859 memset(buf
, 0, sizeof(buf
));
860 crypto_free_cipher_env(cipher
);
861 return outlen
+ symlen
;
863 memset(buf
, 0, sizeof(buf
));
864 if (cipher
) crypto_free_cipher_env(cipher
);
868 /** Invert crypto_pk_public_hybrid_encrypt. */
870 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
874 int padding
, int warnOnFailure
)
878 crypto_cipher_env_t
*cipher
= NULL
;
879 char buf
[PK_BYTES
+1];
881 pkeylen
= crypto_pk_keysize(env
);
883 if (fromlen
<= pkeylen
) {
884 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,
887 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,
890 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
891 "Error decrypting public-key data");
894 if (outlen
< CIPHER_KEY_LEN
) {
895 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
896 "No room for a symmetric key");
899 cipher
= crypto_create_init_cipher(buf
, 0);
903 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
904 outlen
-= CIPHER_KEY_LEN
;
905 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
908 memset(buf
,0,sizeof(buf
));
909 crypto_free_cipher_env(cipher
);
910 return outlen
+ (fromlen
-pkeylen
);
912 memset(buf
,0,sizeof(buf
));
913 if (cipher
) crypto_free_cipher_env(cipher
);
917 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
918 * Return -1 on error, or the number of characters used on success.
921 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
924 unsigned char *buf
, *cp
;
925 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
926 if (len
< 0 || len
> dest_len
)
928 cp
= buf
= tor_malloc(len
+1);
929 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
931 crypto_log_errors(LOG_WARN
,"encoding public key");
935 /* We don't encode directly into 'dest', because that would be illegal
936 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
938 memcpy(dest
,buf
,len
);
943 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
944 * success and NULL on failure.
947 crypto_pk_asn1_decode(const char *str
, size_t len
)
951 /* This ifdef suppresses a type warning. Take out the first case once
952 * everybody is using openssl 0.9.7 or later.
954 #if OPENSSL_VERSION_NUMBER < 0x00907000l
957 const unsigned char *cp
;
959 cp
= buf
= tor_malloc(len
);
961 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
964 crypto_log_errors(LOG_WARN
,"decoding public key");
967 return _crypto_new_pk_env_rsa(rsa
);
970 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
971 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
972 * Return 0 on success, -1 on failure.
975 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
977 unsigned char *buf
, *bufp
;
980 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
983 buf
= bufp
= tor_malloc(len
+1);
984 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
986 crypto_log_errors(LOG_WARN
,"encoding public key");
990 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
998 /** Given a private or public key <b>pk</b>, put a fingerprint of the
999 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1000 * space). Return 0 on success, -1 on failure.
1002 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1003 * of the public key, converted to hexadecimal, in upper case, with a
1004 * space after every four digits.
1006 * If <b>add_space</b> is false, omit the spaces.
1009 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1011 char digest
[DIGEST_LEN
];
1012 char hexdigest
[HEX_DIGEST_LEN
+1];
1013 if (crypto_pk_get_digest(pk
, digest
)) {
1016 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1018 if (tor_strpartition(fp_out
, FINGERPRINT_LEN
+1, hexdigest
, " ", 4)<0)
1021 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1026 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1029 crypto_pk_check_fingerprint_syntax(const char *s
)
1032 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1034 if (!TOR_ISSPACE(s
[i
])) return 0;
1036 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1039 if (s
[FINGERPRINT_LEN
]) return 0;
1043 /* symmetric crypto */
1045 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1046 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1049 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1053 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1056 /** Set the symmetric key for the cipher in <b>env</b> to the first
1057 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1058 * Return 0 on success, -1 on failure.
1061 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1069 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1074 /** Return a pointer to the key set for the cipher in <b>env</b>.
1077 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1082 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1083 * success, -1 on failure.
1086 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1090 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1094 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1095 * success, -1 on failure.
1098 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1102 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1106 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1107 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1108 * On failure, return -1.
1111 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1112 const char *from
, size_t fromlen
)
1115 tor_assert(env
->cipher
);
1117 tor_assert(fromlen
);
1120 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1124 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1125 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1126 * On failure, return -1.
1129 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1130 const char *from
, size_t fromlen
)
1136 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1142 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1143 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1144 * Return 0 on success, -1 on failure.
1147 crypto_digest(char *digest
, const char *m
, size_t len
)
1151 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1154 /** Intermediate information about the digest of a stream of data. */
1155 struct crypto_digest_env_t
{
1159 /** Allocate and return a new digest object.
1161 crypto_digest_env_t
*
1162 crypto_new_digest_env(void)
1164 crypto_digest_env_t
*r
;
1165 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1170 /** Deallocate a digest object.
1173 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1178 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1181 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1186 /* Using the SHA1_*() calls directly means we don't support doing
1187 * sha1 in hardware. But so far the delay of getting the question
1188 * to the hardware, and hearing the answer, is likely higher than
1189 * just doing it ourselves. Hashes are fast.
1191 SHA1_Update(&digest
->d
, (void*)data
, len
);
1194 /** Compute the hash of the data that has been passed to the digest
1195 * object; write the first out_len bytes of the result to <b>out</b>.
1196 * <b>out_len</b> must be \<= DIGEST_LEN.
1199 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1200 char *out
, size_t out_len
)
1202 static unsigned char r
[DIGEST_LEN
];
1206 tor_assert(out_len
<= DIGEST_LEN
);
1207 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1208 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1209 SHA1_Final(r
, &tmpctx
);
1210 memcpy(out
, r
, out_len
);
1213 /** Allocate and return a new digest object with the same state as
1216 crypto_digest_env_t
*
1217 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1219 crypto_digest_env_t
*r
;
1221 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1222 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1226 /** Replace the state of the digest object <b>into</b> with the state
1227 * of the digest object <b>from</b>.
1230 crypto_digest_assign(crypto_digest_env_t
*into
,
1231 const crypto_digest_env_t
*from
)
1235 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1240 /** Shared P parameter for our DH key exchanged. */
1241 static BIGNUM
*dh_param_p
= NULL
;
1242 /** Shared G parameter for our DH key exchanges. */
1243 static BIGNUM
*dh_param_g
= NULL
;
1245 /** Initialize dh_param_p and dh_param_g if they are not already
1252 if (dh_param_p
&& dh_param_g
)
1260 /* This is from rfc2409, section 6.2. It's a safe prime, and
1261 supposedly it equals:
1262 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1265 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1266 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1267 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1268 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1269 "49286651ECE65381FFFFFFFFFFFFFFFF");
1272 r
= BN_set_word(g
, 2);
1278 #define DH_PRIVATE_KEY_BITS 320
1280 /** Allocate and return a new DH object for a key exchange.
1285 crypto_dh_env_t
*res
= NULL
;
1290 res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1292 if (!(res
->dh
= DH_new()))
1295 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1298 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1301 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1305 crypto_log_errors(LOG_WARN
, "creating DH object");
1306 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1307 if (res
) tor_free(res
);
1311 /** Return the length of the DH key in <b>dh</b>, in bytes.
1314 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1317 return DH_size(dh
->dh
);
1320 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1321 * success, -1 on failure.
1324 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1327 if (!DH_generate_key(dh
->dh
)) {
1328 crypto_log_errors(LOG_WARN
, "generating DH key");
1331 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1332 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1333 "the-universe chances really do happen. Trying again.");
1334 /* Free and clear the keys, so openssl will actually try again. */
1335 BN_free(dh
->dh
->pub_key
);
1336 BN_free(dh
->dh
->priv_key
);
1337 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1343 /** Generate g^x as necessary, and write the g^x for the key exchange
1344 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1345 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1348 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1352 if (!dh
->dh
->pub_key
) {
1353 if (crypto_dh_generate_public(dh
)<0)
1357 tor_assert(dh
->dh
->pub_key
);
1358 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1359 tor_assert(bytes
>= 0);
1360 if (pubkey_len
< (size_t)bytes
) {
1362 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1363 (int) pubkey_len
, bytes
);
1367 memset(pubkey
, 0, pubkey_len
);
1368 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1373 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1374 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1375 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1378 tor_check_dh_key(BIGNUM
*bn
)
1388 if (BN_cmp(bn
,x
)<=0) {
1389 log_warn(LD_CRYPTO
, "DH key must be at least 2.");
1392 BN_copy(x
,dh_param_p
);
1394 if (BN_cmp(bn
,x
)>=0) {
1395 log_warn(LD_CRYPTO
, "DH key must be at most p-2.");
1403 log_warn(LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1409 #define MIN(a,b) ((a)<(b)?(a):(b))
1410 /** Given a DH key exchange object, and our peer's value of g^y (as a
1411 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1412 * <b>secret_bytes_out</b> bytes of shared key material and write them
1413 * to <b>secret_out</b>. Return the number of bytes generated on success,
1416 * (We generate key material by computing
1417 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1418 * where || is concatenation.)
1421 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1422 const char *pubkey
, size_t pubkey_len
,
1423 char *secret_out
, size_t secret_bytes_out
)
1425 char *secret_tmp
= NULL
;
1426 BIGNUM
*pubkey_bn
= NULL
;
1427 size_t secret_len
=0;
1430 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1432 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
, pubkey_len
, NULL
)))
1434 if (tor_check_dh_key(pubkey_bn
)<0) {
1435 /* Check for invalid public keys. */
1436 log_warn(LD_CRYPTO
,"Rejected invalid g^x");
1439 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
));
1440 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1442 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
1445 secret_len
= result
;
1446 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1447 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1448 * Leading zeros MUST be preserved, so that ZZ occupies as many
1449 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1451 * What are the security implications here?
1453 if (crypto_expand_key_material(secret_tmp
, secret_len
,
1454 secret_out
, secret_bytes_out
)<0)
1456 secret_len
= secret_bytes_out
;
1462 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1465 tor_free(secret_tmp
);
1472 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1473 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1474 * <b>key_out</b> by taking the first key_out_len bytes of
1475 * H(K | [00]) | H(K | [01]) | ....
1477 * Return 0 on success, -1 on failure.
1480 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
1481 char *key_out
, size_t key_out_len
)
1484 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
1485 char digest
[DIGEST_LEN
];
1487 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1488 tor_assert(key_out_len
<= DIGEST_LEN
*256);
1490 memcpy(tmp
, key_in
, key_in_len
);
1491 for (cp
= key_out
, i
=0; key_out_len
; ++i
, cp
+= DIGEST_LEN
) {
1492 tmp
[key_in_len
] = i
;
1493 if (crypto_digest(digest
, tmp
, key_in_len
+1))
1495 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
));
1496 if (key_out_len
< DIGEST_LEN
)
1498 key_out_len
-= DIGEST_LEN
;
1500 memset(tmp
, 0, key_in_len
+1);
1505 memset(tmp
, 0, key_in_len
+1);
1510 /** Free a DH key exchange object.
1513 crypto_dh_free(crypto_dh_env_t
*dh
)
1521 /* random numbers */
1523 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1524 * work for us too. */
1525 #define ADD_ENTROPY 32
1527 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1529 //#define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1530 #define USE_RAND_POLL 0
1531 /* XXX Somehow setting USE_RAND_POLL on causes stack smashes. We're
1532 * not sure where. This was the big bug with Tor 0.1.1.9-alpha. */
1534 /** Seed OpenSSL's random number generator with bytes from the
1535 * operating system. Return 0 on success, -1 on failure.
1538 crypto_seed_rng(void)
1540 char buf
[ADD_ENTROPY
];
1541 int rand_poll_status
;
1543 /* local variables */
1545 static int provider_set
= 0;
1546 static HCRYPTPROV provider
;
1548 static const char *filenames
[] = {
1549 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1556 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1557 * entropy than we do. We'll try calling that, *and* calling our own entropy
1558 * functions. If one succeeds, we'll accept the RNG as seeded. */
1559 rand_poll_status
= RAND_poll();
1560 if (rand_poll_status
== 0)
1561 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
1563 rand_poll_status
= 0;
1567 if (!provider_set
) {
1568 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1569 CRYPT_VERIFYCONTEXT
)) {
1570 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
1571 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1572 return rand_poll_status
? 0 : -1;
1577 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1578 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1579 return rand_poll_status
? 0 : -1;
1581 RAND_seed(buf
, sizeof(buf
));
1584 for (i
= 0; filenames
[i
]; ++i
) {
1585 fd
= open(filenames
[i
], O_RDONLY
, 0);
1587 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1588 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1590 if (n
!= sizeof(buf
)) {
1592 "Error reading from entropy source (read only %d bytes).", n
);
1595 RAND_seed(buf
, sizeof(buf
));
1599 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1600 return rand_poll_status
? 0 : -1;
1604 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1605 * success, -1 on failure.
1608 crypto_rand(char *to
, size_t n
)
1612 r
= RAND_bytes((unsigned char*)to
, n
);
1614 crypto_log_errors(LOG_WARN
, "generating random data");
1615 return (r
== 1) ? 0 : -1;
1618 /** Return a pseudorandom integer, chosen uniformly from the values
1619 * between 0 and max-1. */
1621 crypto_rand_int(unsigned int max
)
1624 unsigned int cutoff
;
1625 tor_assert(max
< UINT_MAX
);
1626 tor_assert(max
> 0); /* don't div by 0 */
1628 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1629 * distribution with clipping at the upper end of unsigned int's
1632 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1634 crypto_rand((char*)&val
, sizeof(val
));
1640 /** Return a pseudorandom integer, chosen uniformly from the values
1641 * between 0 and max-1. */
1643 crypto_rand_uint64(uint64_t max
)
1647 tor_assert(max
< UINT64_MAX
);
1648 tor_assert(max
> 0); /* don't div by 0 */
1650 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1651 * distribution with clipping at the upper end of unsigned int's
1654 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
1656 crypto_rand((char*)&val
, sizeof(val
));
1662 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1665 smartlist_choose(const smartlist_t
*sl
)
1668 len
= smartlist_len(sl
);
1670 return smartlist_get(sl
,crypto_rand_int(len
));
1671 return NULL
; /* no elements to choose from */
1674 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1675 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1676 * bytes. Return the number of bytes written on success; -1 if
1677 * destlen is too short, or other failure.
1680 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1685 /* 48 bytes of input -> 64 bytes of output plus newline.
1686 Plus one more byte, in case I'm wrong.
1688 if (destlen
< ((srclen
/48)+1)*66)
1690 if (destlen
> SIZE_T_CEILING
)
1693 EVP_EncodeInit(&ctx
);
1694 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1695 (unsigned char*)src
, srclen
);
1696 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1701 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1702 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1703 * bytes. Return the number of bytes written on success; -1 if
1704 * destlen is too short, or other failure.
1706 * NOTE: destlen should be a little longer than the amount of data it
1707 * will contain, since we check for sufficient space conservatively.
1708 * Here, "a little" is around 64-ish bytes.
1711 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1715 /* 64 bytes of input -> *up to* 48 bytes of output.
1716 Plus one more byte, in case I'm wrong.
1718 if (destlen
< ((srclen
/64)+1)*49)
1720 if (destlen
> SIZE_T_CEILING
)
1723 EVP_DecodeInit(&ctx
);
1724 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1725 (unsigned char*)src
, srclen
);
1726 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
1731 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
1732 * and newline characters, and store the nul-terminated result in the first
1733 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
1735 digest_to_base64(char *d64
, const char *digest
)
1738 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
1739 buf
[BASE64_DIGEST_LEN
] = '\0';
1740 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
1744 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
1745 * trailing newline or = characters), decode it and store the result in the
1746 * first DIGEST_LEN bytes at <b>digest</b>. */
1748 digest_from_base64(char *digest
, const char *d64
)
1750 char buf_in
[BASE64_DIGEST_LEN
+3];
1752 if (strlen(d64
) != BASE64_DIGEST_LEN
)
1754 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
1755 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
1756 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
1758 memcpy(digest
, buf
, DIGEST_LEN
);
1762 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1763 * that srclen*8 is a multiple of 5.
1766 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1768 unsigned int nbits
, i
, bit
, v
, u
;
1771 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
1772 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
1773 tor_assert(destlen
< SIZE_T_CEILING
);
1775 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1776 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1777 v
= ((uint8_t)src
[bit
/8]) << 8;
1778 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1779 /* set u to the 5-bit value at the bit'th bit of src. */
1780 u
= (v
>> (11-(bit
%8))) & 0x1F;
1781 dest
[i
] = BASE32_CHARS
[u
];
1786 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1787 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1788 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1789 * are a salt; the 9th byte describes how much iteration to do.
1790 * Does not support <b>key_out_len</b> > DIGEST_LEN.
1793 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
1794 size_t secret_len
, const char *s2k_specifier
)
1796 crypto_digest_env_t
*d
;
1800 tor_assert(key_out_len
< SIZE_T_CEILING
);
1803 c
= s2k_specifier
[8];
1804 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
1807 tor_assert(key_out_len
<= DIGEST_LEN
);
1809 d
= crypto_new_digest_env();
1810 tmp
= tor_malloc(8+secret_len
);
1811 memcpy(tmp
,s2k_specifier
,8);
1812 memcpy(tmp
+8,secret
,secret_len
);
1815 if (count
>= secret_len
) {
1816 crypto_digest_add_bytes(d
, tmp
, secret_len
);
1817 count
-= secret_len
;
1819 crypto_digest_add_bytes(d
, tmp
, count
);
1823 crypto_digest_get_digest(d
, key_out
, key_out_len
);
1825 crypto_free_digest_env(d
);
1828 #ifdef TOR_IS_MULTITHREADED
1829 /** Helper: openssl uses this callback to manipulate mutexes. */
1831 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
1835 if (!_openssl_mutexes
)
1836 /* This is not a really good fix for the
1837 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1840 if (mode
& CRYPTO_LOCK
)
1841 tor_mutex_acquire(_openssl_mutexes
[n
]);
1843 tor_mutex_release(_openssl_mutexes
[n
]);
1846 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
1849 setup_openssl_threading(void)
1852 int n
= CRYPTO_num_locks();
1853 _n_openssl_mutexes
= n
;
1854 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
1855 for (i
=0; i
< n
; ++i
)
1856 _openssl_mutexes
[i
] = tor_mutex_new();
1857 CRYPTO_set_locking_callback(_openssl_locking_cb
);
1858 CRYPTO_set_id_callback(tor_get_thread_id
);
1863 setup_openssl_threading(void)