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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
16 #define WIN32_WINNT 0x400
17 #define _WIN32_WINNT 0x400
18 #define WIN32_LEAN_AND_MEAN
21 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
22 * use either definition. */
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/rand.h>
31 #include <openssl/opensslv.h>
32 #include <openssl/bn.h>
33 #include <openssl/dh.h>
34 #include <openssl/conf.h>
35 #include <openssl/hmac.h>
46 #ifdef HAVE_SYS_FCNTL_H
47 #include <sys/fcntl.h>
50 #define CRYPTO_PRIVATE
55 #include "container.h"
58 #if OPENSSL_VERSION_NUMBER < 0x00907000l
59 #error "We require OpenSSL >= 0.9.7"
62 #include <openssl/engine.h>
64 /** Macro: is k a valid RSA public or private key? */
65 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
66 /** Macro: is k a valid RSA private key? */
67 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
69 #ifdef TOR_IS_MULTITHREADED
70 /** A number of preallocated mutexes for use by OpenSSL. */
71 static tor_mutex_t
**_openssl_mutexes
= NULL
;
72 /** How many mutexes have we allocated for use by OpenSSL? */
73 static int _n_openssl_mutexes
= 0;
76 /** A public key, or a public/private key-pair. */
77 struct crypto_pk_env_t
79 int refs
; /* reference counting so we don't have to copy keys */
83 /** Key and stream information for a stream cipher. */
84 struct crypto_cipher_env_t
86 char key
[CIPHER_KEY_LEN
];
87 aes_cnt_cipher_t
*cipher
;
90 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
91 * while we're waiting for the second.*/
92 struct crypto_dh_env_t
{
96 static int setup_openssl_threading(void);
97 static int tor_check_dh_key(BIGNUM
*bn
);
99 /** Return the number of bytes added by padding method <b>padding</b>.
102 crypto_get_rsa_padding_overhead(int padding
)
106 case RSA_NO_PADDING
: return 0;
107 case RSA_PKCS1_OAEP_PADDING
: return 42;
108 case RSA_PKCS1_PADDING
: return 11;
109 default: tor_assert(0); return -1;
113 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
116 crypto_get_rsa_padding(int padding
)
120 case PK_NO_PADDING
: return RSA_NO_PADDING
;
121 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
122 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
123 default: tor_assert(0); return -1;
127 /** Boolean: has OpenSSL's crypto been initialized? */
128 static int _crypto_global_initialized
= 0;
130 /** Log all pending crypto errors at level <b>severity</b>. Use
131 * <b>doing</b> to describe our current activities.
134 crypto_log_errors(int severity
, const char *doing
)
137 const char *msg
, *lib
, *func
;
138 while ((err
= ERR_get_error()) != 0) {
139 msg
= (const char*)ERR_reason_error_string(err
);
140 lib
= (const char*)ERR_lib_error_string(err
);
141 func
= (const char*)ERR_func_error_string(err
);
142 if (!msg
) msg
= "(null)";
143 if (!lib
) lib
= "(null)";
144 if (!func
) func
= "(null)";
146 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
147 doing
, msg
, lib
, func
);
149 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
154 /** Log any OpenSSL engines we're using at NOTICE. */
156 log_engine(const char *fn
, ENGINE
*e
)
159 const char *name
, *id
;
160 name
= ENGINE_get_name(e
);
161 id
= ENGINE_get_id(e
);
162 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
163 name
?name
:"?", id
?id
:"?", fn
);
165 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
169 /** Initialize the crypto library. Return 0 on success, -1 on failure.
172 crypto_global_init(int useAccel
)
174 if (!_crypto_global_initialized
) {
175 ERR_load_crypto_strings();
176 OpenSSL_add_all_algorithms();
177 _crypto_global_initialized
= 1;
178 setup_openssl_threading();
179 /* XXX the below is a bug, since we can't know if we're supposed
180 * to be using hardware acceleration or not. we should arrange
181 * for this function to be called before init_keys. But make it
182 * not complain loudly, at least until we make acceleration work. */
184 log_info(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
187 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
188 ENGINE_load_builtin_engines();
189 if (!ENGINE_register_all_complete())
192 /* XXXX make sure this isn't leaking. */
193 log_engine("RSA", ENGINE_get_default_RSA());
194 log_engine("DH", ENGINE_get_default_DH());
195 log_engine("RAND", ENGINE_get_default_RAND());
196 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
197 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
198 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
200 return crypto_seed_rng(1);
205 /** Free crypto resources held by this thread. */
207 crypto_thread_cleanup(void)
212 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
215 crypto_global_cleanup(void)
221 CONF_modules_unload(1);
222 CRYPTO_cleanup_all_ex_data();
223 #ifdef TOR_IS_MULTITHREADED
224 if (_n_openssl_mutexes
) {
225 int n
= _n_openssl_mutexes
;
226 tor_mutex_t
**ms
= _openssl_mutexes
;
228 _openssl_mutexes
= NULL
;
229 _n_openssl_mutexes
= 0;
231 tor_mutex_free(ms
[i
]);
239 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
241 _crypto_new_pk_env_rsa(RSA
*rsa
)
243 crypto_pk_env_t
*env
;
245 env
= tor_malloc(sizeof(crypto_pk_env_t
));
251 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
252 * returns NULL if this isn't an RSA key. */
254 _crypto_new_pk_env_evp_pkey(EVP_PKEY
*pkey
)
257 if (!(rsa
= EVP_PKEY_get1_RSA(pkey
)))
259 return _crypto_new_pk_env_rsa(rsa
);
262 /** Helper, used by tor-checkkey.c. Return the RSA from a crypto_pk_env_t. */
264 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
269 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
270 * private is set, include the private-key portion of the key. */
272 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
275 EVP_PKEY
*pkey
= NULL
;
276 tor_assert(env
->key
);
278 if (!(key
= RSAPrivateKey_dup(env
->key
)))
281 if (!(key
= RSAPublicKey_dup(env
->key
)))
284 if (!(pkey
= EVP_PKEY_new()))
286 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
297 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
300 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
305 /** Allocate and return storage for a public key. The key itself will not yet
309 crypto_new_pk_env(void)
314 if (!rsa
) return NULL
;
315 return _crypto_new_pk_env_rsa(rsa
);
318 /** Release a reference to an asymmetric key; when all the references
319 * are released, free the key.
322 crypto_free_pk_env(crypto_pk_env_t
*env
)
335 /** Create a new symmetric cipher for a given key and encryption flag
336 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
339 crypto_cipher_env_t
*
340 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
343 crypto_cipher_env_t
*crypto
= NULL
;
345 if (! (crypto
= crypto_new_cipher_env())) {
346 log_warn(LD_CRYPTO
, "Unable to allocate crypto object");
350 if (crypto_cipher_set_key(crypto
, key
)) {
351 crypto_log_errors(LOG_WARN
, "setting symmetric key");
356 r
= crypto_cipher_encrypt_init_cipher(crypto
);
358 r
= crypto_cipher_decrypt_init_cipher(crypto
);
366 crypto_free_cipher_env(crypto
);
370 /** Allocate and return a new symmetric cipher.
372 crypto_cipher_env_t
*
373 crypto_new_cipher_env(void)
375 crypto_cipher_env_t
*env
;
377 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
378 env
->cipher
= aes_new_cipher();
382 /** Free a symmetric cipher.
385 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
389 tor_assert(env
->cipher
);
390 aes_free_cipher(env
->cipher
);
391 memset(env
, 0, sizeof(crypto_cipher_env_t
));
395 /* public key crypto */
397 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
398 * success, -1 on failure.
401 crypto_pk_generate_key(crypto_pk_env_t
*env
)
407 #if OPENSSL_VERSION_NUMBER < 0x00908000l
408 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
409 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
411 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
413 BIGNUM
*e
= BN_new();
417 if (! BN_set_word(e
, 65537))
422 if (RSA_generate_key_ex(r
, PK_BYTES
*8, e
, NULL
) == -1)
435 crypto_log_errors(LOG_WARN
, "generating RSA key");
442 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
443 * Return 0 on success, -1 on failure.
445 /* Used here, and used for testing. */
447 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
455 /* Create a read-only memory BIO, backed by the NUL-terminated string 's' */
456 b
= BIO_new_mem_buf((char*)s
, -1);
461 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
466 crypto_log_errors(LOG_WARN
, "Error parsing private key");
472 /** Read a PEM-encoded private key from the file named by
473 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
476 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
482 /* Read the file into a string. */
483 contents
= read_file_to_str(keyfile
, 0, NULL
);
485 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
489 /* Try to parse it. */
490 r
= crypto_pk_read_private_key_from_string(env
, contents
);
493 return -1; /* read_private_key_from_string already warned, so we don't.*/
495 /* Make sure it's valid. */
496 if (crypto_pk_check_key(env
) <= 0)
502 /** Helper function to implement crypto_pk_write_*_key_to_string. */
504 crypto_pk_write_key_to_string_impl(crypto_pk_env_t
*env
, char **dest
,
505 size_t *len
, int is_public
)
512 tor_assert(env
->key
);
515 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
517 /* Now you can treat b as if it were a file. Just use the
518 * PEM_*_bio_* functions instead of the non-bio variants.
521 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
523 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
526 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
531 BIO_get_mem_ptr(b
, &buf
);
532 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
535 *dest
= tor_malloc(buf
->length
+1);
536 memcpy(*dest
, buf
->data
, buf
->length
);
537 (*dest
)[buf
->length
] = 0; /* nul terminate it */
544 /** PEM-encode the public key portion of <b>env</b> and write it to a
545 * newly allocated string. On success, set *<b>dest</b> to the new
546 * string, *<b>len</b> to the string's length, and return 0. On
547 * failure, return -1.
550 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
553 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
556 /** PEM-encode the private key portion of <b>env</b> and write it to a
557 * newly allocated string. On success, set *<b>dest</b> to the new
558 * string, *<b>len</b> to the string's length, and return 0. On
559 * failure, return -1.
562 crypto_pk_write_private_key_to_string(crypto_pk_env_t
*env
, char **dest
,
565 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
568 /** Read a PEM-encoded public key from the first <b>len</b> characters of
569 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
573 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
580 tor_assert(len
<INT_MAX
);
582 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
584 BIO_write(b
, src
, (int)len
);
588 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
591 crypto_log_errors(LOG_WARN
, "reading public key from string");
598 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
599 * PEM-encoded. Return 0 on success, -1 on failure.
602 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
611 tor_assert(PRIVATE_KEY_OK(env
));
613 if (!(bio
= BIO_new(BIO_s_mem())))
615 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
617 crypto_log_errors(LOG_WARN
, "writing private key");
621 len
= BIO_get_mem_data(bio
, &cp
);
622 tor_assert(len
>= 0);
623 s
= tor_malloc(len
+1);
626 r
= write_str_to_file(fname
, s
, 0);
632 /** Return true iff <b>env</b> has a valid key.
635 crypto_pk_check_key(crypto_pk_env_t
*env
)
640 r
= RSA_check_key(env
->key
);
642 crypto_log_errors(LOG_WARN
,"checking RSA key");
646 /** Return true iff <b>key</b> contains the private-key portion of the RSA
649 crypto_pk_key_is_private(const crypto_pk_env_t
*key
)
652 return PRIVATE_KEY_OK(key
);
655 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
656 * if a==b, and 1 if a\>b.
659 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
666 if (!a
->key
|| !b
->key
)
669 tor_assert(PUBLIC_KEY_OK(a
));
670 tor_assert(PUBLIC_KEY_OK(b
));
671 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
674 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
677 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
679 crypto_pk_keysize(crypto_pk_env_t
*env
)
682 tor_assert(env
->key
);
684 return (size_t) RSA_size(env
->key
);
687 /** Increase the reference count of <b>env</b>, and return it.
690 crypto_pk_dup_key(crypto_pk_env_t
*env
)
693 tor_assert(env
->key
);
699 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
701 crypto_pk_copy_full(crypto_pk_env_t
*env
)
705 tor_assert(env
->key
);
707 if (PRIVATE_KEY_OK(env
)) {
708 new_key
= RSAPrivateKey_dup(env
->key
);
710 new_key
= RSAPublicKey_dup(env
->key
);
713 return _crypto_new_pk_env_rsa(new_key
);
716 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
717 * in <b>env</b>, using the padding method <b>padding</b>. On success,
718 * write the result to <b>to</b>, and return the number of bytes
719 * written. On failure, return -1.
722 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
723 const char *from
, size_t fromlen
, int padding
)
729 tor_assert(fromlen
<INT_MAX
);
731 r
= RSA_public_encrypt((int)fromlen
,
732 (unsigned char*)from
, (unsigned char*)to
,
733 env
->key
, crypto_get_rsa_padding(padding
));
735 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
741 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
742 * in <b>env</b>, using the padding method <b>padding</b>. On success,
743 * write the result to <b>to</b>, and return the number of bytes
744 * written. On failure, return -1.
747 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
748 const char *from
, size_t fromlen
,
749 int padding
, int warnOnFailure
)
755 tor_assert(env
->key
);
756 tor_assert(fromlen
<INT_MAX
);
758 /* Not a private key */
761 r
= RSA_private_decrypt((int)fromlen
,
762 (unsigned char*)from
, (unsigned char*)to
,
763 env
->key
, crypto_get_rsa_padding(padding
));
766 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
767 "performing RSA decryption");
773 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
774 * public key in <b>env</b>, using PKCS1 padding. On success, write the
775 * signed data to <b>to</b>, and return the number of bytes written.
776 * On failure, return -1.
779 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
780 const char *from
, size_t fromlen
)
786 tor_assert(fromlen
< INT_MAX
);
787 r
= RSA_public_decrypt((int)fromlen
,
788 (unsigned char*)from
, (unsigned char*)to
,
789 env
->key
, RSA_PKCS1_PADDING
);
792 crypto_log_errors(LOG_WARN
, "checking RSA signature");
798 /** Check a siglen-byte long signature at <b>sig</b> against
799 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
800 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
801 * SHA1(data). Else return -1.
804 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
805 size_t datalen
, const char *sig
, size_t siglen
)
807 char digest
[DIGEST_LEN
];
815 if (crypto_digest(digest
,data
,datalen
)<0) {
816 log_warn(LD_BUG
, "couldn't compute digest");
819 buf
= tor_malloc(crypto_pk_keysize(env
)+1);
820 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
821 if (r
!= DIGEST_LEN
) {
822 log_warn(LD_CRYPTO
, "Invalid signature");
826 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
827 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
836 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
837 * <b>env</b>, using PKCS1 padding. On success, write the signature to
838 * <b>to</b>, and return the number of bytes written. On failure, return
842 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
843 const char *from
, size_t fromlen
)
849 tor_assert(fromlen
< INT_MAX
);
851 /* Not a private key */
854 r
= RSA_private_encrypt((int)fromlen
,
855 (unsigned char*)from
, (unsigned char*)to
,
856 env
->key
, RSA_PKCS1_PADDING
);
858 crypto_log_errors(LOG_WARN
, "generating RSA signature");
864 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
865 * <b>from</b>; sign the data with the private key in <b>env</b>, and
866 * store it in <b>to</b>. Return the number of bytes written on
867 * success, and -1 on failure.
870 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
871 const char *from
, size_t fromlen
)
874 char digest
[DIGEST_LEN
];
875 if (crypto_digest(digest
,from
,fromlen
)<0)
877 r
= crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
878 memset(digest
, 0, sizeof(digest
));
882 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
883 * bytes of data from <b>from</b>, with padding type 'padding',
884 * storing the results on <b>to</b>.
886 * If no padding is used, the public key must be at least as large as
889 * Returns the number of bytes written on success, -1 on failure.
891 * The encrypted data consists of:
892 * - The source data, padded and encrypted with the public key, if the
893 * padded source data is no longer than the public key, and <b>force</b>
895 * - The beginning of the source data prefixed with a 16-byte symmetric key,
896 * padded and encrypted with the public key; followed by the rest of
897 * the source data encrypted in AES-CTR mode with the symmetric key.
900 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
904 int padding
, int force
)
906 int overhead
, outlen
, r
;
907 size_t pkeylen
, symlen
;
908 crypto_cipher_env_t
*cipher
= NULL
;
915 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
916 pkeylen
= crypto_pk_keysize(env
);
918 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
921 if (!force
&& fromlen
+overhead
<= pkeylen
) {
922 /* It all fits in a single encrypt. */
923 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
925 cipher
= crypto_new_cipher_env();
926 if (!cipher
) return -1;
927 if (crypto_cipher_generate_key(cipher
)<0)
929 /* You can't just run around RSA-encrypting any bitstream: if it's
930 * greater than the RSA key, then OpenSSL will happily encrypt, and
931 * later decrypt to the wrong value. So we set the first bit of
932 * 'cipher->key' to 0 if we aren't padding. This means that our
933 * symmetric key is really only 127 bits.
935 if (padding
== PK_NO_PADDING
)
936 cipher
->key
[0] &= 0x7f;
937 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
939 buf
= tor_malloc(pkeylen
+1);
940 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
941 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
943 /* Length of symmetrically encrypted data. */
944 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
946 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
947 if (outlen
!=(int)pkeylen
) {
950 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
951 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
954 memset(buf
, 0, pkeylen
);
956 crypto_free_cipher_env(cipher
);
957 tor_assert(outlen
+symlen
< INT_MAX
);
958 return (int)(outlen
+ symlen
);
961 memset(buf
, 0, pkeylen
);
964 if (cipher
) crypto_free_cipher_env(cipher
);
968 /** Invert crypto_pk_public_hybrid_encrypt. */
970 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
974 int padding
, int warnOnFailure
)
978 crypto_cipher_env_t
*cipher
= NULL
;
981 pkeylen
= crypto_pk_keysize(env
);
983 if (fromlen
<= pkeylen
) {
984 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,
987 buf
= tor_malloc(pkeylen
+1);
988 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,
991 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
992 "Error decrypting public-key data");
995 if (outlen
< CIPHER_KEY_LEN
) {
996 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
997 "No room for a symmetric key");
1000 cipher
= crypto_create_init_cipher(buf
, 0);
1004 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1005 outlen
-= CIPHER_KEY_LEN
;
1006 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1009 memset(buf
,0,pkeylen
);
1011 crypto_free_cipher_env(cipher
);
1012 tor_assert(outlen
+ fromlen
< INT_MAX
);
1013 return (int)(outlen
+ (fromlen
-pkeylen
));
1015 memset(buf
,0,pkeylen
);
1017 if (cipher
) crypto_free_cipher_env(cipher
);
1021 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1022 * Return -1 on error, or the number of characters used on success.
1025 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, size_t dest_len
)
1028 unsigned char *buf
, *cp
;
1029 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1030 if (len
< 0 || (size_t)len
> dest_len
)
1032 cp
= buf
= tor_malloc(len
+1);
1033 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1035 crypto_log_errors(LOG_WARN
,"encoding public key");
1039 /* We don't encode directly into 'dest', because that would be illegal
1040 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1042 memcpy(dest
,buf
,len
);
1047 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1048 * success and NULL on failure.
1051 crypto_pk_asn1_decode(const char *str
, size_t len
)
1055 /* This ifdef suppresses a type warning. Take out the first case once
1056 * everybody is using OpenSSL 0.9.7 or later.
1058 const unsigned char *cp
;
1059 cp
= buf
= tor_malloc(len
);
1060 memcpy(buf
,str
,len
);
1061 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1064 crypto_log_errors(LOG_WARN
,"decoding public key");
1067 return _crypto_new_pk_env_rsa(rsa
);
1070 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1071 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1072 * Return 0 on success, -1 on failure.
1075 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1077 unsigned char *buf
, *bufp
;
1080 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1083 buf
= bufp
= tor_malloc(len
+1);
1084 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1086 crypto_log_errors(LOG_WARN
,"encoding public key");
1090 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1098 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1099 * every four spaces. */
1101 add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1104 char *end
= out
+outlen
;
1105 while (*in
&& out
<end
) {
1107 if (++n
== 4 && *in
&& out
<end
) {
1112 tor_assert(out
<end
);
1116 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1117 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1118 * space). Return 0 on success, -1 on failure.
1120 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1121 * of the public key, converted to hexadecimal, in upper case, with a
1122 * space after every four digits.
1124 * If <b>add_space</b> is false, omit the spaces.
1127 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1129 char digest
[DIGEST_LEN
];
1130 char hexdigest
[HEX_DIGEST_LEN
+1];
1131 if (crypto_pk_get_digest(pk
, digest
)) {
1134 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1136 add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1138 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1143 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1146 crypto_pk_check_fingerprint_syntax(const char *s
)
1149 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1151 if (!TOR_ISSPACE(s
[i
])) return 0;
1153 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1156 if (s
[FINGERPRINT_LEN
]) return 0;
1160 /* symmetric crypto */
1162 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1163 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1166 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1170 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1173 /** Set the symmetric key for the cipher in <b>env</b> to the first
1174 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1175 * Return 0 on success, -1 on failure.
1178 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1186 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1190 /** Generate an initialization vector for our AES-CTR cipher; store it
1191 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1193 crypto_cipher_generate_iv(char *iv_out
)
1195 crypto_rand(iv_out
, CIPHER_IV_LEN
);
1198 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1199 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1202 crypto_cipher_set_iv(crypto_cipher_env_t
*env
, const char *iv
)
1206 aes_set_iv(env
->cipher
, iv
);
1210 /** Return a pointer to the key set for the cipher in <b>env</b>.
1213 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1218 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1219 * success, -1 on failure.
1222 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1226 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1230 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1231 * success, -1 on failure.
1234 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1238 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1242 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1243 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1244 * On failure, return -1.
1247 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1248 const char *from
, size_t fromlen
)
1251 tor_assert(env
->cipher
);
1253 tor_assert(fromlen
);
1256 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1260 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1261 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1262 * On failure, return -1.
1265 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1266 const char *from
, size_t fromlen
)
1272 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1276 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1277 * on success, return 0. On failure, return -1.
1280 crypto_cipher_crypt_inplace(crypto_cipher_env_t
*env
, char *buf
, size_t len
)
1282 aes_crypt_inplace(env
->cipher
, buf
, len
);
1286 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1287 * <b>cipher</b> to the buffer in <b>to</b> of length
1288 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1289 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1290 * number of bytes written, on failure, return -1.
1292 * This function adjusts the current position of the counter in <b>cipher</b>
1293 * to immediately after the encrypted data.
1296 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t
*cipher
,
1297 char *to
, size_t tolen
,
1298 const char *from
, size_t fromlen
)
1303 tor_assert(fromlen
< INT_MAX
);
1307 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1310 crypto_cipher_generate_iv(to
);
1311 if (crypto_cipher_set_iv(cipher
, to
)<0)
1313 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1314 return (int)(fromlen
+ CIPHER_IV_LEN
);
1317 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1318 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1319 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1320 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1321 * number of bytes written, on failure, return -1.
1323 * This function adjusts the current position of the counter in <b>cipher</b>
1324 * to immediately after the decrypted data.
1327 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t
*cipher
,
1328 char *to
, size_t tolen
,
1329 const char *from
, size_t fromlen
)
1334 tor_assert(fromlen
< INT_MAX
);
1336 if (fromlen
<= CIPHER_IV_LEN
)
1338 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1341 if (crypto_cipher_set_iv(cipher
, from
)<0)
1343 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1344 return (int)(fromlen
- CIPHER_IV_LEN
);
1349 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1350 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1351 * Return 0 on success, -1 on failure.
1354 crypto_digest(char *digest
, const char *m
, size_t len
)
1358 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1361 /** Intermediate information about the digest of a stream of data. */
1362 struct crypto_digest_env_t
{
1366 /** Allocate and return a new digest object.
1368 crypto_digest_env_t
*
1369 crypto_new_digest_env(void)
1371 crypto_digest_env_t
*r
;
1372 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1377 /** Deallocate a digest object.
1380 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1382 memset(digest
, 0, sizeof(crypto_digest_env_t
));
1386 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1389 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1394 /* Using the SHA1_*() calls directly means we don't support doing
1395 * SHA1 in hardware. But so far the delay of getting the question
1396 * to the hardware, and hearing the answer, is likely higher than
1397 * just doing it ourselves. Hashes are fast.
1399 SHA1_Update(&digest
->d
, (void*)data
, len
);
1402 /** Compute the hash of the data that has been passed to the digest
1403 * object; write the first out_len bytes of the result to <b>out</b>.
1404 * <b>out_len</b> must be \<= DIGEST_LEN.
1407 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1408 char *out
, size_t out_len
)
1410 unsigned char r
[DIGEST_LEN
];
1414 tor_assert(out_len
<= DIGEST_LEN
);
1415 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1416 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1417 SHA1_Final(r
, &tmpctx
);
1418 memcpy(out
, r
, out_len
);
1419 memset(r
, 0, sizeof(r
));
1422 /** Allocate and return a new digest object with the same state as
1425 crypto_digest_env_t
*
1426 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1428 crypto_digest_env_t
*r
;
1430 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1431 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1435 /** Replace the state of the digest object <b>into</b> with the state
1436 * of the digest object <b>from</b>.
1439 crypto_digest_assign(crypto_digest_env_t
*into
,
1440 const crypto_digest_env_t
*from
)
1444 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1447 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1448 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1449 * in <b>hmac_out</b>.
1452 crypto_hmac_sha1(char *hmac_out
,
1453 const char *key
, size_t key_len
,
1454 const char *msg
, size_t msg_len
)
1456 tor_assert(key_len
< INT_MAX
);
1457 tor_assert(msg_len
< INT_MAX
);
1458 HMAC(EVP_sha1(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1459 (unsigned char*)hmac_out
, NULL
);
1464 /** Shared P parameter for our DH key exchanged. */
1465 static BIGNUM
*dh_param_p
= NULL
;
1466 /** Shared G parameter for our DH key exchanges. */
1467 static BIGNUM
*dh_param_g
= NULL
;
1469 /** Initialize dh_param_p and dh_param_g if they are not already
1476 if (dh_param_p
&& dh_param_g
)
1484 /* This is from rfc2409, section 6.2. It's a safe prime, and
1485 supposedly it equals:
1486 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1489 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1490 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1491 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1492 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1493 "49286651ECE65381FFFFFFFFFFFFFFFF");
1496 r
= BN_set_word(g
, 2);
1502 #define DH_PRIVATE_KEY_BITS 320
1504 /** Allocate and return a new DH object for a key exchange.
1509 crypto_dh_env_t
*res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1514 if (!(res
->dh
= DH_new()))
1517 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1520 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1523 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1527 crypto_log_errors(LOG_WARN
, "creating DH object");
1528 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1533 /** Return the length of the DH key in <b>dh</b>, in bytes.
1536 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1539 return DH_size(dh
->dh
);
1542 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1543 * success, -1 on failure.
1546 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1549 if (!DH_generate_key(dh
->dh
)) {
1550 crypto_log_errors(LOG_WARN
, "generating DH key");
1553 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1554 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1555 "the-universe chances really do happen. Trying again.");
1556 /* Free and clear the keys, so OpenSSL will actually try again. */
1557 BN_free(dh
->dh
->pub_key
);
1558 BN_free(dh
->dh
->priv_key
);
1559 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1565 /** Generate g^x as necessary, and write the g^x for the key exchange
1566 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1567 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1570 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1574 if (!dh
->dh
->pub_key
) {
1575 if (crypto_dh_generate_public(dh
)<0)
1579 tor_assert(dh
->dh
->pub_key
);
1580 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1581 tor_assert(bytes
>= 0);
1582 if (pubkey_len
< (size_t)bytes
) {
1584 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1585 (int) pubkey_len
, bytes
);
1589 memset(pubkey
, 0, pubkey_len
);
1590 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1595 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1596 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1597 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1600 tor_check_dh_key(BIGNUM
*bn
)
1610 if (BN_cmp(bn
,x
)<=0) {
1611 log_warn(LD_CRYPTO
, "DH key must be at least 2.");
1614 BN_copy(x
,dh_param_p
);
1616 if (BN_cmp(bn
,x
)>=0) {
1617 log_warn(LD_CRYPTO
, "DH key must be at most p-2.");
1625 log_warn(LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1631 #define MIN(a,b) ((a)<(b)?(a):(b))
1632 /** Given a DH key exchange object, and our peer's value of g^y (as a
1633 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1634 * <b>secret_bytes_out</b> bytes of shared key material and write them
1635 * to <b>secret_out</b>. Return the number of bytes generated on success,
1638 * (We generate key material by computing
1639 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1640 * where || is concatenation.)
1643 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1644 const char *pubkey
, size_t pubkey_len
,
1645 char *secret_out
, size_t secret_bytes_out
)
1647 char *secret_tmp
= NULL
;
1648 BIGNUM
*pubkey_bn
= NULL
;
1649 size_t secret_len
=0;
1652 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1653 tor_assert(pubkey_len
< INT_MAX
);
1655 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
1656 (int)pubkey_len
, NULL
)))
1658 if (tor_check_dh_key(pubkey_bn
)<0) {
1659 /* Check for invalid public keys. */
1660 log_warn(LD_CRYPTO
,"Rejected invalid g^x");
1663 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
));
1664 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1666 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
1669 secret_len
= result
;
1670 if (crypto_expand_key_material(secret_tmp
, secret_len
,
1671 secret_out
, secret_bytes_out
)<0)
1673 secret_len
= secret_bytes_out
;
1679 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1682 tor_free(secret_tmp
);
1689 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1690 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1691 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1692 * H(K | [00]) | H(K | [01]) | ....
1694 * Return 0 on success, -1 on failure.
1697 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
1698 char *key_out
, size_t key_out_len
)
1701 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
1702 char digest
[DIGEST_LEN
];
1704 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1705 tor_assert(key_out_len
<= DIGEST_LEN
*256);
1707 memcpy(tmp
, key_in
, key_in_len
);
1708 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
1709 ++i
, cp
+= DIGEST_LEN
) {
1710 tmp
[key_in_len
] = i
;
1711 if (crypto_digest(digest
, tmp
, key_in_len
+1))
1713 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
1715 memset(tmp
, 0, key_in_len
+1);
1717 memset(digest
, 0, sizeof(digest
));
1721 memset(tmp
, 0, key_in_len
+1);
1723 memset(digest
, 0, sizeof(digest
));
1727 /** Free a DH key exchange object.
1730 crypto_dh_free(crypto_dh_env_t
*dh
)
1738 /* random numbers */
1740 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1741 * work for us too. */
1742 #define ADD_ENTROPY 32
1744 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1746 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1748 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1749 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1750 * that fd without checking whether it fit in the fd_set. Thus, if the
1751 * system has not just been started up, it is unsafe to call */
1752 #define RAND_POLL_IS_SAFE \
1753 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1754 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1755 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1757 /** Seed OpenSSL's random number generator with bytes from the operating
1758 * system. <b>startup</b> should be true iff we have just started Tor and
1759 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1762 crypto_seed_rng(int startup
)
1764 char buf
[ADD_ENTROPY
];
1765 int rand_poll_status
= 0;
1767 /* local variables */
1769 static int provider_set
= 0;
1770 static HCRYPTPROV provider
;
1772 static const char *filenames
[] = {
1773 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1780 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1781 * entropy than we do. We'll try calling that, *and* calling our own entropy
1782 * functions. If one succeeds, we'll accept the RNG as seeded. */
1783 if (startup
|| RAND_POLL_IS_SAFE
) {
1784 rand_poll_status
= RAND_poll();
1785 if (rand_poll_status
== 0)
1786 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
1791 if (!provider_set
) {
1792 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1793 CRYPT_VERIFYCONTEXT
)) {
1794 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
1795 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1796 return rand_poll_status
? 0 : -1;
1801 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1802 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1803 return rand_poll_status
? 0 : -1;
1805 RAND_seed(buf
, sizeof(buf
));
1806 memset(buf
, 0, sizeof(buf
));
1809 for (i
= 0; filenames
[i
]; ++i
) {
1810 fd
= open(filenames
[i
], O_RDONLY
, 0);
1812 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1813 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1815 if (n
!= sizeof(buf
)) {
1817 "Error reading from entropy source (read only %lu bytes).",
1821 RAND_seed(buf
, (int)sizeof(buf
));
1822 memset(buf
, 0, sizeof(buf
));
1826 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1827 return rand_poll_status
? 0 : -1;
1831 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1832 * success, -1 on failure.
1835 crypto_rand(char *to
, size_t n
)
1838 tor_assert(n
< INT_MAX
);
1840 r
= RAND_bytes((unsigned char*)to
, (int)n
);
1842 crypto_log_errors(LOG_WARN
, "generating random data");
1843 return (r
== 1) ? 0 : -1;
1846 /** Return a pseudorandom integer, chosen uniformly from the values
1847 * between 0 and <b>max</b>-1. */
1849 crypto_rand_int(unsigned int max
)
1852 unsigned int cutoff
;
1853 tor_assert(max
< UINT_MAX
);
1854 tor_assert(max
> 0); /* don't div by 0 */
1856 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1857 * distribution with clipping at the upper end of unsigned int's
1860 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1862 crypto_rand((char*)&val
, sizeof(val
));
1868 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1869 * between 0 and <b>max</b>-1. */
1871 crypto_rand_uint64(uint64_t max
)
1875 tor_assert(max
< UINT64_MAX
);
1876 tor_assert(max
> 0); /* don't div by 0 */
1878 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1879 * distribution with clipping at the upper end of unsigned int's
1882 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
1884 crypto_rand((char*)&val
, sizeof(val
));
1890 /** Generate and return a new random hostname starting with <b>prefix</b>,
1891 * ending with <b>suffix</b>, and containing no less than
1892 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1893 * characters between. */
1895 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
1898 char *result
, *rand_bytes
;
1899 int randlen
, rand_bytes_len
;
1900 size_t resultlen
, prefixlen
;
1902 tor_assert(max_rand_len
>= min_rand_len
);
1903 randlen
= min_rand_len
+ crypto_rand_int(max_rand_len
- min_rand_len
+ 1);
1904 prefixlen
= strlen(prefix
);
1905 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
1907 rand_bytes_len
= ((randlen
*5)+7)/8;
1908 if (rand_bytes_len
% 5)
1909 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
1910 rand_bytes
= tor_malloc(rand_bytes_len
);
1911 crypto_rand(rand_bytes
, rand_bytes_len
);
1913 result
= tor_malloc(resultlen
);
1914 memcpy(result
, prefix
, prefixlen
);
1915 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
1916 rand_bytes
, rand_bytes_len
);
1917 tor_free(rand_bytes
);
1918 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
1923 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1926 smartlist_choose(const smartlist_t
*sl
)
1928 int len
= smartlist_len(sl
);
1930 return smartlist_get(sl
,crypto_rand_int(len
));
1931 return NULL
; /* no elements to choose from */
1934 /** Scramble the elements of <b>sl</b> into a random order. */
1936 smartlist_shuffle(smartlist_t
*sl
)
1939 /* From the end of the list to the front, choose at random from the
1940 positions we haven't looked at yet, and swap that position into the
1941 current position. Remember to give "no swap" the same probability as
1943 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
1944 int j
= crypto_rand_int(i
+1);
1945 smartlist_swap(sl
, i
, j
);
1949 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1950 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1951 * bytes. Return the number of bytes written on success; -1 if
1952 * destlen is too short, or other failure.
1955 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1957 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1958 * it ever shows up in the profile. */
1961 tor_assert(srclen
< INT_MAX
);
1963 /* 48 bytes of input -> 64 bytes of output plus newline.
1964 Plus one more byte, in case I'm wrong.
1966 if (destlen
< ((srclen
/48)+1)*66)
1968 if (destlen
> SIZE_T_CEILING
)
1971 EVP_EncodeInit(&ctx
);
1972 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1973 (unsigned char*)src
, (int)srclen
);
1974 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1982 /** Internal table mapping byte values to what they represent in base64.
1983 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
1984 * skipped. Xs are invalid and must not appear in base64. PAD indicates
1986 static const uint8_t base64_decode_table
[256] = {
1987 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
1988 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
1989 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
1990 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
1991 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1992 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
1993 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1994 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
1995 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
1996 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
1997 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 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
,
2005 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2006 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2007 * bytes. Return the number of bytes written on success; -1 if
2008 * destlen is too short, or other failure.
2010 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2011 * spaces or padding.
2013 * NOTE 2: This implementation does not check for the correct number of
2014 * padding "=" characters at the end of the string, and does not check
2015 * for internal padding characters.
2018 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2020 #ifdef USE_OPENSSL_BASE64
2023 /* 64 bytes of input -> *up to* 48 bytes of output.
2024 Plus one more byte, in case I'm wrong.
2026 if (destlen
< ((srclen
/64)+1)*49)
2028 if (destlen
> SIZE_T_CEILING
)
2031 EVP_DecodeInit(&ctx
);
2032 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2033 (unsigned char*)src
, srclen
);
2034 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
2038 const char *eos
= src
+srclen
;
2041 char *dest_orig
= dest
;
2043 /* Max number of bits == srclen*6.
2044 * Number of bytes required to hold all bits == (srclen*6)/8.
2045 * Yes, we want to round down: anything that hangs over the end of a
2046 * byte is padding. */
2047 if (destlen
< (srclen
*3)/4)
2049 if (destlen
> SIZE_T_CEILING
)
2052 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2053 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2054 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2056 for ( ; src
< eos
; ++src
) {
2057 unsigned char c
= (unsigned char) *src
;
2058 uint8_t v
= base64_decode_table
[c
];
2061 /* This character isn't allowed in base64. */
2064 /* This character is whitespace, and has no effect. */
2067 /* We've hit an = character: the data is over. */
2070 /* We have an actual 6-bit value. Append it to the bits in n. */
2072 if ((++n_idx
) == 4) {
2073 /* We've accumulated 24 bits in n. Flush them. */
2075 *dest
++ = (n
>>8) & 0xff;
2076 *dest
++ = (n
) & 0xff;
2083 /* If we have leftover bits, we need to cope. */
2087 /* No leftover bits. We win. */
2090 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2093 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2097 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2102 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2103 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2105 return (int)(dest
-dest_orig
);
2112 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2113 * and newline characters, and store the nul-terminated result in the first
2114 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2116 digest_to_base64(char *d64
, const char *digest
)
2119 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
2120 buf
[BASE64_DIGEST_LEN
] = '\0';
2121 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2125 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2126 * trailing newline or = characters), decode it and store the result in the
2127 * first DIGEST_LEN bytes at <b>digest</b>. */
2129 digest_from_base64(char *digest
, const char *d64
)
2131 #ifdef USE_OPENSSL_BASE64
2132 char buf_in
[BASE64_DIGEST_LEN
+3];
2134 if (strlen(d64
) != BASE64_DIGEST_LEN
)
2136 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
2137 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
2138 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
2140 memcpy(digest
, buf
, DIGEST_LEN
);
2143 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2150 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2151 * that srclen*8 is a multiple of 5.
2154 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2156 unsigned int i
, bit
, v
, u
;
2157 size_t nbits
= srclen
* 8;
2159 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2160 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2161 tor_assert(destlen
< SIZE_T_CEILING
);
2163 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2164 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2165 v
= ((uint8_t)src
[bit
/8]) << 8;
2166 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2167 /* set u to the 5-bit value at the bit'th bit of src. */
2168 u
= (v
>> (11-(bit
%8))) & 0x1F;
2169 dest
[i
] = BASE32_CHARS
[u
];
2174 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2175 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2178 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2180 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2181 * it ever shows up in the profile. */
2182 unsigned int i
, j
, bit
;
2187 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2188 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2189 tor_assert(destlen
< SIZE_T_CEILING
);
2191 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2192 tmp
= tor_malloc_zero(srclen
);
2193 for (j
= 0; j
< srclen
; ++j
) {
2194 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2195 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2196 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2198 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2204 /* Assemble result byte-wise by applying five possible cases. */
2205 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2208 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2209 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2212 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2213 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2214 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2217 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2218 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2221 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2222 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2223 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2226 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2227 ((uint8_t)tmp
[(bit
/5)+1]);
2232 memset(tmp
, 0, srclen
);
2238 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2239 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2240 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2241 * are a salt; the 9th byte describes how much iteration to do.
2242 * Does not support <b>key_out_len</b> > DIGEST_LEN.
2245 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
2246 size_t secret_len
, const char *s2k_specifier
)
2248 crypto_digest_env_t
*d
;
2250 size_t count
, tmplen
;
2252 tor_assert(key_out_len
< SIZE_T_CEILING
);
2255 c
= s2k_specifier
[8];
2256 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
2259 tor_assert(key_out_len
<= DIGEST_LEN
);
2261 d
= crypto_new_digest_env();
2262 tmplen
= 8+secret_len
;
2263 tmp
= tor_malloc(tmplen
);
2264 memcpy(tmp
,s2k_specifier
,8);
2265 memcpy(tmp
+8,secret
,secret_len
);
2268 if (count
>= secret_len
) {
2269 crypto_digest_add_bytes(d
, tmp
, secret_len
);
2270 count
-= secret_len
;
2272 crypto_digest_add_bytes(d
, tmp
, count
);
2276 crypto_digest_get_digest(d
, key_out
, key_out_len
);
2277 memset(tmp
, 0, tmplen
);
2279 crypto_free_digest_env(d
);
2282 #ifdef TOR_IS_MULTITHREADED
2283 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2285 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
2289 if (!_openssl_mutexes
)
2290 /* This is not a really good fix for the
2291 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2294 if (mode
& CRYPTO_LOCK
)
2295 tor_mutex_acquire(_openssl_mutexes
[n
]);
2297 tor_mutex_release(_openssl_mutexes
[n
]);
2300 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2302 struct CRYPTO_dynlock_value
{
2306 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2307 * documentation in OpenSSL's docs for more info. */
2308 static struct CRYPTO_dynlock_value
*
2309 _openssl_dynlock_create_cb(const char *file
, int line
)
2311 struct CRYPTO_dynlock_value
*v
;
2314 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
2315 v
->lock
= tor_mutex_new();
2319 /** OpenSSL callback function to acquire or release a lock: see
2320 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2322 _openssl_dynlock_lock_cb(int mode
, struct CRYPTO_dynlock_value
*v
,
2323 const char *file
, int line
)
2327 if (mode
& CRYPTO_LOCK
)
2328 tor_mutex_acquire(v
->lock
);
2330 tor_mutex_release(v
->lock
);
2333 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2334 * documentation in OpenSSL's docs for more info. */
2336 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value
*v
,
2337 const char *file
, int line
)
2341 tor_mutex_free(v
->lock
);
2345 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2348 setup_openssl_threading(void)
2351 int n
= CRYPTO_num_locks();
2352 _n_openssl_mutexes
= n
;
2353 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
2354 for (i
=0; i
< n
; ++i
)
2355 _openssl_mutexes
[i
] = tor_mutex_new();
2356 CRYPTO_set_locking_callback(_openssl_locking_cb
);
2357 CRYPTO_set_id_callback(tor_get_thread_id
);
2358 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb
);
2359 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb
);
2360 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb
);
2365 setup_openssl_threading(void)