1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, 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 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
);
109 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
110 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
112 static int setup_openssl_threading(void);
113 static int tor_check_dh_key(BIGNUM
*bn
);
115 /** Return the number of bytes added by padding method <b>padding</b>.
118 crypto_get_rsa_padding_overhead(int padding
)
122 case RSA_NO_PADDING
: return 0;
123 case RSA_PKCS1_OAEP_PADDING
: return 42;
124 case RSA_PKCS1_PADDING
: return 11;
125 default: tor_assert(0); return -1;
129 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
132 crypto_get_rsa_padding(int padding
)
136 case PK_NO_PADDING
: return RSA_NO_PADDING
;
137 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
138 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
139 default: tor_assert(0); return -1;
143 /** Boolean: has OpenSSL's crypto been initialized? */
144 static int _crypto_global_initialized
= 0;
146 /** Log all pending crypto errors at level <b>severity</b>. Use
147 * <b>doing</b> to describe our current activities.
150 crypto_log_errors(int severity
, const char *doing
)
153 const char *msg
, *lib
, *func
;
154 while ((err
= ERR_get_error()) != 0) {
155 msg
= (const char*)ERR_reason_error_string(err
);
156 lib
= (const char*)ERR_lib_error_string(err
);
157 func
= (const char*)ERR_func_error_string(err
);
158 if (!msg
) msg
= "(null)";
159 if (!lib
) lib
= "(null)";
160 if (!func
) func
= "(null)";
162 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
163 doing
, msg
, lib
, func
);
165 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
171 /** Log any OpenSSL engines we're using at NOTICE. */
173 log_engine(const char *fn
, ENGINE
*e
)
176 const char *name
, *id
;
177 name
= ENGINE_get_name(e
);
178 id
= ENGINE_get_id(e
);
179 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
180 name
?name
:"?", id
?id
:"?", fn
);
182 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
187 /** Initialize the crypto library. Return 0 on success, -1 on failure.
190 crypto_global_init(int useAccel
)
192 if (!_crypto_global_initialized
) {
193 ERR_load_crypto_strings();
194 OpenSSL_add_all_algorithms();
195 _crypto_global_initialized
= 1;
196 setup_openssl_threading();
197 /* XXX the below is a bug, since we can't know if we're supposed
198 * to be using hardware acceleration or not. we should arrange
199 * for this function to be called before init_keys. But make it
200 * not complain loudly, at least until we make acceleration work. */
202 log_info(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
206 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
207 ENGINE_load_builtin_engines();
208 if (!ENGINE_register_all_complete())
211 /* XXXX make sure this isn't leaking. */
212 log_engine("RSA", ENGINE_get_default_RSA());
213 log_engine("DH", ENGINE_get_default_DH());
214 log_engine("RAND", ENGINE_get_default_RAND());
215 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
216 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
217 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
224 /** Free crypto resources held by this thread. */
226 crypto_thread_cleanup(void)
231 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
234 crypto_global_cleanup(void)
241 CONF_modules_unload(1);
242 CRYPTO_cleanup_all_ex_data();
244 #ifdef TOR_IS_MULTITHREADED
245 if (_n_openssl_mutexes
) {
246 int n
= _n_openssl_mutexes
;
247 tor_mutex_t
**ms
= _openssl_mutexes
;
249 _openssl_mutexes
= NULL
;
250 _n_openssl_mutexes
= 0;
252 tor_mutex_free(ms
[i
]);
260 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
262 _crypto_new_pk_env_rsa(RSA
*rsa
)
264 crypto_pk_env_t
*env
;
266 env
= tor_malloc(sizeof(crypto_pk_env_t
));
272 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
274 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
279 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
280 * private is set, include the private-key portion of the key. */
282 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
285 EVP_PKEY
*pkey
= NULL
;
286 tor_assert(env
->key
);
288 if (!(key
= RSAPrivateKey_dup(env
->key
)))
291 if (!(key
= RSAPublicKey_dup(env
->key
)))
294 if (!(pkey
= EVP_PKEY_new()))
296 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
307 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
310 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
315 /** Allocate and return storage for a public key. The key itself will not yet
319 crypto_new_pk_env(void)
324 if (!rsa
) return NULL
;
325 return _crypto_new_pk_env_rsa(rsa
);
328 /** Release a reference to an asymmetric key; when all the references
329 * are released, free the key.
332 crypto_free_pk_env(crypto_pk_env_t
*env
)
345 /** Create a new symmetric cipher for a given key and encryption flag
346 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
349 crypto_cipher_env_t
*
350 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
353 crypto_cipher_env_t
*crypto
= NULL
;
355 if (! (crypto
= crypto_new_cipher_env())) {
356 log_warn(LD_CRYPTO
, "Unable to allocate crypto object");
360 if (crypto_cipher_set_key(crypto
, key
)) {
361 crypto_log_errors(LOG_WARN
, "setting symmetric key");
366 r
= crypto_cipher_encrypt_init_cipher(crypto
);
368 r
= crypto_cipher_decrypt_init_cipher(crypto
);
376 crypto_free_cipher_env(crypto
);
380 /** Allocate and return a new symmetric cipher.
382 crypto_cipher_env_t
*
383 crypto_new_cipher_env(void)
385 crypto_cipher_env_t
*env
;
387 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
388 env
->cipher
= aes_new_cipher();
392 /** Free a symmetric cipher.
395 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
399 tor_assert(env
->cipher
);
400 aes_free_cipher(env
->cipher
);
404 /* public key crypto */
406 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
407 * success, -1 on failure.
410 crypto_pk_generate_key(crypto_pk_env_t
*env
)
416 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
418 crypto_log_errors(LOG_WARN
, "generating RSA key");
425 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
426 * Return 0 on success, -1 on failure.
429 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
437 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
438 b
= BIO_new_mem_buf((char*)s
, -1);
443 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
448 crypto_log_errors(LOG_WARN
, "Error parsing private key");
454 /** Read a PEM-encoded private key from the file named by
455 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
458 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
464 /* Read the file into a string. */
465 contents
= read_file_to_str(keyfile
, 0, NULL
);
467 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
471 /* Try to parse it. */
472 r
= crypto_pk_read_private_key_from_string(env
, contents
);
475 return -1; /* read_private_key_from_string already warned, so we don't.*/
477 /* Make sure it's valid. */
478 if (crypto_pk_check_key(env
) <= 0)
484 /** PEM-encode the public key portion of <b>env</b> and write it to a
485 * newly allocated string. On success, set *<b>dest</b> to the new
486 * string, *<b>len</b> to the string's length, and return 0. On
487 * failure, return -1.
490 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
497 tor_assert(env
->key
);
500 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
502 /* Now you can treat b as if it were a file. Just use the
503 * PEM_*_bio_* functions instead of the non-bio variants.
505 if (!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
506 crypto_log_errors(LOG_WARN
, "writing public key to string");
510 BIO_get_mem_ptr(b
, &buf
);
511 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
514 tor_assert(buf
->length
>= 0);
515 *dest
= tor_malloc(buf
->length
+1);
516 memcpy(*dest
, buf
->data
, buf
->length
);
517 (*dest
)[buf
->length
] = 0; /* nul terminate it */
524 /** Read a PEM-encoded public key from the first <b>len</b> characters of
525 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
529 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
537 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
539 BIO_write(b
, src
, len
);
543 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
546 crypto_log_errors(LOG_WARN
, "reading public key from string");
553 /* Write the private key from 'env' into the file named by 'fname',
554 * PEM-encoded. Return 0 on success, -1 on failure.
557 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
566 tor_assert(PRIVATE_KEY_OK(env
));
568 if (!(bio
= BIO_new(BIO_s_mem())))
570 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
572 crypto_log_errors(LOG_WARN
, "writing private key");
576 len
= BIO_get_mem_data(bio
, &cp
);
577 tor_assert(len
>= 0);
578 s
= tor_malloc(len
+1);
581 r
= write_str_to_file(fname
, s
, 0);
587 /** Return true iff <b>env</b> has a valid key.
590 crypto_pk_check_key(crypto_pk_env_t
*env
)
595 r
= RSA_check_key(env
->key
);
597 crypto_log_errors(LOG_WARN
,"checking RSA key");
601 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
602 * if a==b, and 1 if a\>b.
605 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
612 if (!a
->key
|| !b
->key
)
615 tor_assert(PUBLIC_KEY_OK(a
));
616 tor_assert(PUBLIC_KEY_OK(b
));
617 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
620 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
623 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
625 crypto_pk_keysize(crypto_pk_env_t
*env
)
628 tor_assert(env
->key
);
630 return (size_t) RSA_size(env
->key
);
633 /** Increase the reference count of <b>env</b>, and return it.
636 crypto_pk_dup_key(crypto_pk_env_t
*env
)
639 tor_assert(env
->key
);
645 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
646 * in <b>env</b>, using the padding method <b>padding</b>. On success,
647 * write the result to <b>to</b>, and return the number of bytes
648 * written. On failure, return -1.
651 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
652 const char *from
, size_t fromlen
, int padding
)
659 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
660 env
->key
, crypto_get_rsa_padding(padding
));
662 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
668 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
669 * in <b>env</b>, using the padding method <b>padding</b>. On success,
670 * write the result to <b>to</b>, and return the number of bytes
671 * written. On failure, return -1.
674 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
675 const char *from
, size_t fromlen
,
676 int padding
, int warnOnFailure
)
682 tor_assert(env
->key
);
684 /* Not a private key */
687 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
688 env
->key
, crypto_get_rsa_padding(padding
));
691 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
692 "performing RSA decryption");
698 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
699 * public key in <b>env</b>, using PKCS1 padding. On success, write the
700 * signed data to <b>to</b>, and return the number of bytes written.
701 * On failure, return -1.
704 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
705 const char *from
, size_t fromlen
)
711 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
712 env
->key
, RSA_PKCS1_PADDING
);
715 crypto_log_errors(LOG_WARN
, "checking RSA signature");
721 /** Check a siglen-byte long signature at <b>sig</b> against
722 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
723 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
724 * SHA1(data). Else return -1.
727 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
728 int datalen
, const char *sig
, int siglen
)
730 char digest
[DIGEST_LEN
];
731 char buf
[PK_BYTES
+1];
738 if (crypto_digest(digest
,data
,datalen
)<0) {
739 log_warn(LD_BUG
, "couldn't compute digest");
742 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
743 if (r
!= DIGEST_LEN
) {
744 log_warn(LD_CRYPTO
, "Invalid signature");
747 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
748 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
755 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
756 * <b>env</b>, using PKCS1 padding. On success, write the signature to
757 * <b>to</b>, and return the number of bytes written. On failure, return
761 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
762 const char *from
, size_t fromlen
)
769 /* Not a private key */
772 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
773 env
->key
, RSA_PKCS1_PADDING
);
775 crypto_log_errors(LOG_WARN
, "generating RSA signature");
781 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
782 * <b>from</b>; sign the data with the private key in <b>env</b>, and
783 * store it in <b>to</b>. Return the number of bytes written on
784 * success, and -1 on failure.
787 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
788 const char *from
, size_t fromlen
)
790 char digest
[DIGEST_LEN
];
791 if (crypto_digest(digest
,from
,fromlen
)<0)
793 return crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
796 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
797 * bytes of data from <b>from</b>, with padding type 'padding',
798 * storing the results on <b>to</b>.
800 * If no padding is used, the public key must be at least as large as
803 * Returns the number of bytes written on success, -1 on failure.
805 * The encrypted data consists of:
806 * - The source data, padded and encrypted with the public key, if the
807 * padded source data is no longer than the public key, and <b>force</b>
809 * - The beginning of the source data prefixed with a 16-byte symmetric key,
810 * padded and encrypted with the public key; followed by the rest of
811 * the source data encrypted in AES-CTR mode with the symmetric key.
814 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
818 int padding
, int force
)
820 int overhead
, outlen
, r
, symlen
;
822 crypto_cipher_env_t
*cipher
= NULL
;
823 char buf
[PK_BYTES
+1];
829 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
830 pkeylen
= crypto_pk_keysize(env
);
832 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
835 if (!force
&& fromlen
+overhead
<= pkeylen
) {
836 /* It all fits in a single encrypt. */
837 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
839 cipher
= crypto_new_cipher_env();
840 if (!cipher
) return -1;
841 if (crypto_cipher_generate_key(cipher
)<0)
843 /* You can't just run around RSA-encrypting any bitstream: if it's
844 * greater than the RSA key, then OpenSSL will happily encrypt, and
845 * later decrypt to the wrong value. So we set the first bit of
846 * 'cipher->key' to 0 if we aren't padding. This means that our
847 * symmetric key is really only 127 bits.
849 if (padding
== PK_NO_PADDING
)
850 cipher
->key
[0] &= 0x7f;
851 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
853 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
854 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
856 /* Length of symmetrically encrypted data. */
857 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
859 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
860 if (outlen
!=(int)pkeylen
) {
863 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
864 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
867 memset(buf
, 0, sizeof(buf
));
868 crypto_free_cipher_env(cipher
);
869 return outlen
+ symlen
;
871 memset(buf
, 0, sizeof(buf
));
872 if (cipher
) crypto_free_cipher_env(cipher
);
876 /** Invert crypto_pk_public_hybrid_encrypt. */
878 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
882 int padding
, int warnOnFailure
)
886 crypto_cipher_env_t
*cipher
= NULL
;
887 char buf
[PK_BYTES
+1];
889 pkeylen
= crypto_pk_keysize(env
);
891 if (fromlen
<= pkeylen
) {
892 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,
895 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,
898 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
899 "Error decrypting public-key data");
902 if (outlen
< CIPHER_KEY_LEN
) {
903 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
904 "No room for a symmetric key");
907 cipher
= crypto_create_init_cipher(buf
, 0);
911 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
912 outlen
-= CIPHER_KEY_LEN
;
913 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
916 memset(buf
,0,sizeof(buf
));
917 crypto_free_cipher_env(cipher
);
918 return outlen
+ (fromlen
-pkeylen
);
920 memset(buf
,0,sizeof(buf
));
921 if (cipher
) crypto_free_cipher_env(cipher
);
925 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
926 * Return -1 on error, or the number of characters used on success.
929 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
932 unsigned char *buf
, *cp
;
933 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
934 if (len
< 0 || len
> dest_len
)
936 cp
= buf
= tor_malloc(len
+1);
937 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
939 crypto_log_errors(LOG_WARN
,"encoding public key");
943 /* We don't encode directly into 'dest', because that would be illegal
944 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
946 memcpy(dest
,buf
,len
);
951 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
952 * success and NULL on failure.
955 crypto_pk_asn1_decode(const char *str
, size_t len
)
959 /* This ifdef suppresses a type warning. Take out the first case once
960 * everybody is using openssl 0.9.7 or later.
962 #if OPENSSL_VERSION_NUMBER < 0x00907000l
965 const unsigned char *cp
;
967 cp
= buf
= tor_malloc(len
);
969 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
972 crypto_log_errors(LOG_WARN
,"decoding public key");
975 return _crypto_new_pk_env_rsa(rsa
);
978 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
979 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
980 * Return 0 on success, -1 on failure.
983 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
985 unsigned char *buf
, *bufp
;
988 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
991 buf
= bufp
= tor_malloc(len
+1);
992 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
994 crypto_log_errors(LOG_WARN
,"encoding public key");
998 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1006 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1007 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1008 * space). Return 0 on success, -1 on failure.
1010 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1011 * of the public key, converted to hexadecimal, in upper case, with a
1012 * space after every four digits.
1014 * If <b>add_space</b> is false, omit the spaces.
1017 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1019 char digest
[DIGEST_LEN
];
1020 char hexdigest
[HEX_DIGEST_LEN
+1];
1021 if (crypto_pk_get_digest(pk
, digest
)) {
1024 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1026 if (tor_strpartition(fp_out
, FINGERPRINT_LEN
+1, hexdigest
, " ", 4,
1030 strcpy(fp_out
, hexdigest
);
1035 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1038 crypto_pk_check_fingerprint_syntax(const char *s
)
1041 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1043 if (!TOR_ISSPACE(s
[i
])) return 0;
1045 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1048 if (s
[FINGERPRINT_LEN
]) return 0;
1052 /* symmetric crypto */
1054 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1055 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1058 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1062 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1065 /** Set the symmetric key for the cipher in <b>env</b> to the first
1066 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1067 * Return 0 on success, -1 on failure.
1070 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1078 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1083 /** Return a pointer to the key set for the cipher in <b>env</b>.
1086 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1091 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1092 * success, -1 on failure.
1095 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1099 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1103 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1104 * success, -1 on failure.
1107 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1111 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1115 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1116 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1117 * On failure, return -1.
1120 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1121 const char *from
, size_t fromlen
)
1124 tor_assert(env
->cipher
);
1126 tor_assert(fromlen
);
1129 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1133 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1134 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1135 * On failure, return -1.
1138 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1139 const char *from
, size_t fromlen
)
1145 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1151 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1152 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1153 * Return 0 on success, -1 on failure.
1156 crypto_digest(char *digest
, const char *m
, size_t len
)
1160 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1163 /** Intermediate information about the digest of a stream of data. */
1164 struct crypto_digest_env_t
{
1168 /** Allocate and return a new digest object.
1170 crypto_digest_env_t
*
1171 crypto_new_digest_env(void)
1173 crypto_digest_env_t
*r
;
1174 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1179 /** Deallocate a digest object.
1182 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1187 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1190 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1195 /* Using the SHA1_*() calls directly means we don't support doing
1196 * sha1 in hardware. But so far the delay of getting the question
1197 * to the hardware, and hearing the answer, is likely higher than
1198 * just doing it ourselves. Hashes are fast.
1200 SHA1_Update(&digest
->d
, (void*)data
, len
);
1203 /** Compute the hash of the data that has been passed to the digest
1204 * object; write the first out_len bytes of the result to <b>out</b>.
1205 * <b>out_len</b> must be \<= DIGEST_LEN.
1208 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1209 char *out
, size_t out_len
)
1211 static unsigned char r
[DIGEST_LEN
];
1215 tor_assert(out_len
<= DIGEST_LEN
);
1216 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1217 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1218 SHA1_Final(r
, &tmpctx
);
1219 memcpy(out
, r
, out_len
);
1222 /** Allocate and return a new digest object with the same state as
1225 crypto_digest_env_t
*
1226 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1228 crypto_digest_env_t
*r
;
1230 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1231 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1235 /** Replace the state of the digest object <b>into</b> with the state
1236 * of the digest object <b>from</b>.
1239 crypto_digest_assign(crypto_digest_env_t
*into
,
1240 const crypto_digest_env_t
*from
)
1244 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1249 /** Shared P parameter for our DH key exchanged. */
1250 static BIGNUM
*dh_param_p
= NULL
;
1251 /** Shared G parameter for our DH key exchanges. */
1252 static BIGNUM
*dh_param_g
= NULL
;
1254 /** Initialize dh_param_p and dh_param_g if they are not already
1261 if (dh_param_p
&& dh_param_g
)
1269 /* This is from rfc2409, section 6.2. It's a safe prime, and
1270 supposedly it equals:
1271 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1274 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1275 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1276 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1277 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1278 "49286651ECE65381FFFFFFFFFFFFFFFF");
1281 r
= BN_set_word(g
, 2);
1287 #define DH_PRIVATE_KEY_BITS 320
1289 /** Allocate and return a new DH object for a key exchange.
1294 crypto_dh_env_t
*res
= NULL
;
1299 res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1301 if (!(res
->dh
= DH_new()))
1304 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1307 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1310 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1314 crypto_log_errors(LOG_WARN
, "creating DH object");
1315 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1316 if (res
) tor_free(res
);
1320 /** Return the length of the DH key in <b>dh</b>, in bytes.
1323 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1326 return DH_size(dh
->dh
);
1329 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1330 * success, -1 on failure.
1333 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1336 if (!DH_generate_key(dh
->dh
)) {
1337 crypto_log_errors(LOG_WARN
, "generating DH key");
1340 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1341 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1342 "the-universe chances really do happen. Trying again.");
1343 /* Free and clear the keys, so openssl will actually try again. */
1344 BN_free(dh
->dh
->pub_key
);
1345 BN_free(dh
->dh
->priv_key
);
1346 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1352 /** Generate g^x as necessary, and write the g^x for the key exchange
1353 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1354 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1357 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1361 if (!dh
->dh
->pub_key
) {
1362 if (crypto_dh_generate_public(dh
)<0)
1366 tor_assert(dh
->dh
->pub_key
);
1367 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1368 tor_assert(bytes
>= 0);
1369 if (pubkey_len
< (size_t)bytes
) {
1371 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1372 (int) pubkey_len
, bytes
);
1376 memset(pubkey
, 0, pubkey_len
);
1377 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1382 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1383 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1384 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1387 tor_check_dh_key(BIGNUM
*bn
)
1397 if (BN_cmp(bn
,x
)<=0) {
1398 log_warn(LD_CRYPTO
, "DH key must be at least 2.");
1401 BN_copy(x
,dh_param_p
);
1403 if (BN_cmp(bn
,x
)>=0) {
1404 log_warn(LD_CRYPTO
, "DH key must be at most p-2.");
1412 log_warn(LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1418 #define MIN(a,b) ((a)<(b)?(a):(b))
1419 /** Given a DH key exchange object, and our peer's value of g^y (as a
1420 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1421 * <b>secret_bytes_out</b> bytes of shared key material and write them
1422 * to <b>secret_out</b>. Return the number of bytes generated on success,
1425 * (We generate key material by computing
1426 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1427 * where || is concatenation.)
1430 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1431 const char *pubkey
, size_t pubkey_len
,
1432 char *secret_out
, size_t secret_bytes_out
)
1434 char *secret_tmp
= NULL
;
1435 BIGNUM
*pubkey_bn
= NULL
;
1436 size_t secret_len
=0;
1439 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1441 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
, pubkey_len
, NULL
)))
1443 if (tor_check_dh_key(pubkey_bn
)<0) {
1444 /* Check for invalid public keys. */
1445 log_warn(LD_CRYPTO
,"Rejected invalid g^x");
1448 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
));
1449 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1451 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
1454 secret_len
= result
;
1455 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1456 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1457 * Leading zeros MUST be preserved, so that ZZ occupies as many
1458 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1460 * What are the security implications here?
1462 if (crypto_expand_key_material(secret_tmp
, secret_len
,
1463 secret_out
, secret_bytes_out
)<0)
1465 secret_len
= secret_bytes_out
;
1471 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1474 tor_free(secret_tmp
);
1481 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1482 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1483 * <b>key_out</b> by taking the first key_out_len bytes of
1484 * H(K | [00]) | H(K | [01]) | ....
1486 * Return 0 on success, -1 on failure.
1489 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
1490 char *key_out
, size_t key_out_len
)
1493 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
1494 char digest
[DIGEST_LEN
];
1496 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1497 tor_assert(key_out_len
<= DIGEST_LEN
*256);
1499 memcpy(tmp
, key_in
, key_in_len
);
1500 for (cp
= key_out
, i
=0; key_out_len
; ++i
, cp
+= DIGEST_LEN
) {
1501 tmp
[key_in_len
] = i
;
1502 if (crypto_digest(digest
, tmp
, key_in_len
+1))
1504 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
));
1505 if (key_out_len
< DIGEST_LEN
)
1507 key_out_len
-= DIGEST_LEN
;
1509 memset(tmp
, 0, key_in_len
+1);
1514 memset(tmp
, 0, key_in_len
+1);
1519 /** Free a DH key exchange object.
1522 crypto_dh_free(crypto_dh_env_t
*dh
)
1530 /* random numbers */
1532 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1533 * work for us too. */
1534 #define ADD_ENTROPY 32
1536 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1538 //#define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1539 #define USE_RAND_POLL 0
1540 /* XXX Somehow setting USE_RAND_POLL on causes stack smashes. We're
1541 * not sure where. This was the big bug with Tor 0.1.1.9-alpha. */
1543 /** Seed OpenSSL's random number generator with bytes from the
1544 * operating system. Return 0 on success, -1 on failure.
1547 crypto_seed_rng(void)
1549 char buf
[ADD_ENTROPY
];
1550 int rand_poll_status
;
1552 /* local variables */
1554 static int provider_set
= 0;
1555 static HCRYPTPROV provider
;
1557 static const char *filenames
[] = {
1558 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1565 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1566 * entropy than we do. We'll try calling that, *and* calling our own entropy
1567 * functions. If one succeeds, we'll accept the RNG as seeded. */
1568 rand_poll_status
= RAND_poll();
1569 if (rand_poll_status
== 0)
1570 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
1572 rand_poll_status
= 0;
1576 if (!provider_set
) {
1577 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1578 CRYPT_VERIFYCONTEXT
)) {
1579 if (GetLastError() != NTE_BAD_KEYSET
) {
1580 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1581 return rand_poll_status
? 0 : -1;
1586 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1587 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1588 return rand_poll_status
? 0 : -1;
1590 RAND_seed(buf
, sizeof(buf
));
1593 for (i
= 0; filenames
[i
]; ++i
) {
1594 fd
= open(filenames
[i
], O_RDONLY
, 0);
1596 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1597 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1599 if (n
!= sizeof(buf
)) {
1601 "Error reading from entropy source (read only %d bytes).", n
);
1604 RAND_seed(buf
, sizeof(buf
));
1608 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1609 return rand_poll_status
? 0 : -1;
1613 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1614 * success, -1 on failure.
1617 crypto_rand(char *to
, size_t n
)
1621 r
= RAND_bytes((unsigned char*)to
, n
);
1623 crypto_log_errors(LOG_WARN
, "generating random data");
1624 return (r
== 1) ? 0 : -1;
1627 /** Return a pseudorandom integer, chosen uniformly from the values
1628 * between 0 and max-1. */
1630 crypto_rand_int(unsigned int max
)
1633 unsigned int cutoff
;
1634 tor_assert(max
< UINT_MAX
);
1635 tor_assert(max
> 0); /* don't div by 0 */
1637 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1638 * distribution with clipping at the upper end of unsigned int's
1641 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1643 crypto_rand((char*)&val
, sizeof(val
));
1649 /** Return a pseudorandom integer, chosen uniformly from the values
1650 * between 0 and max-1. */
1652 crypto_rand_uint64(uint64_t max
)
1656 tor_assert(max
< UINT64_MAX
);
1657 tor_assert(max
> 0); /* don't div by 0 */
1659 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1660 * distribution with clipping at the upper end of unsigned int's
1663 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
1665 crypto_rand((char*)&val
, sizeof(val
));
1671 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1674 smartlist_choose(const smartlist_t
*sl
)
1677 len
= smartlist_len(sl
);
1679 return smartlist_get(sl
,crypto_rand_int(len
));
1680 return NULL
; /* no elements to choose from */
1683 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1684 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1685 * bytes. Return the number of bytes written on success; -1 if
1686 * destlen is too short, or other failure.
1689 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1694 /* 48 bytes of input -> 64 bytes of output plus newline.
1695 Plus one more byte, in case I'm wrong.
1697 if (destlen
< ((srclen
/48)+1)*66)
1699 if (destlen
> SIZE_T_CEILING
)
1702 EVP_EncodeInit(&ctx
);
1703 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1704 (unsigned char*)src
, srclen
);
1705 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1710 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1711 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1712 * bytes. Return the number of bytes written on success; -1 if
1713 * destlen is too short, or other failure.
1715 * NOTE: destlen should be a little longer than the amount of data it
1716 * will contain, since we check for sufficient space conservatively.
1717 * Here, "a little" is around 64-ish bytes.
1720 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1724 /* 64 bytes of input -> *up to* 48 bytes of output.
1725 Plus one more byte, in case I'm wrong.
1727 if (destlen
< ((srclen
/64)+1)*49)
1729 if (destlen
> SIZE_T_CEILING
)
1732 EVP_DecodeInit(&ctx
);
1733 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1734 (unsigned char*)src
, srclen
);
1735 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
1740 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
1741 * and newline characters, and store the nul-terminated result in the first
1742 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
1744 digest_to_base64(char *d64
, const char *digest
)
1747 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
1748 buf
[BASE64_DIGEST_LEN
] = '\0';
1749 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
1753 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
1754 * trailing newline or = characters), decode it and store the result in the
1755 * first DIGEST_LEN bytes at <b>digest</b>. */
1757 digest_from_base64(char *digest
, const char *d64
)
1759 char buf_in
[BASE64_DIGEST_LEN
+3];
1761 if (strlen(d64
) != BASE64_DIGEST_LEN
)
1763 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
1764 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
1765 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
1767 memcpy(digest
, buf
, DIGEST_LEN
);
1771 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1772 * that srclen*8 is a multiple of 5.
1775 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1777 unsigned int nbits
, i
, bit
, v
, u
;
1780 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
1781 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
1782 tor_assert(destlen
< SIZE_T_CEILING
);
1784 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1785 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1786 v
= ((uint8_t)src
[bit
/8]) << 8;
1787 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1788 /* set u to the 5-bit value at the bit'th bit of src. */
1789 u
= (v
>> (11-(bit
%8))) & 0x1F;
1790 dest
[i
] = BASE32_CHARS
[u
];
1795 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1796 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1797 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1798 * are a salt; the 9th byte describes how much iteration to do.
1799 * Does not support <b>key_out_len</b> > DIGEST_LEN.
1802 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
1803 size_t secret_len
, const char *s2k_specifier
)
1805 crypto_digest_env_t
*d
;
1809 tor_assert(key_out_len
< SIZE_T_CEILING
);
1812 c
= s2k_specifier
[8];
1813 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
1816 tor_assert(key_out_len
<= DIGEST_LEN
);
1818 d
= crypto_new_digest_env();
1819 tmp
= tor_malloc(8+secret_len
);
1820 memcpy(tmp
,s2k_specifier
,8);
1821 memcpy(tmp
+8,secret
,secret_len
);
1824 if (count
>= secret_len
) {
1825 crypto_digest_add_bytes(d
, tmp
, secret_len
);
1826 count
-= secret_len
;
1828 crypto_digest_add_bytes(d
, tmp
, count
);
1832 crypto_digest_get_digest(d
, key_out
, key_out_len
);
1834 crypto_free_digest_env(d
);
1837 #ifdef TOR_IS_MULTITHREADED
1838 /** Helper: openssl uses this callback to manipulate mutexes. */
1840 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
1844 if (!_openssl_mutexes
)
1845 /* This is not a really good fix for the
1846 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1849 if (mode
& CRYPTO_LOCK
)
1850 tor_mutex_acquire(_openssl_mutexes
[n
]);
1852 tor_mutex_release(_openssl_mutexes
[n
]);
1855 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
1858 setup_openssl_threading(void)
1861 int n
= CRYPTO_num_locks();
1862 _n_openssl_mutexes
= n
;
1863 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
1864 for (i
=0; i
< n
; ++i
)
1865 _openssl_mutexes
[i
] = tor_mutex_new();
1866 CRYPTO_set_locking_callback(_openssl_locking_cb
);
1867 CRYPTO_set_id_callback(tor_get_thread_id
);
1872 setup_openssl_threading(void)