1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
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.
721 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
722 * at least the length of the modulus of <b>env</b>.
725 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
726 const char *from
, size_t fromlen
, int padding
)
732 tor_assert(fromlen
<INT_MAX
);
733 tor_assert(tolen
>= crypto_pk_keysize(env
));
735 r
= RSA_public_encrypt((int)fromlen
,
736 (unsigned char*)from
, (unsigned char*)to
,
737 env
->key
, crypto_get_rsa_padding(padding
));
739 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
745 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
746 * in <b>env</b>, using the padding method <b>padding</b>. On success,
747 * write the result to <b>to</b>, and return the number of bytes
748 * written. On failure, return -1.
750 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
751 * at least the length of the modulus of <b>env</b>.
754 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
756 const char *from
, size_t fromlen
,
757 int padding
, int warnOnFailure
)
763 tor_assert(env
->key
);
764 tor_assert(fromlen
<INT_MAX
);
765 tor_assert(tolen
>= crypto_pk_keysize(env
));
767 /* Not a private key */
770 r
= RSA_private_decrypt((int)fromlen
,
771 (unsigned char*)from
, (unsigned char*)to
,
772 env
->key
, crypto_get_rsa_padding(padding
));
775 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
776 "performing RSA decryption");
782 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
783 * public key in <b>env</b>, using PKCS1 padding. On success, write the
784 * signed data to <b>to</b>, and return the number of bytes written.
785 * On failure, return -1.
787 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
788 * at least the length of the modulus of <b>env</b>.
791 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
793 const char *from
, size_t fromlen
)
799 tor_assert(fromlen
< INT_MAX
);
800 tor_assert(tolen
>= crypto_pk_keysize(env
));
801 r
= RSA_public_decrypt((int)fromlen
,
802 (unsigned char*)from
, (unsigned char*)to
,
803 env
->key
, RSA_PKCS1_PADDING
);
806 crypto_log_errors(LOG_WARN
, "checking RSA signature");
812 /** Check a siglen-byte long signature at <b>sig</b> against
813 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
814 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
815 * SHA1(data). Else return -1.
818 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
819 size_t datalen
, const char *sig
, size_t siglen
)
821 char digest
[DIGEST_LEN
];
829 tor_assert(datalen
< SIZE_T_CEILING
);
830 tor_assert(siglen
< SIZE_T_CEILING
);
832 if (crypto_digest(digest
,data
,datalen
)<0) {
833 log_warn(LD_BUG
, "couldn't compute digest");
836 buflen
= crypto_pk_keysize(env
)+1;
837 buf
= tor_malloc(buflen
);
838 r
= crypto_pk_public_checksig(env
,buf
,buflen
,sig
,siglen
);
839 if (r
!= DIGEST_LEN
) {
840 log_warn(LD_CRYPTO
, "Invalid signature");
844 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
845 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
854 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
855 * <b>env</b>, using PKCS1 padding. On success, write the signature to
856 * <b>to</b>, and return the number of bytes written. On failure, return
859 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
860 * at least the length of the modulus of <b>env</b>.
863 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
864 const char *from
, size_t fromlen
)
870 tor_assert(fromlen
< INT_MAX
);
871 tor_assert(tolen
>= crypto_pk_keysize(env
));
873 /* Not a private key */
876 r
= RSA_private_encrypt((int)fromlen
,
877 (unsigned char*)from
, (unsigned char*)to
,
878 env
->key
, RSA_PKCS1_PADDING
);
880 crypto_log_errors(LOG_WARN
, "generating RSA signature");
886 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
887 * <b>from</b>; sign the data with the private key in <b>env</b>, and
888 * store it in <b>to</b>. Return the number of bytes written on
889 * success, and -1 on failure.
891 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
892 * at least the length of the modulus of <b>env</b>.
895 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
896 const char *from
, size_t fromlen
)
899 char digest
[DIGEST_LEN
];
900 if (crypto_digest(digest
,from
,fromlen
)<0)
902 r
= crypto_pk_private_sign(env
,to
,tolen
,digest
,DIGEST_LEN
);
903 memset(digest
, 0, sizeof(digest
));
907 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
908 * bytes of data from <b>from</b>, with padding type 'padding',
909 * storing the results on <b>to</b>.
911 * If no padding is used, the public key must be at least as large as
914 * Returns the number of bytes written on success, -1 on failure.
916 * The encrypted data consists of:
917 * - The source data, padded and encrypted with the public key, if the
918 * padded source data is no longer than the public key, and <b>force</b>
920 * - The beginning of the source data prefixed with a 16-byte symmetric key,
921 * padded and encrypted with the public key; followed by the rest of
922 * the source data encrypted in AES-CTR mode with the symmetric key.
925 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
926 char *to
, size_t tolen
,
929 int padding
, int force
)
931 int overhead
, outlen
, r
;
932 size_t pkeylen
, symlen
;
933 crypto_cipher_env_t
*cipher
= NULL
;
939 tor_assert(fromlen
< SIZE_T_CEILING
);
941 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
942 pkeylen
= crypto_pk_keysize(env
);
944 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
947 if (!force
&& fromlen
+overhead
<= pkeylen
) {
948 /* It all fits in a single encrypt. */
949 return crypto_pk_public_encrypt(env
,to
,
951 from
,fromlen
,padding
);
953 tor_assert(tolen
>= fromlen
+ overhead
+ CIPHER_KEY_LEN
);
954 tor_assert(tolen
>= pkeylen
);
956 cipher
= crypto_new_cipher_env();
957 if (!cipher
) return -1;
958 if (crypto_cipher_generate_key(cipher
)<0)
960 /* You can't just run around RSA-encrypting any bitstream: if it's
961 * greater than the RSA key, then OpenSSL will happily encrypt, and
962 * later decrypt to the wrong value. So we set the first bit of
963 * 'cipher->key' to 0 if we aren't padding. This means that our
964 * symmetric key is really only 127 bits.
966 if (padding
== PK_NO_PADDING
)
967 cipher
->key
[0] &= 0x7f;
968 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
970 buf
= tor_malloc(pkeylen
+1);
971 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
972 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
974 /* Length of symmetrically encrypted data. */
975 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
977 outlen
= crypto_pk_public_encrypt(env
,to
,tolen
,buf
,pkeylen
-overhead
,padding
);
978 if (outlen
!=(int)pkeylen
) {
981 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
982 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
985 memset(buf
, 0, pkeylen
);
987 crypto_free_cipher_env(cipher
);
988 tor_assert(outlen
+symlen
< INT_MAX
);
989 return (int)(outlen
+ symlen
);
992 memset(buf
, 0, pkeylen
);
995 if (cipher
) crypto_free_cipher_env(cipher
);
999 /** Invert crypto_pk_public_hybrid_encrypt. */
1001 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
1006 int padding
, int warnOnFailure
)
1010 crypto_cipher_env_t
*cipher
= NULL
;
1013 tor_assert(fromlen
< SIZE_T_CEILING
);
1014 pkeylen
= crypto_pk_keysize(env
);
1016 if (fromlen
<= pkeylen
) {
1017 return crypto_pk_private_decrypt(env
,to
,tolen
,from
,fromlen
,padding
,
1021 buf
= tor_malloc(pkeylen
+1);
1022 outlen
= crypto_pk_private_decrypt(env
,buf
,pkeylen
+1,from
,pkeylen
,padding
,
1025 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
1026 "Error decrypting public-key data");
1029 if (outlen
< CIPHER_KEY_LEN
) {
1030 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1031 "No room for a symmetric key");
1034 cipher
= crypto_create_init_cipher(buf
, 0);
1038 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1039 outlen
-= CIPHER_KEY_LEN
;
1040 tor_assert(tolen
- outlen
>= fromlen
- pkeylen
);
1041 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1044 memset(buf
,0,pkeylen
);
1046 crypto_free_cipher_env(cipher
);
1047 tor_assert(outlen
+ fromlen
< INT_MAX
);
1048 return (int)(outlen
+ (fromlen
-pkeylen
));
1050 memset(buf
,0,pkeylen
);
1052 if (cipher
) crypto_free_cipher_env(cipher
);
1056 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1057 * Return -1 on error, or the number of characters used on success.
1060 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, size_t dest_len
)
1063 unsigned char *buf
, *cp
;
1064 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1065 if (len
< 0 || (size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
)
1067 cp
= buf
= tor_malloc(len
+1);
1068 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1070 crypto_log_errors(LOG_WARN
,"encoding public key");
1074 /* We don't encode directly into 'dest', because that would be illegal
1075 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1077 memcpy(dest
,buf
,len
);
1082 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1083 * success and NULL on failure.
1086 crypto_pk_asn1_decode(const char *str
, size_t len
)
1090 /* This ifdef suppresses a type warning. Take out the first case once
1091 * everybody is using OpenSSL 0.9.7 or later.
1093 const unsigned char *cp
;
1094 cp
= buf
= tor_malloc(len
);
1095 memcpy(buf
,str
,len
);
1096 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1099 crypto_log_errors(LOG_WARN
,"decoding public key");
1102 return _crypto_new_pk_env_rsa(rsa
);
1105 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1106 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1107 * Return 0 on success, -1 on failure.
1110 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1112 unsigned char *buf
, *bufp
;
1115 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1118 buf
= bufp
= tor_malloc(len
+1);
1119 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1121 crypto_log_errors(LOG_WARN
,"encoding public key");
1125 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1133 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1134 * every four spaces. */
1136 add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1139 char *end
= out
+outlen
;
1140 tor_assert(outlen
< SIZE_T_CEILING
);
1142 while (*in
&& out
<end
) {
1144 if (++n
== 4 && *in
&& out
<end
) {
1149 tor_assert(out
<end
);
1153 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1154 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1155 * space). Return 0 on success, -1 on failure.
1157 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1158 * of the public key, converted to hexadecimal, in upper case, with a
1159 * space after every four digits.
1161 * If <b>add_space</b> is false, omit the spaces.
1164 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1166 char digest
[DIGEST_LEN
];
1167 char hexdigest
[HEX_DIGEST_LEN
+1];
1168 if (crypto_pk_get_digest(pk
, digest
)) {
1171 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1173 add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1175 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1180 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1183 crypto_pk_check_fingerprint_syntax(const char *s
)
1186 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1188 if (!TOR_ISSPACE(s
[i
])) return 0;
1190 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1193 if (s
[FINGERPRINT_LEN
]) return 0;
1197 /* symmetric crypto */
1199 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1200 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1203 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1207 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1210 /** Set the symmetric key for the cipher in <b>env</b> to the first
1211 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1212 * Return 0 on success, -1 on failure.
1215 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1223 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1227 /** Generate an initialization vector for our AES-CTR cipher; store it
1228 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1230 crypto_cipher_generate_iv(char *iv_out
)
1232 crypto_rand(iv_out
, CIPHER_IV_LEN
);
1235 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1236 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1239 crypto_cipher_set_iv(crypto_cipher_env_t
*env
, const char *iv
)
1243 aes_set_iv(env
->cipher
, iv
);
1247 /** Return a pointer to the key set for the cipher in <b>env</b>.
1250 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1255 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1256 * success, -1 on failure.
1259 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1263 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1267 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1268 * success, -1 on failure.
1271 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1275 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1279 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1280 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1281 * On failure, return -1.
1284 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1285 const char *from
, size_t fromlen
)
1288 tor_assert(env
->cipher
);
1290 tor_assert(fromlen
);
1292 tor_assert(fromlen
< SIZE_T_CEILING
);
1294 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1298 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1299 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1300 * On failure, return -1.
1303 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1304 const char *from
, size_t fromlen
)
1309 tor_assert(fromlen
< SIZE_T_CEILING
);
1311 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1315 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1316 * on success, return 0. On failure, return -1.
1319 crypto_cipher_crypt_inplace(crypto_cipher_env_t
*env
, char *buf
, size_t len
)
1321 tor_assert(len
< SIZE_T_CEILING
);
1322 aes_crypt_inplace(env
->cipher
, buf
, len
);
1326 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1327 * <b>cipher</b> to the buffer in <b>to</b> of length
1328 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1329 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1330 * number of bytes written, on failure, return -1.
1332 * This function adjusts the current position of the counter in <b>cipher</b>
1333 * to immediately after the encrypted data.
1336 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t
*cipher
,
1337 char *to
, size_t tolen
,
1338 const char *from
, size_t fromlen
)
1343 tor_assert(fromlen
< INT_MAX
);
1347 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1350 crypto_cipher_generate_iv(to
);
1351 if (crypto_cipher_set_iv(cipher
, to
)<0)
1353 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1354 return (int)(fromlen
+ CIPHER_IV_LEN
);
1357 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1358 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1359 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1360 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1361 * number of bytes written, on failure, return -1.
1363 * This function adjusts the current position of the counter in <b>cipher</b>
1364 * to immediately after the decrypted data.
1367 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t
*cipher
,
1368 char *to
, size_t tolen
,
1369 const char *from
, size_t fromlen
)
1374 tor_assert(fromlen
< INT_MAX
);
1376 if (fromlen
<= CIPHER_IV_LEN
)
1378 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1381 if (crypto_cipher_set_iv(cipher
, from
)<0)
1383 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1384 return (int)(fromlen
- CIPHER_IV_LEN
);
1389 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1390 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1391 * Return 0 on success, -1 on failure.
1394 crypto_digest(char *digest
, const char *m
, size_t len
)
1398 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1401 /** Intermediate information about the digest of a stream of data. */
1402 struct crypto_digest_env_t
{
1406 /** Allocate and return a new digest object.
1408 crypto_digest_env_t
*
1409 crypto_new_digest_env(void)
1411 crypto_digest_env_t
*r
;
1412 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1417 /** Deallocate a digest object.
1420 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1422 memset(digest
, 0, sizeof(crypto_digest_env_t
));
1426 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1429 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1434 /* Using the SHA1_*() calls directly means we don't support doing
1435 * SHA1 in hardware. But so far the delay of getting the question
1436 * to the hardware, and hearing the answer, is likely higher than
1437 * just doing it ourselves. Hashes are fast.
1439 SHA1_Update(&digest
->d
, (void*)data
, len
);
1442 /** Compute the hash of the data that has been passed to the digest
1443 * object; write the first out_len bytes of the result to <b>out</b>.
1444 * <b>out_len</b> must be \<= DIGEST_LEN.
1447 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1448 char *out
, size_t out_len
)
1450 unsigned char r
[DIGEST_LEN
];
1454 tor_assert(out_len
<= DIGEST_LEN
);
1455 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1456 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1457 SHA1_Final(r
, &tmpctx
);
1458 memcpy(out
, r
, out_len
);
1459 memset(r
, 0, sizeof(r
));
1462 /** Allocate and return a new digest object with the same state as
1465 crypto_digest_env_t
*
1466 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1468 crypto_digest_env_t
*r
;
1470 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1471 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1475 /** Replace the state of the digest object <b>into</b> with the state
1476 * of the digest object <b>from</b>.
1479 crypto_digest_assign(crypto_digest_env_t
*into
,
1480 const crypto_digest_env_t
*from
)
1484 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1487 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1488 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1489 * in <b>hmac_out</b>.
1492 crypto_hmac_sha1(char *hmac_out
,
1493 const char *key
, size_t key_len
,
1494 const char *msg
, size_t msg_len
)
1496 tor_assert(key_len
< INT_MAX
);
1497 tor_assert(msg_len
< INT_MAX
);
1498 HMAC(EVP_sha1(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1499 (unsigned char*)hmac_out
, NULL
);
1504 /** Shared P parameter for our DH key exchanged. */
1505 static BIGNUM
*dh_param_p
= NULL
;
1506 /** Shared G parameter for our DH key exchanges. */
1507 static BIGNUM
*dh_param_g
= NULL
;
1509 /** Initialize dh_param_p and dh_param_g if they are not already
1516 if (dh_param_p
&& dh_param_g
)
1524 /* This is from rfc2409, section 6.2. It's a safe prime, and
1525 supposedly it equals:
1526 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1529 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1530 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1531 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1532 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1533 "49286651ECE65381FFFFFFFFFFFFFFFF");
1536 r
= BN_set_word(g
, 2);
1542 #define DH_PRIVATE_KEY_BITS 320
1544 /** Allocate and return a new DH object for a key exchange.
1549 crypto_dh_env_t
*res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1554 if (!(res
->dh
= DH_new()))
1557 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1560 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1563 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1567 crypto_log_errors(LOG_WARN
, "creating DH object");
1568 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1573 /** Return the length of the DH key in <b>dh</b>, in bytes.
1576 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1579 return DH_size(dh
->dh
);
1582 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1583 * success, -1 on failure.
1586 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1589 if (!DH_generate_key(dh
->dh
)) {
1590 crypto_log_errors(LOG_WARN
, "generating DH key");
1593 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1594 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1595 "the-universe chances really do happen. Trying again.");
1596 /* Free and clear the keys, so OpenSSL will actually try again. */
1597 BN_free(dh
->dh
->pub_key
);
1598 BN_free(dh
->dh
->priv_key
);
1599 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1605 /** Generate g^x as necessary, and write the g^x for the key exchange
1606 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1607 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1610 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1614 if (!dh
->dh
->pub_key
) {
1615 if (crypto_dh_generate_public(dh
)<0)
1619 tor_assert(dh
->dh
->pub_key
);
1620 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1621 tor_assert(bytes
>= 0);
1622 if (pubkey_len
< (size_t)bytes
) {
1624 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1625 (int) pubkey_len
, bytes
);
1629 memset(pubkey
, 0, pubkey_len
);
1630 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1635 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1636 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1637 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1640 tor_check_dh_key(BIGNUM
*bn
)
1650 if (BN_cmp(bn
,x
)<=0) {
1651 log_warn(LD_CRYPTO
, "DH key must be at least 2.");
1654 BN_copy(x
,dh_param_p
);
1656 if (BN_cmp(bn
,x
)>=0) {
1657 log_warn(LD_CRYPTO
, "DH key must be at most p-2.");
1665 log_warn(LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1671 #define MIN(a,b) ((a)<(b)?(a):(b))
1672 /** Given a DH key exchange object, and our peer's value of g^y (as a
1673 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1674 * <b>secret_bytes_out</b> bytes of shared key material and write them
1675 * to <b>secret_out</b>. Return the number of bytes generated on success,
1678 * (We generate key material by computing
1679 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1680 * where || is concatenation.)
1683 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1684 const char *pubkey
, size_t pubkey_len
,
1685 char *secret_out
, size_t secret_bytes_out
)
1687 char *secret_tmp
= NULL
;
1688 BIGNUM
*pubkey_bn
= NULL
;
1689 size_t secret_len
=0;
1692 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1693 tor_assert(pubkey_len
< INT_MAX
);
1695 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
1696 (int)pubkey_len
, NULL
)))
1698 if (tor_check_dh_key(pubkey_bn
)<0) {
1699 /* Check for invalid public keys. */
1700 log_warn(LD_CRYPTO
,"Rejected invalid g^x");
1703 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
));
1704 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1706 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
1709 secret_len
= result
;
1710 if (crypto_expand_key_material(secret_tmp
, secret_len
,
1711 secret_out
, secret_bytes_out
)<0)
1713 secret_len
= secret_bytes_out
;
1719 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1722 tor_free(secret_tmp
);
1729 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1730 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1731 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1732 * H(K | [00]) | H(K | [01]) | ....
1734 * Return 0 on success, -1 on failure.
1737 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
1738 char *key_out
, size_t key_out_len
)
1741 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
1742 char digest
[DIGEST_LEN
];
1744 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1745 tor_assert(key_out_len
<= DIGEST_LEN
*256);
1747 memcpy(tmp
, key_in
, key_in_len
);
1748 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
1749 ++i
, cp
+= DIGEST_LEN
) {
1750 tmp
[key_in_len
] = i
;
1751 if (crypto_digest(digest
, tmp
, key_in_len
+1))
1753 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
1755 memset(tmp
, 0, key_in_len
+1);
1757 memset(digest
, 0, sizeof(digest
));
1761 memset(tmp
, 0, key_in_len
+1);
1763 memset(digest
, 0, sizeof(digest
));
1767 /** Free a DH key exchange object.
1770 crypto_dh_free(crypto_dh_env_t
*dh
)
1778 /* random numbers */
1780 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1781 * work for us too. */
1782 #define ADD_ENTROPY 32
1784 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1786 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1788 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1789 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1790 * that fd without checking whether it fit in the fd_set. Thus, if the
1791 * system has not just been started up, it is unsafe to call */
1792 #define RAND_POLL_IS_SAFE \
1793 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1794 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1795 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1797 /** Seed OpenSSL's random number generator with bytes from the operating
1798 * system. <b>startup</b> should be true iff we have just started Tor and
1799 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1802 crypto_seed_rng(int startup
)
1804 char buf
[ADD_ENTROPY
];
1805 int rand_poll_status
= 0;
1807 /* local variables */
1809 static int provider_set
= 0;
1810 static HCRYPTPROV provider
;
1812 static const char *filenames
[] = {
1813 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1820 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1821 * entropy than we do. We'll try calling that, *and* calling our own entropy
1822 * functions. If one succeeds, we'll accept the RNG as seeded. */
1823 if (startup
|| RAND_POLL_IS_SAFE
) {
1824 rand_poll_status
= RAND_poll();
1825 if (rand_poll_status
== 0)
1826 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
1831 if (!provider_set
) {
1832 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1833 CRYPT_VERIFYCONTEXT
)) {
1834 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
1835 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1836 return rand_poll_status
? 0 : -1;
1841 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1842 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1843 return rand_poll_status
? 0 : -1;
1845 RAND_seed(buf
, sizeof(buf
));
1846 memset(buf
, 0, sizeof(buf
));
1849 for (i
= 0; filenames
[i
]; ++i
) {
1850 fd
= open(filenames
[i
], O_RDONLY
, 0);
1852 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1853 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1855 if (n
!= sizeof(buf
)) {
1857 "Error reading from entropy source (read only %lu bytes).",
1861 RAND_seed(buf
, (int)sizeof(buf
));
1862 memset(buf
, 0, sizeof(buf
));
1866 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1867 return rand_poll_status
? 0 : -1;
1871 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1872 * success, -1 on failure.
1875 crypto_rand(char *to
, size_t n
)
1878 tor_assert(n
< INT_MAX
);
1880 r
= RAND_bytes((unsigned char*)to
, (int)n
);
1882 crypto_log_errors(LOG_WARN
, "generating random data");
1883 return (r
== 1) ? 0 : -1;
1886 /** Return a pseudorandom integer, chosen uniformly from the values
1887 * between 0 and <b>max</b>-1. */
1889 crypto_rand_int(unsigned int max
)
1892 unsigned int cutoff
;
1893 tor_assert(max
< UINT_MAX
);
1894 tor_assert(max
> 0); /* don't div by 0 */
1896 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1897 * distribution with clipping at the upper end of unsigned int's
1900 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1902 crypto_rand((char*)&val
, sizeof(val
));
1908 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1909 * between 0 and <b>max</b>-1. */
1911 crypto_rand_uint64(uint64_t max
)
1915 tor_assert(max
< UINT64_MAX
);
1916 tor_assert(max
> 0); /* don't div by 0 */
1918 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1919 * distribution with clipping at the upper end of unsigned int's
1922 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
1924 crypto_rand((char*)&val
, sizeof(val
));
1930 /** Generate and return a new random hostname starting with <b>prefix</b>,
1931 * ending with <b>suffix</b>, and containing no less than
1932 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1933 * characters between. */
1935 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
1938 char *result
, *rand_bytes
;
1939 int randlen
, rand_bytes_len
;
1940 size_t resultlen
, prefixlen
;
1942 tor_assert(max_rand_len
>= min_rand_len
);
1943 randlen
= min_rand_len
+ crypto_rand_int(max_rand_len
- min_rand_len
+ 1);
1944 prefixlen
= strlen(prefix
);
1945 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
1947 rand_bytes_len
= ((randlen
*5)+7)/8;
1948 if (rand_bytes_len
% 5)
1949 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
1950 rand_bytes
= tor_malloc(rand_bytes_len
);
1951 crypto_rand(rand_bytes
, rand_bytes_len
);
1953 result
= tor_malloc(resultlen
);
1954 memcpy(result
, prefix
, prefixlen
);
1955 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
1956 rand_bytes
, rand_bytes_len
);
1957 tor_free(rand_bytes
);
1958 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
1963 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1966 smartlist_choose(const smartlist_t
*sl
)
1968 int len
= smartlist_len(sl
);
1970 return smartlist_get(sl
,crypto_rand_int(len
));
1971 return NULL
; /* no elements to choose from */
1974 /** Scramble the elements of <b>sl</b> into a random order. */
1976 smartlist_shuffle(smartlist_t
*sl
)
1979 /* From the end of the list to the front, choose at random from the
1980 positions we haven't looked at yet, and swap that position into the
1981 current position. Remember to give "no swap" the same probability as
1983 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
1984 int j
= crypto_rand_int(i
+1);
1985 smartlist_swap(sl
, i
, j
);
1989 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1990 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1991 * bytes. Return the number of bytes written on success; -1 if
1992 * destlen is too short, or other failure.
1995 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1997 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1998 * it ever shows up in the profile. */
2001 tor_assert(srclen
< INT_MAX
);
2003 /* 48 bytes of input -> 64 bytes of output plus newline.
2004 Plus one more byte, in case I'm wrong.
2006 if (destlen
< ((srclen
/48)+1)*66)
2008 if (destlen
> SIZE_T_CEILING
)
2011 EVP_EncodeInit(&ctx
);
2012 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2013 (unsigned char*)src
, (int)srclen
);
2014 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
2022 /** Internal table mapping byte values to what they represent in base64.
2023 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2024 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2026 static const uint8_t base64_decode_table
[256] = {
2027 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
2028 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2029 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
2030 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
2031 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2032 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
2033 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2034 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
2035 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2036 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2037 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2038 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2039 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2040 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2041 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2042 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2045 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2046 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2047 * bytes. Return the number of bytes written on success; -1 if
2048 * destlen is too short, or other failure.
2050 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2051 * spaces or padding.
2053 * NOTE 2: This implementation does not check for the correct number of
2054 * padding "=" characters at the end of the string, and does not check
2055 * for internal padding characters.
2058 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2060 #ifdef USE_OPENSSL_BASE64
2063 /* 64 bytes of input -> *up to* 48 bytes of output.
2064 Plus one more byte, in case I'm wrong.
2066 if (destlen
< ((srclen
/64)+1)*49)
2068 if (destlen
> SIZE_T_CEILING
)
2071 EVP_DecodeInit(&ctx
);
2072 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2073 (unsigned char*)src
, srclen
);
2074 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
2078 const char *eos
= src
+srclen
;
2081 char *dest_orig
= dest
;
2083 /* Max number of bits == srclen*6.
2084 * Number of bytes required to hold all bits == (srclen*6)/8.
2085 * Yes, we want to round down: anything that hangs over the end of a
2086 * byte is padding. */
2087 if (destlen
< (srclen
*3)/4)
2089 if (destlen
> SIZE_T_CEILING
)
2092 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2093 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2094 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2096 for ( ; src
< eos
; ++src
) {
2097 unsigned char c
= (unsigned char) *src
;
2098 uint8_t v
= base64_decode_table
[c
];
2101 /* This character isn't allowed in base64. */
2104 /* This character is whitespace, and has no effect. */
2107 /* We've hit an = character: the data is over. */
2110 /* We have an actual 6-bit value. Append it to the bits in n. */
2112 if ((++n_idx
) == 4) {
2113 /* We've accumulated 24 bits in n. Flush them. */
2115 *dest
++ = (n
>>8) & 0xff;
2116 *dest
++ = (n
) & 0xff;
2123 /* If we have leftover bits, we need to cope. */
2127 /* No leftover bits. We win. */
2130 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2133 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2137 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2142 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2143 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2145 return (int)(dest
-dest_orig
);
2152 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2153 * and newline characters, and store the nul-terminated result in the first
2154 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2156 digest_to_base64(char *d64
, const char *digest
)
2159 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
2160 buf
[BASE64_DIGEST_LEN
] = '\0';
2161 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2165 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2166 * trailing newline or = characters), decode it and store the result in the
2167 * first DIGEST_LEN bytes at <b>digest</b>. */
2169 digest_from_base64(char *digest
, const char *d64
)
2171 #ifdef USE_OPENSSL_BASE64
2172 char buf_in
[BASE64_DIGEST_LEN
+3];
2174 if (strlen(d64
) != BASE64_DIGEST_LEN
)
2176 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
2177 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
2178 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
2180 memcpy(digest
, buf
, DIGEST_LEN
);
2183 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2190 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2191 * that srclen*8 is a multiple of 5.
2194 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2196 unsigned int i
, bit
, v
, u
;
2197 size_t nbits
= srclen
* 8;
2199 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2200 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2201 tor_assert(destlen
< SIZE_T_CEILING
);
2203 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2204 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2205 v
= ((uint8_t)src
[bit
/8]) << 8;
2206 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2207 /* set u to the 5-bit value at the bit'th bit of src. */
2208 u
= (v
>> (11-(bit
%8))) & 0x1F;
2209 dest
[i
] = BASE32_CHARS
[u
];
2214 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2215 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2218 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2220 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2221 * it ever shows up in the profile. */
2222 unsigned int i
, j
, bit
;
2227 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2228 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2229 tor_assert(destlen
< SIZE_T_CEILING
);
2231 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2232 tmp
= tor_malloc_zero(srclen
);
2233 for (j
= 0; j
< srclen
; ++j
) {
2234 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2235 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2236 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2238 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2244 /* Assemble result byte-wise by applying five possible cases. */
2245 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2248 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2249 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2252 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2253 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2254 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2257 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2258 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2261 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2262 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2263 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2266 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2267 ((uint8_t)tmp
[(bit
/5)+1]);
2272 memset(tmp
, 0, srclen
);
2278 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2279 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2280 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2281 * are a salt; the 9th byte describes how much iteration to do.
2282 * Does not support <b>key_out_len</b> > DIGEST_LEN.
2285 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
2286 size_t secret_len
, const char *s2k_specifier
)
2288 crypto_digest_env_t
*d
;
2290 size_t count
, tmplen
;
2292 tor_assert(key_out_len
< SIZE_T_CEILING
);
2295 c
= s2k_specifier
[8];
2296 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
2299 tor_assert(key_out_len
<= DIGEST_LEN
);
2301 d
= crypto_new_digest_env();
2302 tmplen
= 8+secret_len
;
2303 tmp
= tor_malloc(tmplen
);
2304 memcpy(tmp
,s2k_specifier
,8);
2305 memcpy(tmp
+8,secret
,secret_len
);
2308 if (count
>= secret_len
) {
2309 crypto_digest_add_bytes(d
, tmp
, secret_len
);
2310 count
-= secret_len
;
2312 crypto_digest_add_bytes(d
, tmp
, count
);
2316 crypto_digest_get_digest(d
, key_out
, key_out_len
);
2317 memset(tmp
, 0, tmplen
);
2319 crypto_free_digest_env(d
);
2322 #ifdef TOR_IS_MULTITHREADED
2323 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2325 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
2329 if (!_openssl_mutexes
)
2330 /* This is not a really good fix for the
2331 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2334 if (mode
& CRYPTO_LOCK
)
2335 tor_mutex_acquire(_openssl_mutexes
[n
]);
2337 tor_mutex_release(_openssl_mutexes
[n
]);
2340 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2342 struct CRYPTO_dynlock_value
{
2346 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2347 * documentation in OpenSSL's docs for more info. */
2348 static struct CRYPTO_dynlock_value
*
2349 _openssl_dynlock_create_cb(const char *file
, int line
)
2351 struct CRYPTO_dynlock_value
*v
;
2354 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
2355 v
->lock
= tor_mutex_new();
2359 /** OpenSSL callback function to acquire or release a lock: see
2360 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2362 _openssl_dynlock_lock_cb(int mode
, struct CRYPTO_dynlock_value
*v
,
2363 const char *file
, int line
)
2367 if (mode
& CRYPTO_LOCK
)
2368 tor_mutex_acquire(v
->lock
);
2370 tor_mutex_release(v
->lock
);
2373 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2374 * documentation in OpenSSL's docs for more info. */
2376 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value
*v
,
2377 const char *file
, int line
)
2381 tor_mutex_free(v
->lock
);
2385 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2388 setup_openssl_threading(void)
2391 int n
= CRYPTO_num_locks();
2392 _n_openssl_mutexes
= n
;
2393 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
2394 for (i
=0; i
< n
; ++i
)
2395 _openssl_mutexes
[i
] = tor_mutex_new();
2396 CRYPTO_set_locking_callback(_openssl_locking_cb
);
2397 CRYPTO_set_id_callback(tor_get_thread_id
);
2398 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb
);
2399 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb
);
2400 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb
);
2405 setup_openssl_threading(void)