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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 const char crypto_c_id
[] =
12 * \brief Wrapper functions to present a consistent interface to
13 * public-key and symmetric cryptography operations from OpenSSL.
19 #define WIN32_WINNT 0x400
20 #define _WIN32_WINNT 0x400
21 #define WIN32_LEAN_AND_MEAN
24 /* Windows defines this; so does openssl 0.9.8h and later. We don't actually
25 * use either definition. */
29 #include <openssl/err.h>
30 #include <openssl/rsa.h>
31 #include <openssl/pem.h>
32 #include <openssl/evp.h>
33 #include <openssl/rand.h>
34 #include <openssl/opensslv.h>
35 #include <openssl/bn.h>
36 #include <openssl/dh.h>
37 #include <openssl/conf.h>
38 #include <openssl/hmac.h>
49 #ifdef HAVE_SYS_FCNTL_H
50 #include <sys/fcntl.h>
53 #define CRYPTO_PRIVATE
58 #include "container.h"
61 #if OPENSSL_VERSION_NUMBER < 0x00907000l
62 #error "We require openssl >= 0.9.7"
65 #include <openssl/engine.h>
67 /** Macro: is k a valid RSA public or private key? */
68 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
69 /** Macro: is k a valid RSA private key? */
70 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
72 #ifdef TOR_IS_MULTITHREADED
73 /** A number of prealloced mutexes for use by openssl. */
74 static tor_mutex_t
**_openssl_mutexes
= NULL
;
75 /** How many mutexes have we allocated for use by openssl? */
76 static int _n_openssl_mutexes
= 0;
79 /** A public key, or a public/private keypair. */
80 struct crypto_pk_env_t
82 int refs
; /* reference counting so we don't have to copy keys */
86 /** Key and stream information for a stream cipher. */
87 struct crypto_cipher_env_t
89 char key
[CIPHER_KEY_LEN
];
90 aes_cnt_cipher_t
*cipher
;
93 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
94 * while we're waiting for the second.*/
95 struct crypto_dh_env_t
{
99 static int setup_openssl_threading(void);
100 static int tor_check_dh_key(BIGNUM
*bn
);
102 /** Return the number of bytes added by padding method <b>padding</b>.
105 crypto_get_rsa_padding_overhead(int padding
)
109 case RSA_NO_PADDING
: return 0;
110 case RSA_PKCS1_OAEP_PADDING
: return 42;
111 case RSA_PKCS1_PADDING
: return 11;
112 default: tor_assert(0); return -1;
116 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
119 crypto_get_rsa_padding(int padding
)
123 case PK_NO_PADDING
: return RSA_NO_PADDING
;
124 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
125 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
126 default: tor_assert(0); return -1;
130 /** Boolean: has OpenSSL's crypto been initialized? */
131 static int _crypto_global_initialized
= 0;
133 /** Log all pending crypto errors at level <b>severity</b>. Use
134 * <b>doing</b> to describe our current activities.
137 crypto_log_errors(int severity
, const char *doing
)
140 const char *msg
, *lib
, *func
;
141 while ((err
= ERR_get_error()) != 0) {
142 msg
= (const char*)ERR_reason_error_string(err
);
143 lib
= (const char*)ERR_lib_error_string(err
);
144 func
= (const char*)ERR_func_error_string(err
);
145 if (!msg
) msg
= "(null)";
146 if (!lib
) lib
= "(null)";
147 if (!func
) func
= "(null)";
149 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
150 doing
, msg
, lib
, func
);
152 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
157 /** Log any OpenSSL engines we're using at NOTICE. */
159 log_engine(const char *fn
, ENGINE
*e
)
162 const char *name
, *id
;
163 name
= ENGINE_get_name(e
);
164 id
= ENGINE_get_id(e
);
165 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
166 name
?name
:"?", id
?id
:"?", fn
);
168 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
172 /** Initialize the crypto library. Return 0 on success, -1 on failure.
175 crypto_global_init(int useAccel
)
177 if (!_crypto_global_initialized
) {
178 ERR_load_crypto_strings();
179 OpenSSL_add_all_algorithms();
180 _crypto_global_initialized
= 1;
181 setup_openssl_threading();
182 /* XXX the below is a bug, since we can't know if we're supposed
183 * to be using hardware acceleration or not. we should arrange
184 * for this function to be called before init_keys. But make it
185 * not complain loudly, at least until we make acceleration work. */
187 log_info(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
190 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
191 ENGINE_load_builtin_engines();
192 if (!ENGINE_register_all_complete())
195 /* XXXX make sure this isn't leaking. */
196 log_engine("RSA", ENGINE_get_default_RSA());
197 log_engine("DH", ENGINE_get_default_DH());
198 log_engine("RAND", ENGINE_get_default_RAND());
199 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
200 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
201 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
207 /** Free crypto resources held by this thread. */
209 crypto_thread_cleanup(void)
214 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
217 crypto_global_cleanup(void)
223 CONF_modules_unload(1);
224 CRYPTO_cleanup_all_ex_data();
225 #ifdef TOR_IS_MULTITHREADED
226 if (_n_openssl_mutexes
) {
227 int n
= _n_openssl_mutexes
;
228 tor_mutex_t
**ms
= _openssl_mutexes
;
230 _openssl_mutexes
= NULL
;
231 _n_openssl_mutexes
= 0;
233 tor_mutex_free(ms
[i
]);
241 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
243 _crypto_new_pk_env_rsa(RSA
*rsa
)
245 crypto_pk_env_t
*env
;
247 env
= tor_malloc(sizeof(crypto_pk_env_t
));
253 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
254 * returns NULL if this isn't an RSA key. */
256 _crypto_new_pk_env_evp_pkey(EVP_PKEY
*pkey
)
259 if (!(rsa
= EVP_PKEY_get1_RSA(pkey
)))
261 return _crypto_new_pk_env_rsa(rsa
);
264 /** Helper, used by tor-checkkey.c. Return the RSA from a crypto_pk_env_t. */
266 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
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
);
393 memset(env
, 0, sizeof(crypto_cipher_env_t
));
397 /* public key crypto */
399 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
400 * success, -1 on failure.
403 crypto_pk_generate_key(crypto_pk_env_t
*env
)
409 #if OPENSSL_VERSION_NUMBER < 0x00908000l
410 /* In openssl 0.9.7, RSA_generate_key is all we have. */
411 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
413 /* In openssl 0.9.8, RSA_generate_key is deprecated. */
415 BIGNUM
*e
= BN_new();
419 if (! BN_set_word(e
, 65537))
424 if (RSA_generate_key_ex(r
, PK_BYTES
*8, e
, NULL
) == -1)
437 crypto_log_errors(LOG_WARN
, "generating RSA key");
444 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
445 * Return 0 on success, -1 on failure.
447 /* Used here, and used for testing. */
449 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
457 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
458 b
= BIO_new_mem_buf((char*)s
, -1);
463 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
468 crypto_log_errors(LOG_WARN
, "Error parsing private key");
474 /** Read a PEM-encoded private key from the file named by
475 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
478 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
484 /* Read the file into a string. */
485 contents
= read_file_to_str(keyfile
, 0, NULL
);
487 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
491 /* Try to parse it. */
492 r
= crypto_pk_read_private_key_from_string(env
, contents
);
495 return -1; /* read_private_key_from_string already warned, so we don't.*/
497 /* Make sure it's valid. */
498 if (crypto_pk_check_key(env
) <= 0)
504 /** Helper function to implement crypto_pk_write_*_key_to_string. */
506 crypto_pk_write_key_to_string_impl(crypto_pk_env_t
*env
, char **dest
,
507 size_t *len
, int is_public
)
514 tor_assert(env
->key
);
517 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
519 /* Now you can treat b as if it were a file. Just use the
520 * PEM_*_bio_* functions instead of the non-bio variants.
523 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
525 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
528 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
533 BIO_get_mem_ptr(b
, &buf
);
534 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
537 tor_assert(buf
->length
>= 0);
538 *dest
= tor_malloc(buf
->length
+1);
539 memcpy(*dest
, buf
->data
, buf
->length
);
540 (*dest
)[buf
->length
] = 0; /* nul terminate it */
547 /** PEM-encode the public key portion of <b>env</b> and write it to a
548 * newly allocated string. On success, set *<b>dest</b> to the new
549 * string, *<b>len</b> to the string's length, and return 0. On
550 * failure, return -1.
553 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
556 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
559 /** PEM-encode the private key portion of <b>env</b> and write it to a
560 * newly allocated string. On success, set *<b>dest</b> to the new
561 * string, *<b>len</b> to the string's length, and return 0. On
562 * failure, return -1.
565 crypto_pk_write_private_key_to_string(crypto_pk_env_t
*env
, char **dest
,
568 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
571 /** Read a PEM-encoded public key from the first <b>len</b> characters of
572 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
576 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
583 tor_assert(len
<INT_MAX
);
585 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
587 BIO_write(b
, src
, (int)len
);
591 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
594 crypto_log_errors(LOG_WARN
, "reading public key from string");
601 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
602 * PEM-encoded. Return 0 on success, -1 on failure.
605 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
614 tor_assert(PRIVATE_KEY_OK(env
));
616 if (!(bio
= BIO_new(BIO_s_mem())))
618 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
620 crypto_log_errors(LOG_WARN
, "writing private key");
624 len
= BIO_get_mem_data(bio
, &cp
);
625 tor_assert(len
>= 0);
626 s
= tor_malloc(len
+1);
629 r
= write_str_to_file(fname
, s
, 0);
635 /** Return true iff <b>env</b> has a valid key.
638 crypto_pk_check_key(crypto_pk_env_t
*env
)
643 r
= RSA_check_key(env
->key
);
645 crypto_log_errors(LOG_WARN
,"checking RSA key");
649 /** Return true iff <b>key</b> contains the private-key portion of the RSA
652 crypto_pk_key_is_private(const crypto_pk_env_t
*key
)
655 return PRIVATE_KEY_OK(key
);
658 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
659 * if a==b, and 1 if a\>b.
662 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
669 if (!a
->key
|| !b
->key
)
672 tor_assert(PUBLIC_KEY_OK(a
));
673 tor_assert(PUBLIC_KEY_OK(b
));
674 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
677 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
680 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
682 crypto_pk_keysize(crypto_pk_env_t
*env
)
685 tor_assert(env
->key
);
687 return (size_t) RSA_size(env
->key
);
690 /** Increase the reference count of <b>env</b>, and return it.
693 crypto_pk_dup_key(crypto_pk_env_t
*env
)
696 tor_assert(env
->key
);
702 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
704 crypto_pk_copy_full(crypto_pk_env_t
*env
)
708 tor_assert(env
->key
);
710 if (PRIVATE_KEY_OK(env
)) {
711 new_key
= RSAPrivateKey_dup(env
->key
);
713 new_key
= RSAPublicKey_dup(env
->key
);
716 return _crypto_new_pk_env_rsa(new_key
);
719 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
720 * in <b>env</b>, using the padding method <b>padding</b>. On success,
721 * write the result to <b>to</b>, and return the number of bytes
722 * written. On failure, return -1.
725 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
726 const char *from
, size_t fromlen
, int padding
)
732 tor_assert(fromlen
<INT_MAX
);
734 r
= RSA_public_encrypt((int)fromlen
,
735 (unsigned char*)from
, (unsigned char*)to
,
736 env
->key
, crypto_get_rsa_padding(padding
));
738 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
744 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
745 * in <b>env</b>, using the padding method <b>padding</b>. On success,
746 * write the result to <b>to</b>, and return the number of bytes
747 * written. On failure, return -1.
750 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
751 const char *from
, size_t fromlen
,
752 int padding
, int warnOnFailure
)
758 tor_assert(env
->key
);
759 tor_assert(fromlen
<INT_MAX
);
761 /* Not a private key */
764 r
= RSA_private_decrypt((int)fromlen
,
765 (unsigned char*)from
, (unsigned char*)to
,
766 env
->key
, crypto_get_rsa_padding(padding
));
769 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
770 "performing RSA decryption");
776 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
777 * public key in <b>env</b>, using PKCS1 padding. On success, write the
778 * signed data to <b>to</b>, and return the number of bytes written.
779 * On failure, return -1.
782 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
783 const char *from
, size_t fromlen
)
789 tor_assert(fromlen
< INT_MAX
);
790 r
= RSA_public_decrypt((int)fromlen
,
791 (unsigned char*)from
, (unsigned char*)to
,
792 env
->key
, RSA_PKCS1_PADDING
);
795 crypto_log_errors(LOG_WARN
, "checking RSA signature");
801 /** Check a siglen-byte long signature at <b>sig</b> against
802 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
803 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
804 * SHA1(data). Else return -1.
807 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
808 size_t datalen
, const char *sig
, size_t siglen
)
810 char digest
[DIGEST_LEN
];
818 if (crypto_digest(digest
,data
,datalen
)<0) {
819 log_warn(LD_BUG
, "couldn't compute digest");
822 buf
= tor_malloc(crypto_pk_keysize(env
)+1);
823 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
824 if (r
!= DIGEST_LEN
) {
825 log_warn(LD_CRYPTO
, "Invalid signature");
829 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
830 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
839 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
840 * <b>env</b>, using PKCS1 padding. On success, write the signature to
841 * <b>to</b>, and return the number of bytes written. On failure, return
845 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
846 const char *from
, size_t fromlen
)
852 tor_assert(fromlen
< INT_MAX
);
854 /* Not a private key */
857 r
= RSA_private_encrypt((int)fromlen
,
858 (unsigned char*)from
, (unsigned char*)to
,
859 env
->key
, RSA_PKCS1_PADDING
);
861 crypto_log_errors(LOG_WARN
, "generating RSA signature");
867 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
868 * <b>from</b>; sign the data with the private key in <b>env</b>, and
869 * store it in <b>to</b>. Return the number of bytes written on
870 * success, and -1 on failure.
873 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
874 const char *from
, size_t fromlen
)
877 char digest
[DIGEST_LEN
];
878 if (crypto_digest(digest
,from
,fromlen
)<0)
880 r
= crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
881 memset(digest
, 0, sizeof(digest
));
885 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
886 * bytes of data from <b>from</b>, with padding type 'padding',
887 * storing the results on <b>to</b>.
889 * If no padding is used, the public key must be at least as large as
892 * Returns the number of bytes written on success, -1 on failure.
894 * The encrypted data consists of:
895 * - The source data, padded and encrypted with the public key, if the
896 * padded source data is no longer than the public key, and <b>force</b>
898 * - The beginning of the source data prefixed with a 16-byte symmetric key,
899 * padded and encrypted with the public key; followed by the rest of
900 * the source data encrypted in AES-CTR mode with the symmetric key.
903 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
907 int padding
, int force
)
909 int overhead
, outlen
, r
;
910 size_t pkeylen
, symlen
;
911 crypto_cipher_env_t
*cipher
= NULL
;
918 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
919 pkeylen
= crypto_pk_keysize(env
);
921 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
924 if (!force
&& fromlen
+overhead
<= pkeylen
) {
925 /* It all fits in a single encrypt. */
926 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
928 cipher
= crypto_new_cipher_env();
929 if (!cipher
) return -1;
930 if (crypto_cipher_generate_key(cipher
)<0)
932 /* You can't just run around RSA-encrypting any bitstream: if it's
933 * greater than the RSA key, then OpenSSL will happily encrypt, and
934 * later decrypt to the wrong value. So we set the first bit of
935 * 'cipher->key' to 0 if we aren't padding. This means that our
936 * symmetric key is really only 127 bits.
938 if (padding
== PK_NO_PADDING
)
939 cipher
->key
[0] &= 0x7f;
940 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
942 buf
= tor_malloc(pkeylen
+1);
943 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
944 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
946 /* Length of symmetrically encrypted data. */
947 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
949 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
950 if (outlen
!=(int)pkeylen
) {
953 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
954 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
957 memset(buf
, 0, pkeylen
);
959 crypto_free_cipher_env(cipher
);
960 tor_assert(outlen
+symlen
< INT_MAX
);
961 return (int)(outlen
+ symlen
);
964 memset(buf
, 0, pkeylen
);
967 if (cipher
) crypto_free_cipher_env(cipher
);
971 /** Invert crypto_pk_public_hybrid_encrypt. */
973 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
977 int padding
, int warnOnFailure
)
981 crypto_cipher_env_t
*cipher
= NULL
;
984 pkeylen
= crypto_pk_keysize(env
);
986 if (fromlen
<= pkeylen
) {
987 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,
990 buf
= tor_malloc(pkeylen
+1);
991 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,
994 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
995 "Error decrypting public-key data");
998 if (outlen
< CIPHER_KEY_LEN
) {
999 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1000 "No room for a symmetric key");
1003 cipher
= crypto_create_init_cipher(buf
, 0);
1007 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1008 outlen
-= CIPHER_KEY_LEN
;
1009 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1012 memset(buf
,0,pkeylen
);
1014 crypto_free_cipher_env(cipher
);
1015 tor_assert(outlen
+ fromlen
< INT_MAX
);
1016 return (int)(outlen
+ (fromlen
-pkeylen
));
1018 memset(buf
,0,pkeylen
);
1020 if (cipher
) crypto_free_cipher_env(cipher
);
1024 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1025 * Return -1 on error, or the number of characters used on success.
1028 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, size_t dest_len
)
1031 unsigned char *buf
, *cp
;
1032 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1033 if (len
< 0 || (size_t)len
> dest_len
)
1035 cp
= buf
= tor_malloc(len
+1);
1036 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1038 crypto_log_errors(LOG_WARN
,"encoding public key");
1042 /* We don't encode directly into 'dest', because that would be illegal
1043 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1045 memcpy(dest
,buf
,len
);
1050 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1051 * success and NULL on failure.
1054 crypto_pk_asn1_decode(const char *str
, size_t len
)
1058 /* This ifdef suppresses a type warning. Take out the first case once
1059 * everybody is using openssl 0.9.7 or later.
1061 const unsigned char *cp
;
1062 cp
= buf
= tor_malloc(len
);
1063 memcpy(buf
,str
,len
);
1064 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1067 crypto_log_errors(LOG_WARN
,"decoding public key");
1070 return _crypto_new_pk_env_rsa(rsa
);
1073 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1074 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1075 * Return 0 on success, -1 on failure.
1078 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1080 unsigned char *buf
, *bufp
;
1083 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1086 buf
= bufp
= tor_malloc(len
+1);
1087 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1089 crypto_log_errors(LOG_WARN
,"encoding public key");
1093 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1101 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1102 * every four spaces. */
1104 add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1107 char *end
= out
+outlen
;
1108 while (*in
&& out
<end
) {
1110 if (++n
== 4 && *in
&& out
<end
) {
1115 tor_assert(out
<end
);
1119 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1120 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1121 * space). Return 0 on success, -1 on failure.
1123 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1124 * of the public key, converted to hexadecimal, in upper case, with a
1125 * space after every four digits.
1127 * If <b>add_space</b> is false, omit the spaces.
1130 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1132 char digest
[DIGEST_LEN
];
1133 char hexdigest
[HEX_DIGEST_LEN
+1];
1134 if (crypto_pk_get_digest(pk
, digest
)) {
1137 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1139 add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1141 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1146 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1149 crypto_pk_check_fingerprint_syntax(const char *s
)
1152 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1154 if (!TOR_ISSPACE(s
[i
])) return 0;
1156 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1159 if (s
[FINGERPRINT_LEN
]) return 0;
1163 /* symmetric crypto */
1165 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1166 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1169 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1173 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1176 /** Set the symmetric key for the cipher in <b>env</b> to the first
1177 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1178 * Return 0 on success, -1 on failure.
1181 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1189 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1193 /** Generate an initialization vector for our AES-CTR cipher; store it
1194 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1196 crypto_cipher_generate_iv(char *iv_out
)
1198 crypto_rand(iv_out
, CIPHER_IV_LEN
);
1201 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1202 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1205 crypto_cipher_set_iv(crypto_cipher_env_t
*env
, const char *iv
)
1209 aes_set_iv(env
->cipher
, iv
);
1213 /** Return a pointer to the key set for the cipher in <b>env</b>.
1216 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1221 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1222 * success, -1 on failure.
1225 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1229 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1233 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1234 * success, -1 on failure.
1237 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1241 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1245 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1246 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1247 * On failure, return -1.
1250 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1251 const char *from
, size_t fromlen
)
1254 tor_assert(env
->cipher
);
1256 tor_assert(fromlen
);
1259 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1263 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1264 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1265 * On failure, return -1.
1268 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1269 const char *from
, size_t fromlen
)
1275 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1279 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1280 * on success, return 0. On failure, return -1.
1283 crypto_cipher_crypt_inplace(crypto_cipher_env_t
*env
, char *buf
, size_t len
)
1285 aes_crypt_inplace(env
->cipher
, buf
, len
);
1289 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1290 * <b>cipher</b> to the buffer in <b>to</b> of length
1291 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1292 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1293 * number of bytes written, on failure, return -1.
1295 * This function adjusts the current position of the counter in <b>cipher</b>
1296 * to immediately after the encrypted data.
1299 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t
*cipher
,
1300 char *to
, size_t tolen
,
1301 const char *from
, size_t fromlen
)
1306 tor_assert(fromlen
< INT_MAX
);
1310 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1313 crypto_cipher_generate_iv(to
);
1314 if (crypto_cipher_set_iv(cipher
, to
)<0)
1316 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1317 return (int)(fromlen
+ CIPHER_IV_LEN
);
1320 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1321 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1322 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1323 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1324 * number of bytes written, on failure, return -1.
1326 * This function adjusts the current position of the counter in <b>cipher</b>
1327 * to immediately after the decrypted data.
1330 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t
*cipher
,
1331 char *to
, size_t tolen
,
1332 const char *from
, size_t fromlen
)
1337 tor_assert(fromlen
< INT_MAX
);
1339 if (fromlen
<= CIPHER_IV_LEN
)
1341 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1344 if (crypto_cipher_set_iv(cipher
, from
)<0)
1346 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1347 return (int)(fromlen
- CIPHER_IV_LEN
);
1352 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1353 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1354 * Return 0 on success, -1 on failure.
1357 crypto_digest(char *digest
, const char *m
, size_t len
)
1361 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1364 /** Intermediate information about the digest of a stream of data. */
1365 struct crypto_digest_env_t
{
1369 /** Allocate and return a new digest object.
1371 crypto_digest_env_t
*
1372 crypto_new_digest_env(void)
1374 crypto_digest_env_t
*r
;
1375 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1380 /** Deallocate a digest object.
1383 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1385 memset(digest
, 0, sizeof(crypto_digest_env_t
));
1389 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1392 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1397 /* Using the SHA1_*() calls directly means we don't support doing
1398 * sha1 in hardware. But so far the delay of getting the question
1399 * to the hardware, and hearing the answer, is likely higher than
1400 * just doing it ourselves. Hashes are fast.
1402 SHA1_Update(&digest
->d
, (void*)data
, len
);
1405 /** Compute the hash of the data that has been passed to the digest
1406 * object; write the first out_len bytes of the result to <b>out</b>.
1407 * <b>out_len</b> must be \<= DIGEST_LEN.
1410 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1411 char *out
, size_t out_len
)
1413 unsigned char r
[DIGEST_LEN
];
1417 tor_assert(out_len
<= DIGEST_LEN
);
1418 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1419 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1420 SHA1_Final(r
, &tmpctx
);
1421 memcpy(out
, r
, out_len
);
1422 memset(r
, 0, sizeof(r
));
1425 /** Allocate and return a new digest object with the same state as
1428 crypto_digest_env_t
*
1429 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1431 crypto_digest_env_t
*r
;
1433 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1434 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1438 /** Replace the state of the digest object <b>into</b> with the state
1439 * of the digest object <b>from</b>.
1442 crypto_digest_assign(crypto_digest_env_t
*into
,
1443 const crypto_digest_env_t
*from
)
1447 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1450 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1451 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1452 * in <b>hmac_out</b>.
1455 crypto_hmac_sha1(char *hmac_out
,
1456 const char *key
, size_t key_len
,
1457 const char *msg
, size_t msg_len
)
1459 tor_assert(key_len
< INT_MAX
);
1460 tor_assert(msg_len
< INT_MAX
);
1461 HMAC(EVP_sha1(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1462 (unsigned char*)hmac_out
, NULL
);
1467 /** Shared P parameter for our DH key exchanged. */
1468 static BIGNUM
*dh_param_p
= NULL
;
1469 /** Shared G parameter for our DH key exchanges. */
1470 static BIGNUM
*dh_param_g
= NULL
;
1472 /** Initialize dh_param_p and dh_param_g if they are not already
1479 if (dh_param_p
&& dh_param_g
)
1487 /* This is from rfc2409, section 6.2. It's a safe prime, and
1488 supposedly it equals:
1489 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1492 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1493 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1494 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1495 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1496 "49286651ECE65381FFFFFFFFFFFFFFFF");
1499 r
= BN_set_word(g
, 2);
1505 #define DH_PRIVATE_KEY_BITS 320
1507 /** Allocate and return a new DH object for a key exchange.
1512 crypto_dh_env_t
*res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1517 if (!(res
->dh
= DH_new()))
1520 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1523 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1526 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1530 crypto_log_errors(LOG_WARN
, "creating DH object");
1531 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1536 /** Return the length of the DH key in <b>dh</b>, in bytes.
1539 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1542 return DH_size(dh
->dh
);
1545 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1546 * success, -1 on failure.
1549 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1552 if (!DH_generate_key(dh
->dh
)) {
1553 crypto_log_errors(LOG_WARN
, "generating DH key");
1556 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1557 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1558 "the-universe chances really do happen. Trying again.");
1559 /* Free and clear the keys, so openssl will actually try again. */
1560 BN_free(dh
->dh
->pub_key
);
1561 BN_free(dh
->dh
->priv_key
);
1562 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1568 /** Generate g^x as necessary, and write the g^x for the key exchange
1569 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1570 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1573 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1577 if (!dh
->dh
->pub_key
) {
1578 if (crypto_dh_generate_public(dh
)<0)
1582 tor_assert(dh
->dh
->pub_key
);
1583 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1584 tor_assert(bytes
>= 0);
1585 if (pubkey_len
< (size_t)bytes
) {
1587 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1588 (int) pubkey_len
, bytes
);
1592 memset(pubkey
, 0, pubkey_len
);
1593 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1598 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1599 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1600 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1603 tor_check_dh_key(BIGNUM
*bn
)
1613 if (BN_cmp(bn
,x
)<=0) {
1614 log_warn(LD_CRYPTO
, "DH key must be at least 2.");
1617 BN_copy(x
,dh_param_p
);
1619 if (BN_cmp(bn
,x
)>=0) {
1620 log_warn(LD_CRYPTO
, "DH key must be at most p-2.");
1628 log_warn(LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1634 #define MIN(a,b) ((a)<(b)?(a):(b))
1635 /** Given a DH key exchange object, and our peer's value of g^y (as a
1636 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1637 * <b>secret_bytes_out</b> bytes of shared key material and write them
1638 * to <b>secret_out</b>. Return the number of bytes generated on success,
1641 * (We generate key material by computing
1642 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1643 * where || is concatenation.)
1646 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1647 const char *pubkey
, size_t pubkey_len
,
1648 char *secret_out
, size_t secret_bytes_out
)
1650 char *secret_tmp
= NULL
;
1651 BIGNUM
*pubkey_bn
= NULL
;
1652 size_t secret_len
=0;
1655 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1656 tor_assert(pubkey_len
< INT_MAX
);
1658 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
1659 (int)pubkey_len
, NULL
)))
1661 if (tor_check_dh_key(pubkey_bn
)<0) {
1662 /* Check for invalid public keys. */
1663 log_warn(LD_CRYPTO
,"Rejected invalid g^x");
1666 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
));
1667 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1669 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
1672 secret_len
= result
;
1673 if (crypto_expand_key_material(secret_tmp
, secret_len
,
1674 secret_out
, secret_bytes_out
)<0)
1676 secret_len
= secret_bytes_out
;
1682 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1685 tor_free(secret_tmp
);
1692 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1693 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1694 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1695 * H(K | [00]) | H(K | [01]) | ....
1697 * Return 0 on success, -1 on failure.
1700 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
1701 char *key_out
, size_t key_out_len
)
1704 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
1705 char digest
[DIGEST_LEN
];
1707 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1708 tor_assert(key_out_len
<= DIGEST_LEN
*256);
1710 memcpy(tmp
, key_in
, key_in_len
);
1711 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
1712 ++i
, cp
+= DIGEST_LEN
) {
1713 tmp
[key_in_len
] = i
;
1714 if (crypto_digest(digest
, tmp
, key_in_len
+1))
1716 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
1718 memset(tmp
, 0, key_in_len
+1);
1720 memset(digest
, 0, sizeof(digest
));
1724 memset(tmp
, 0, key_in_len
+1);
1726 memset(digest
, 0, sizeof(digest
));
1730 /** Free a DH key exchange object.
1733 crypto_dh_free(crypto_dh_env_t
*dh
)
1741 /* random numbers */
1743 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1744 * work for us too. */
1745 #define ADD_ENTROPY 32
1747 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1749 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1751 /* Versions of openssl prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1752 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1753 * that fd without checking whether it fit in the fd_set. Thus, if the
1754 * system has not just been started up, it is unsafe to call */
1755 #define RAND_POLL_IS_SAFE \
1756 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1757 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1758 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1760 /** Seed OpenSSL's random number generator with bytes from the operating
1761 * system. <b>startup</b> should be true iff we have just started Tor and
1762 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1765 crypto_seed_rng(int startup
)
1767 char buf
[ADD_ENTROPY
];
1768 int rand_poll_status
= 0;
1770 /* local variables */
1772 static int provider_set
= 0;
1773 static HCRYPTPROV provider
;
1775 static const char *filenames
[] = {
1776 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1783 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1784 * entropy than we do. We'll try calling that, *and* calling our own entropy
1785 * functions. If one succeeds, we'll accept the RNG as seeded. */
1786 if (startup
|| RAND_POLL_IS_SAFE
) {
1787 rand_poll_status
= RAND_poll();
1788 if (rand_poll_status
== 0)
1789 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
1794 if (!provider_set
) {
1795 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1796 CRYPT_VERIFYCONTEXT
)) {
1797 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
1798 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1799 return rand_poll_status
? 0 : -1;
1804 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1805 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1806 return rand_poll_status
? 0 : -1;
1808 RAND_seed(buf
, sizeof(buf
));
1809 memset(buf
, 0, sizeof(buf
));
1812 for (i
= 0; filenames
[i
]; ++i
) {
1813 fd
= open(filenames
[i
], O_RDONLY
, 0);
1815 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1816 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1818 if (n
!= sizeof(buf
)) {
1820 "Error reading from entropy source (read only %lu bytes).",
1824 RAND_seed(buf
, (int)sizeof(buf
));
1825 memset(buf
, 0, sizeof(buf
));
1829 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1830 return rand_poll_status
? 0 : -1;
1834 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1835 * success, -1 on failure.
1838 crypto_rand(char *to
, size_t n
)
1841 tor_assert(n
< INT_MAX
);
1843 r
= RAND_bytes((unsigned char*)to
, (int)n
);
1845 crypto_log_errors(LOG_WARN
, "generating random data");
1846 return (r
== 1) ? 0 : -1;
1849 /** Return a pseudorandom integer, chosen uniformly from the values
1850 * between 0 and <b>max</b>-1. */
1852 crypto_rand_int(unsigned int max
)
1855 unsigned int cutoff
;
1856 tor_assert(max
< UINT_MAX
);
1857 tor_assert(max
> 0); /* don't div by 0 */
1859 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1860 * distribution with clipping at the upper end of unsigned int's
1863 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1865 crypto_rand((char*)&val
, sizeof(val
));
1871 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1872 * between 0 and <b>max</b>-1. */
1874 crypto_rand_uint64(uint64_t max
)
1878 tor_assert(max
< UINT64_MAX
);
1879 tor_assert(max
> 0); /* don't div by 0 */
1881 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1882 * distribution with clipping at the upper end of unsigned int's
1885 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
1887 crypto_rand((char*)&val
, sizeof(val
));
1893 /** Generate and return a new random hostname starting with <b>prefix</b>,
1894 * ending with <b>suffix</b>, and containing no less than
1895 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1896 * characters between. */
1898 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
1901 char *result
, *rand_bytes
;
1902 int randlen
, rand_bytes_len
;
1903 size_t resultlen
, prefixlen
;
1905 tor_assert(max_rand_len
>= min_rand_len
);
1906 randlen
= min_rand_len
+ crypto_rand_int(max_rand_len
- min_rand_len
+ 1);
1907 prefixlen
= strlen(prefix
);
1908 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
1910 rand_bytes_len
= ((randlen
*5)+7)/8;
1911 if (rand_bytes_len
% 5)
1912 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
1913 rand_bytes
= tor_malloc(rand_bytes_len
);
1914 crypto_rand(rand_bytes
, rand_bytes_len
);
1916 result
= tor_malloc(resultlen
);
1917 memcpy(result
, prefix
, prefixlen
);
1918 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
1919 rand_bytes
, rand_bytes_len
);
1920 tor_free(rand_bytes
);
1921 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
1926 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1929 smartlist_choose(const smartlist_t
*sl
)
1931 int len
= smartlist_len(sl
);
1933 return smartlist_get(sl
,crypto_rand_int(len
));
1934 return NULL
; /* no elements to choose from */
1937 /** Scramble the elements of <b>sl</b> into a random order. */
1939 smartlist_shuffle(smartlist_t
*sl
)
1942 /* From the end of the list to the front, choose at random from the
1943 positions we haven't looked at yet, and swap that position into the
1944 current position. Remember to give "no swap" the same probability as
1946 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
1947 int j
= crypto_rand_int(i
+1);
1948 smartlist_swap(sl
, i
, j
);
1952 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1953 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1954 * bytes. Return the number of bytes written on success; -1 if
1955 * destlen is too short, or other failure.
1958 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1960 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1961 * it ever shows up in the profile. */
1964 tor_assert(srclen
< INT_MAX
);
1966 /* 48 bytes of input -> 64 bytes of output plus newline.
1967 Plus one more byte, in case I'm wrong.
1969 if (destlen
< ((srclen
/48)+1)*66)
1971 if (destlen
> SIZE_T_CEILING
)
1974 EVP_EncodeInit(&ctx
);
1975 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1976 (unsigned char*)src
, (int)srclen
);
1977 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1985 /** Internal table mapping byte values to what they represent in base64.
1986 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
1987 * skipped. Xs are invalid and must not appear in base64. PAD indicates
1989 static const uint8_t base64_decode_table
[256] = {
1990 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
1991 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
1992 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
1993 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
1994 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1995 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
1996 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1997 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
1998 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
1999 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2000 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2001 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2002 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2003 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2004 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2005 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2008 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2009 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2010 * bytes. Return the number of bytes written on success; -1 if
2011 * destlen is too short, or other failure.
2013 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2014 * spaces or padding.
2016 * NOTE 2: This implementation does not check for the correct number of
2017 * padding "=" characters at the end of the string, and does not check
2018 * for internal padding characters.
2021 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2023 #ifdef USE_OPENSSL_BASE64
2026 /* 64 bytes of input -> *up to* 48 bytes of output.
2027 Plus one more byte, in case I'm wrong.
2029 if (destlen
< ((srclen
/64)+1)*49)
2031 if (destlen
> SIZE_T_CEILING
)
2034 EVP_DecodeInit(&ctx
);
2035 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2036 (unsigned char*)src
, srclen
);
2037 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
2041 const char *eos
= src
+srclen
;
2044 char *dest_orig
= dest
;
2046 /* Max number of bits == srclen*6.
2047 * Number of bytes required to hold all bits == (srclen*6)/8.
2048 * Yes, we want to round down: anything that hangs over the end of a
2049 * byte is padding. */
2050 if (destlen
< (srclen
*3)/4)
2052 if (destlen
> SIZE_T_CEILING
)
2055 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2056 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2057 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2059 for ( ; src
< eos
; ++src
) {
2060 unsigned char c
= (unsigned char) *src
;
2061 uint8_t v
= base64_decode_table
[c
];
2064 /* This character isn't allowed in base64. */
2067 /* This character is whitespace, and has no effect. */
2070 /* We've hit an = character: the data is over. */
2073 /* We have an actual 6-bit value. Append it to the bits in n. */
2075 if ((++n_idx
) == 4) {
2076 /* We've accumulated 24 bits in n. Flush them. */
2078 *dest
++ = (n
>>8) & 0xff;
2079 *dest
++ = (n
) & 0xff;
2086 /* If we have leftover bits, we need to cope. */
2090 /* No leftover bits. We win. */
2093 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2096 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2100 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2105 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2106 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2108 return (int)(dest
-dest_orig
);
2115 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2116 * and newline characters, and store the nul-terminated result in the first
2117 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2119 digest_to_base64(char *d64
, const char *digest
)
2122 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
2123 buf
[BASE64_DIGEST_LEN
] = '\0';
2124 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2128 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2129 * trailing newline or = characters), decode it and store the result in the
2130 * first DIGEST_LEN bytes at <b>digest</b>. */
2132 digest_from_base64(char *digest
, const char *d64
)
2134 #ifdef USE_OPENSSL_BASE64
2135 char buf_in
[BASE64_DIGEST_LEN
+3];
2137 if (strlen(d64
) != BASE64_DIGEST_LEN
)
2139 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
2140 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
2141 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
2143 memcpy(digest
, buf
, DIGEST_LEN
);
2146 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2153 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2154 * that srclen*8 is a multiple of 5.
2157 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2159 unsigned int i
, bit
, v
, u
;
2160 size_t nbits
= srclen
* 8;
2162 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2163 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2164 tor_assert(destlen
< SIZE_T_CEILING
);
2166 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2167 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2168 v
= ((uint8_t)src
[bit
/8]) << 8;
2169 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2170 /* set u to the 5-bit value at the bit'th bit of src. */
2171 u
= (v
>> (11-(bit
%8))) & 0x1F;
2172 dest
[i
] = BASE32_CHARS
[u
];
2177 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2178 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2181 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2183 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2184 * it ever shows up in the profile. */
2185 unsigned int i
, j
, bit
;
2190 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2191 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2192 tor_assert(destlen
< SIZE_T_CEILING
);
2194 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2195 tmp
= tor_malloc_zero(srclen
);
2196 for (j
= 0; j
< srclen
; ++j
) {
2197 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2198 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2199 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2201 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2207 /* Assemble result byte-wise by applying five possible cases. */
2208 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2211 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2212 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2215 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2216 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2217 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2220 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2221 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2224 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2225 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2226 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2229 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2230 ((uint8_t)tmp
[(bit
/5)+1]);
2235 memset(tmp
, 0, srclen
);
2241 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2242 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2243 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2244 * are a salt; the 9th byte describes how much iteration to do.
2245 * Does not support <b>key_out_len</b> > DIGEST_LEN.
2248 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
2249 size_t secret_len
, const char *s2k_specifier
)
2251 crypto_digest_env_t
*d
;
2253 size_t count
, tmplen
;
2255 tor_assert(key_out_len
< SIZE_T_CEILING
);
2258 c
= s2k_specifier
[8];
2259 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
2262 tor_assert(key_out_len
<= DIGEST_LEN
);
2264 d
= crypto_new_digest_env();
2265 tmplen
= 8+secret_len
;
2266 tmp
= tor_malloc(tmplen
);
2267 memcpy(tmp
,s2k_specifier
,8);
2268 memcpy(tmp
+8,secret
,secret_len
);
2271 if (count
>= secret_len
) {
2272 crypto_digest_add_bytes(d
, tmp
, secret_len
);
2273 count
-= secret_len
;
2275 crypto_digest_add_bytes(d
, tmp
, count
);
2279 crypto_digest_get_digest(d
, key_out
, key_out_len
);
2280 memset(tmp
, 0, tmplen
);
2282 crypto_free_digest_env(d
);
2285 #ifdef TOR_IS_MULTITHREADED
2286 /** Helper: openssl uses this callback to manipulate mutexes. */
2288 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
2292 if (!_openssl_mutexes
)
2293 /* This is not a really good fix for the
2294 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2297 if (mode
& CRYPTO_LOCK
)
2298 tor_mutex_acquire(_openssl_mutexes
[n
]);
2300 tor_mutex_release(_openssl_mutexes
[n
]);
2303 /** OpenSSL helper type: wraps a Tor mutex so that openssl can */
2304 struct CRYPTO_dynlock_value
{
2308 /** Openssl callback function to allocate a lock: see CRYPTO_set_dynlock_*
2309 * documentation in OpenSSL's docs for more info. */
2310 static struct CRYPTO_dynlock_value
*
2311 _openssl_dynlock_create_cb(const char *file
, int line
)
2313 struct CRYPTO_dynlock_value
*v
;
2316 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
2317 v
->lock
= tor_mutex_new();
2321 /** Openssl callback function to acquire or release a lock: see
2322 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2324 _openssl_dynlock_lock_cb(int mode
, struct CRYPTO_dynlock_value
*v
,
2325 const char *file
, int line
)
2329 if (mode
& CRYPTO_LOCK
)
2330 tor_mutex_acquire(v
->lock
);
2332 tor_mutex_release(v
->lock
);
2335 /** Openssl callback function to free a lock: see CRYPTO_set_dynlock_*
2336 * documentation in OpenSSL's docs for more info. */
2338 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value
*v
,
2339 const char *file
, int line
)
2343 tor_mutex_free(v
->lock
);
2347 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2350 setup_openssl_threading(void)
2353 int n
= CRYPTO_num_locks();
2354 _n_openssl_mutexes
= n
;
2355 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
2356 for (i
=0; i
< n
; ++i
)
2357 _openssl_mutexes
[i
] = tor_mutex_new();
2358 CRYPTO_set_locking_callback(_openssl_locking_cb
);
2359 CRYPTO_set_id_callback(tor_get_thread_id
);
2360 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb
);
2361 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb
);
2362 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb
);
2367 setup_openssl_threading(void)