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-2015, 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.
17 #define _WIN32_WINNT 0x0501
19 #define WIN32_LEAN_AND_MEAN
22 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
23 * use either definition. */
27 #include <openssl/err.h>
28 #include <openssl/rsa.h>
29 #include <openssl/pem.h>
30 #include <openssl/evp.h>
31 #include <openssl/engine.h>
32 #include <openssl/rand.h>
33 #include <openssl/opensslv.h>
34 #include <openssl/bn.h>
35 #include <openssl/dh.h>
36 #include <openssl/conf.h>
37 #include <openssl/hmac.h>
48 #ifdef HAVE_SYS_FCNTL_H
49 #include <sys/fcntl.h>
52 #define CRYPTO_PRIVATE
57 #include "container.h"
61 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
62 #error "We require OpenSSL >= 0.9.8"
66 /* Android's OpenSSL seems to have removed all of its Engine support. */
67 #define DISABLE_ENGINES
70 /** Longest recognized */
71 #define MAX_DNS_LABEL_SIZE 63
73 /** Macro: is k a valid RSA public or private key? */
74 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
75 /** Macro: is k a valid RSA private key? */
76 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
78 /** A number of preallocated mutexes for use by OpenSSL. */
79 static tor_mutex_t
**openssl_mutexes_
= NULL
;
80 /** How many mutexes have we allocated for use by OpenSSL? */
81 static int n_openssl_mutexes_
= 0;
83 /** A public key, or a public/private key-pair. */
86 int refs
; /**< reference count, so we don't have to copy keys */
87 RSA
*key
; /**< The key itself */
90 /** Key and stream information for a stream cipher. */
91 struct crypto_cipher_t
93 char key
[CIPHER_KEY_LEN
]; /**< The raw key. */
94 char iv
[CIPHER_IV_LEN
]; /**< The initial IV. */
95 aes_cnt_cipher_t
*cipher
; /**< The key in format usable for counter-mode AES
99 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
100 * while we're waiting for the second.*/
102 DH
*dh
; /**< The openssl DH object */
105 static int setup_openssl_threading(void);
106 static int tor_check_dh_key(int severity
, BIGNUM
*bn
);
108 /** Return the number of bytes added by padding method <b>padding</b>.
111 crypto_get_rsa_padding_overhead(int padding
)
115 case RSA_PKCS1_OAEP_PADDING
: return PKCS1_OAEP_PADDING_OVERHEAD
;
116 default: tor_assert(0); return -1;
120 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
123 crypto_get_rsa_padding(int padding
)
127 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
128 default: tor_assert(0); return -1;
132 /** Boolean: has OpenSSL's crypto been initialized? */
133 static int crypto_early_initialized_
= 0;
135 /** Boolean: has OpenSSL's crypto been initialized? */
136 static int crypto_global_initialized_
= 0;
138 /** Log all pending crypto errors at level <b>severity</b>. Use
139 * <b>doing</b> to describe our current activities.
142 crypto_log_errors(int severity
, const char *doing
)
145 const char *msg
, *lib
, *func
;
146 while ((err
= ERR_get_error()) != 0) {
147 msg
= (const char*)ERR_reason_error_string(err
);
148 lib
= (const char*)ERR_lib_error_string(err
);
149 func
= (const char*)ERR_func_error_string(err
);
150 if (!msg
) msg
= "(null)";
151 if (!lib
) lib
= "(null)";
152 if (!func
) func
= "(null)";
154 tor_log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
155 doing
, msg
, lib
, func
);
157 tor_log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)",
163 #ifndef DISABLE_ENGINES
164 /** Log any OpenSSL engines we're using at NOTICE. */
166 log_engine(const char *fn
, ENGINE
*e
)
169 const char *name
, *id
;
170 name
= ENGINE_get_name(e
);
171 id
= ENGINE_get_id(e
);
172 log_notice(LD_CRYPTO
, "Default OpenSSL engine for %s is %s [%s]",
173 fn
, name
?name
:"?", id
?id
:"?");
175 log_info(LD_CRYPTO
, "Using default implementation for %s", fn
);
180 #ifndef DISABLE_ENGINES
181 /** Try to load an engine in a shared library via fully qualified path.
184 try_load_engine(const char *path
, const char *engine
)
186 ENGINE
*e
= ENGINE_by_id("dynamic");
188 if (!ENGINE_ctrl_cmd_string(e
, "ID", engine
, 0) ||
189 !ENGINE_ctrl_cmd_string(e
, "DIR_LOAD", "2", 0) ||
190 !ENGINE_ctrl_cmd_string(e
, "DIR_ADD", path
, 0) ||
191 !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
200 /* Returns a trimmed and human-readable version of an openssl version string
201 * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
202 * May 2012' and this will parse them into a form similar to '1.0.0b' */
204 parse_openssl_version_str(const char *raw_version
)
206 const char *end_of_version
= NULL
;
207 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
209 if (!strcmpstart(raw_version
, "OpenSSL ")) {
210 raw_version
+= strlen("OpenSSL ");
211 end_of_version
= strchr(raw_version
, ' ');
215 return tor_strndup(raw_version
,
216 end_of_version
-raw_version
);
218 return tor_strdup(raw_version
);
221 static char *crypto_openssl_version_str
= NULL
;
222 /* Return a human-readable version of the run-time openssl version number. */
224 crypto_openssl_get_version_str(void)
226 if (crypto_openssl_version_str
== NULL
) {
227 const char *raw_version
= SSLeay_version(SSLEAY_VERSION
);
228 crypto_openssl_version_str
= parse_openssl_version_str(raw_version
);
230 return crypto_openssl_version_str
;
233 static char *crypto_openssl_header_version_str
= NULL
;
234 /* Return a human-readable version of the compile-time openssl version
237 crypto_openssl_get_header_version_str(void)
239 if (crypto_openssl_header_version_str
== NULL
) {
240 crypto_openssl_header_version_str
=
241 parse_openssl_version_str(OPENSSL_VERSION_TEXT
);
243 return crypto_openssl_header_version_str
;
246 /** Make sure that openssl is using its default PRNG. Return 1 if we had to
247 * adjust it; 0 otherwise. */
249 crypto_force_rand_ssleay(void)
251 if (RAND_get_rand_method() != RAND_SSLeay()) {
252 log_notice(LD_CRYPTO
, "It appears that one of our engines has provided "
253 "a replacement the OpenSSL RNG. Resetting it to the default "
255 RAND_set_rand_method(RAND_SSLeay());
261 /** Set up the siphash key if we haven't already done so. */
263 crypto_init_siphash_key(void)
265 static int have_seeded_siphash
= 0;
267 if (have_seeded_siphash
)
270 if (crypto_rand((char*) &key
, sizeof(key
)) < 0)
272 siphash_set_global_key(&key
);
273 have_seeded_siphash
= 1;
277 /** Initialize the crypto library. Return 0 on success, -1 on failure.
280 crypto_early_init(void)
282 if (!crypto_early_initialized_
) {
284 crypto_early_initialized_
= 1;
286 ERR_load_crypto_strings();
287 OpenSSL_add_all_algorithms();
289 setup_openssl_threading();
291 if (SSLeay() == OPENSSL_VERSION_NUMBER
&&
292 !strcmp(SSLeay_version(SSLEAY_VERSION
), OPENSSL_VERSION_TEXT
)) {
293 log_info(LD_CRYPTO
, "OpenSSL version matches version from headers "
294 "(%lx: %s).", SSLeay(), SSLeay_version(SSLEAY_VERSION
));
296 log_warn(LD_CRYPTO
, "OpenSSL version from headers does not match the "
297 "version we're running with. If you get weird crashes, that "
298 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
299 (unsigned long)OPENSSL_VERSION_NUMBER
, OPENSSL_VERSION_TEXT
,
300 SSLeay(), SSLeay_version(SSLEAY_VERSION
));
303 if (SSLeay() < OPENSSL_V_SERIES(1,0,0)) {
304 log_notice(LD_CRYPTO
,
305 "Your OpenSSL version seems to be %s. We recommend 1.0.0 "
307 crypto_openssl_get_version_str());
310 crypto_force_rand_ssleay();
312 if (crypto_seed_rng(1) < 0)
314 if (crypto_init_siphash_key() < 0)
320 /** Initialize the crypto library. Return 0 on success, -1 on failure.
323 crypto_global_init(int useAccel
, const char *accelName
, const char *accelDir
)
325 if (!crypto_global_initialized_
) {
328 crypto_global_initialized_
= 1;
331 #ifdef DISABLE_ENGINES
334 log_warn(LD_CRYPTO
, "No OpenSSL hardware acceleration support enabled.");
338 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
339 ENGINE_load_builtin_engines();
340 ENGINE_register_all_complete();
344 log_info(LD_CRYPTO
, "Trying to load dynamic OpenSSL engine \"%s\""
345 " via path \"%s\".", accelName
, accelDir
);
346 e
= try_load_engine(accelName
, accelDir
);
348 log_info(LD_CRYPTO
, "Initializing dynamic OpenSSL engine \"%s\""
349 " acceleration support.", accelName
);
350 e
= ENGINE_by_id(accelName
);
353 log_warn(LD_CRYPTO
, "Unable to load dynamic OpenSSL engine \"%s\".",
356 log_info(LD_CRYPTO
, "Loaded dynamic OpenSSL engine \"%s\".",
361 log_info(LD_CRYPTO
, "Loaded OpenSSL hardware acceleration engine,"
362 " setting default ciphers.");
363 ENGINE_set_default(e
, ENGINE_METHOD_ALL
);
365 /* Log, if available, the intersection of the set of algorithms
366 used by Tor and the set of algorithms available in the engine */
367 log_engine("RSA", ENGINE_get_default_RSA());
368 log_engine("DH", ENGINE_get_default_DH());
369 log_engine("ECDH", ENGINE_get_default_ECDH());
370 log_engine("ECDSA", ENGINE_get_default_ECDSA());
371 log_engine("RAND", ENGINE_get_default_RAND());
372 log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
373 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
374 log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc
));
375 log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
376 log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc
));
377 #ifdef NID_aes_128_ctr
378 log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr
));
380 #ifdef NID_aes_128_gcm
381 log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm
));
383 log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc
));
384 #ifdef NID_aes_256_gcm
385 log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm
));
390 log_info(LD_CRYPTO
, "NOT using OpenSSL engine support.");
393 if (crypto_force_rand_ssleay()) {
394 if (crypto_seed_rng(1) < 0)
398 evaluate_evp_for_aes(-1);
399 evaluate_ctr_for_aes();
404 /** Free crypto resources held by this thread. */
406 crypto_thread_cleanup(void)
411 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
413 crypto_new_pk_from_rsa_(RSA
*rsa
)
417 env
= tor_malloc(sizeof(crypto_pk_t
));
423 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
426 crypto_pk_get_rsa_(crypto_pk_t
*env
)
431 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
432 * private is set, include the private-key portion of the key. */
434 crypto_pk_get_evp_pkey_(crypto_pk_t
*env
, int private)
437 EVP_PKEY
*pkey
= NULL
;
438 tor_assert(env
->key
);
440 if (!(key
= RSAPrivateKey_dup(env
->key
)))
443 if (!(key
= RSAPublicKey_dup(env
->key
)))
446 if (!(pkey
= EVP_PKEY_new()))
448 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
459 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
462 crypto_dh_get_dh_(crypto_dh_t
*dh
)
467 /** Allocate and return storage for a public key. The key itself will not yet
477 return crypto_new_pk_from_rsa_(rsa
);
480 /** Release a reference to an asymmetric key; when all the references
481 * are released, free the key.
484 crypto_pk_free(crypto_pk_t
*env
)
491 tor_assert(env
->refs
== 0);
499 /** Allocate and return a new symmetric cipher using the provided key and iv.
500 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
501 * provide NULL in place of either one, it is generated at random.
504 crypto_cipher_new_with_iv(const char *key
, const char *iv
)
506 crypto_cipher_t
*env
;
508 env
= tor_malloc_zero(sizeof(crypto_cipher_t
));
511 crypto_rand(env
->key
, CIPHER_KEY_LEN
);
513 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
515 crypto_rand(env
->iv
, CIPHER_IV_LEN
);
517 memcpy(env
->iv
, iv
, CIPHER_IV_LEN
);
519 env
->cipher
= aes_new_cipher(env
->key
, env
->iv
);
524 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
527 crypto_cipher_new(const char *key
)
529 char zeroiv
[CIPHER_IV_LEN
];
530 memset(zeroiv
, 0, sizeof(zeroiv
));
531 return crypto_cipher_new_with_iv(key
, zeroiv
);
534 /** Free a symmetric cipher.
537 crypto_cipher_free(crypto_cipher_t
*env
)
542 tor_assert(env
->cipher
);
543 aes_cipher_free(env
->cipher
);
544 memwipe(env
, 0, sizeof(crypto_cipher_t
));
548 /* public key crypto */
550 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
551 * Return 0 on success, -1 on failure.
554 crypto_pk_generate_key_with_bits(crypto_pk_t
*env
, int bits
)
562 BIGNUM
*e
= BN_new();
566 if (! BN_set_word(e
, 65537))
571 if (RSA_generate_key_ex(r
, bits
, e
, NULL
) == -1)
584 crypto_log_errors(LOG_WARN
, "generating RSA key");
591 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
592 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
593 * the string is nul-terminated.
595 /* Used here, and used for testing. */
597 crypto_pk_read_private_key_from_string(crypto_pk_t
*env
,
598 const char *s
, ssize_t len
)
604 tor_assert(len
< INT_MAX
&& len
< SSIZE_T_CEILING
);
606 /* Create a read-only memory BIO, backed by the string 's' */
607 b
= BIO_new_mem_buf((char*)s
, (int)len
);
614 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
619 crypto_log_errors(LOG_WARN
, "Error parsing private key");
625 /** Read a PEM-encoded private key from the file named by
626 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
629 crypto_pk_read_private_key_from_filename(crypto_pk_t
*env
,
635 /* Read the file into a string. */
636 contents
= read_file_to_str(keyfile
, 0, NULL
);
638 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
642 /* Try to parse it. */
643 r
= crypto_pk_read_private_key_from_string(env
, contents
, -1);
644 memwipe(contents
, 0, strlen(contents
));
647 return -1; /* read_private_key_from_string already warned, so we don't.*/
649 /* Make sure it's valid. */
650 if (crypto_pk_check_key(env
) <= 0)
656 /** Helper function to implement crypto_pk_write_*_key_to_string. */
658 crypto_pk_write_key_to_string_impl(crypto_pk_t
*env
, char **dest
,
659 size_t *len
, int is_public
)
666 tor_assert(env
->key
);
669 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
673 /* Now you can treat b as if it were a file. Just use the
674 * PEM_*_bio_* functions instead of the non-bio variants.
677 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
679 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
682 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
687 BIO_get_mem_ptr(b
, &buf
);
688 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
691 *dest
= tor_malloc(buf
->length
+1);
692 memcpy(*dest
, buf
->data
, buf
->length
);
693 (*dest
)[buf
->length
] = 0; /* nul terminate it */
700 /** PEM-encode the public key portion of <b>env</b> and write it to a
701 * newly allocated string. On success, set *<b>dest</b> to the new
702 * string, *<b>len</b> to the string's length, and return 0. On
703 * failure, return -1.
706 crypto_pk_write_public_key_to_string(crypto_pk_t
*env
, char **dest
,
709 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
712 /** PEM-encode the private key portion of <b>env</b> and write it to a
713 * newly allocated string. On success, set *<b>dest</b> to the new
714 * string, *<b>len</b> to the string's length, and return 0. On
715 * failure, return -1.
718 crypto_pk_write_private_key_to_string(crypto_pk_t
*env
, char **dest
,
721 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
724 /** Read a PEM-encoded public key from the first <b>len</b> characters of
725 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
729 crypto_pk_read_public_key_from_string(crypto_pk_t
*env
, const char *src
,
736 tor_assert(len
<INT_MAX
);
738 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
742 BIO_write(b
, src
, (int)len
);
746 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
749 crypto_log_errors(LOG_WARN
, "reading public key from string");
756 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
757 * PEM-encoded. Return 0 on success, -1 on failure.
760 crypto_pk_write_private_key_to_filename(crypto_pk_t
*env
,
769 tor_assert(PRIVATE_KEY_OK(env
));
771 if (!(bio
= BIO_new(BIO_s_mem())))
773 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
775 crypto_log_errors(LOG_WARN
, "writing private key");
779 len
= BIO_get_mem_data(bio
, &cp
);
780 tor_assert(len
>= 0);
781 s
= tor_malloc(len
+1);
784 r
= write_str_to_file(fname
, s
, 0);
786 memwipe(s
, 0, strlen(s
));
791 /** Return true iff <b>env</b> has a valid key.
794 crypto_pk_check_key(crypto_pk_t
*env
)
799 r
= RSA_check_key(env
->key
);
801 crypto_log_errors(LOG_WARN
,"checking RSA key");
805 /** Return true iff <b>key</b> contains the private-key portion of the RSA
808 crypto_pk_key_is_private(const crypto_pk_t
*key
)
811 return PRIVATE_KEY_OK(key
);
814 /** Return true iff <b>env</b> contains a public key whose public exponent
818 crypto_pk_public_exponent_ok(crypto_pk_t
*env
)
821 tor_assert(env
->key
);
823 return BN_is_word(env
->key
->e
, 65537);
826 /** Compare the public-key components of a and b. Return less than 0
827 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
828 * considered to be less than all non-NULL keys, and equal to itself.
830 * Note that this may leak information about the keys through timing.
833 crypto_pk_cmp_keys(crypto_pk_t
*a
, crypto_pk_t
*b
)
836 char a_is_non_null
= (a
!= NULL
) && (a
->key
!= NULL
);
837 char b_is_non_null
= (b
!= NULL
) && (b
->key
!= NULL
);
838 char an_argument_is_null
= !a_is_non_null
| !b_is_non_null
;
840 result
= tor_memcmp(&a_is_non_null
, &b_is_non_null
, sizeof(a_is_non_null
));
841 if (an_argument_is_null
)
844 tor_assert(PUBLIC_KEY_OK(a
));
845 tor_assert(PUBLIC_KEY_OK(b
));
846 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
849 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
852 /** Compare the public-key components of a and b. Return non-zero iff
853 * a==b. A NULL key is considered to be distinct from all non-NULL
854 * keys, and equal to itself.
856 * Note that this may leak information about the keys through timing.
859 crypto_pk_eq_keys(crypto_pk_t
*a
, crypto_pk_t
*b
)
861 return (crypto_pk_cmp_keys(a
, b
) == 0);
864 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
866 crypto_pk_keysize(crypto_pk_t
*env
)
869 tor_assert(env
->key
);
871 return (size_t) RSA_size(env
->key
);
874 /** Return the size of the public key modulus of <b>env</b>, in bits. */
876 crypto_pk_num_bits(crypto_pk_t
*env
)
879 tor_assert(env
->key
);
880 tor_assert(env
->key
->n
);
882 return BN_num_bits(env
->key
->n
);
885 /** Increase the reference count of <b>env</b>, and return it.
888 crypto_pk_dup_key(crypto_pk_t
*env
)
891 tor_assert(env
->key
);
897 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
899 crypto_pk_copy_full(crypto_pk_t
*env
)
904 tor_assert(env
->key
);
906 if (PRIVATE_KEY_OK(env
)) {
907 new_key
= RSAPrivateKey_dup(env
->key
);
910 new_key
= RSAPublicKey_dup(env
->key
);
913 log_err(LD_CRYPTO
, "Unable to duplicate a %s key: openssl failed.",
914 privatekey
?"private":"public");
915 crypto_log_errors(LOG_ERR
,
916 privatekey
? "Duplicating a private key" :
917 "Duplicating a public key");
918 tor_fragile_assert();
922 return crypto_new_pk_from_rsa_(new_key
);
925 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
926 * in <b>env</b>, using the padding method <b>padding</b>. On success,
927 * write the result to <b>to</b>, and return the number of bytes
928 * written. On failure, return -1.
930 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
931 * at least the length of the modulus of <b>env</b>.
934 crypto_pk_public_encrypt(crypto_pk_t
*env
, char *to
, size_t tolen
,
935 const char *from
, size_t fromlen
, int padding
)
941 tor_assert(fromlen
<INT_MAX
);
942 tor_assert(tolen
>= crypto_pk_keysize(env
));
944 r
= RSA_public_encrypt((int)fromlen
,
945 (unsigned char*)from
, (unsigned char*)to
,
946 env
->key
, crypto_get_rsa_padding(padding
));
948 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
954 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
955 * in <b>env</b>, using the padding method <b>padding</b>. On success,
956 * write the result to <b>to</b>, and return the number of bytes
957 * written. On failure, return -1.
959 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
960 * at least the length of the modulus of <b>env</b>.
963 crypto_pk_private_decrypt(crypto_pk_t
*env
, char *to
,
965 const char *from
, size_t fromlen
,
966 int padding
, int warnOnFailure
)
972 tor_assert(env
->key
);
973 tor_assert(fromlen
<INT_MAX
);
974 tor_assert(tolen
>= crypto_pk_keysize(env
));
976 /* Not a private key */
979 r
= RSA_private_decrypt((int)fromlen
,
980 (unsigned char*)from
, (unsigned char*)to
,
981 env
->key
, crypto_get_rsa_padding(padding
));
984 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
985 "performing RSA decryption");
991 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
992 * public key in <b>env</b>, using PKCS1 padding. On success, write the
993 * signed data to <b>to</b>, and return the number of bytes written.
994 * On failure, return -1.
996 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
997 * at least the length of the modulus of <b>env</b>.
1000 crypto_pk_public_checksig(crypto_pk_t
*env
, char *to
,
1002 const char *from
, size_t fromlen
)
1008 tor_assert(fromlen
< INT_MAX
);
1009 tor_assert(tolen
>= crypto_pk_keysize(env
));
1010 r
= RSA_public_decrypt((int)fromlen
,
1011 (unsigned char*)from
, (unsigned char*)to
,
1012 env
->key
, RSA_PKCS1_PADDING
);
1015 crypto_log_errors(LOG_INFO
, "checking RSA signature");
1021 /** Check a siglen-byte long signature at <b>sig</b> against
1022 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
1023 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
1024 * SHA1(data). Else return -1.
1027 crypto_pk_public_checksig_digest(crypto_pk_t
*env
, const char *data
,
1028 size_t datalen
, const char *sig
, size_t siglen
)
1030 char digest
[DIGEST_LEN
];
1038 tor_assert(datalen
< SIZE_T_CEILING
);
1039 tor_assert(siglen
< SIZE_T_CEILING
);
1041 if (crypto_digest(digest
,data
,datalen
)<0) {
1042 log_warn(LD_BUG
, "couldn't compute digest");
1045 buflen
= crypto_pk_keysize(env
);
1046 buf
= tor_malloc(buflen
);
1047 r
= crypto_pk_public_checksig(env
,buf
,buflen
,sig
,siglen
);
1048 if (r
!= DIGEST_LEN
) {
1049 log_warn(LD_CRYPTO
, "Invalid signature");
1053 if (tor_memneq(buf
, digest
, DIGEST_LEN
)) {
1054 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
1063 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
1064 * <b>env</b>, using PKCS1 padding. On success, write the signature to
1065 * <b>to</b>, and return the number of bytes written. On failure, return
1068 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1069 * at least the length of the modulus of <b>env</b>.
1072 crypto_pk_private_sign(crypto_pk_t
*env
, char *to
, size_t tolen
,
1073 const char *from
, size_t fromlen
)
1079 tor_assert(fromlen
< INT_MAX
);
1080 tor_assert(tolen
>= crypto_pk_keysize(env
));
1082 /* Not a private key */
1085 r
= RSA_private_encrypt((int)fromlen
,
1086 (unsigned char*)from
, (unsigned char*)to
,
1087 env
->key
, RSA_PKCS1_PADDING
);
1089 crypto_log_errors(LOG_WARN
, "generating RSA signature");
1095 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1096 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1097 * store it in <b>to</b>. Return the number of bytes written on
1098 * success, and -1 on failure.
1100 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1101 * at least the length of the modulus of <b>env</b>.
1104 crypto_pk_private_sign_digest(crypto_pk_t
*env
, char *to
, size_t tolen
,
1105 const char *from
, size_t fromlen
)
1108 char digest
[DIGEST_LEN
];
1109 if (crypto_digest(digest
,from
,fromlen
)<0)
1111 r
= crypto_pk_private_sign(env
,to
,tolen
,digest
,DIGEST_LEN
);
1112 memwipe(digest
, 0, sizeof(digest
));
1116 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1117 * bytes of data from <b>from</b>, with padding type 'padding',
1118 * storing the results on <b>to</b>.
1120 * Returns the number of bytes written on success, -1 on failure.
1122 * The encrypted data consists of:
1123 * - The source data, padded and encrypted with the public key, if the
1124 * padded source data is no longer than the public key, and <b>force</b>
1126 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1127 * padded and encrypted with the public key; followed by the rest of
1128 * the source data encrypted in AES-CTR mode with the symmetric key.
1131 crypto_pk_public_hybrid_encrypt(crypto_pk_t
*env
,
1132 char *to
, size_t tolen
,
1135 int padding
, int force
)
1137 int overhead
, outlen
, r
;
1138 size_t pkeylen
, symlen
;
1139 crypto_cipher_t
*cipher
= NULL
;
1145 tor_assert(fromlen
< SIZE_T_CEILING
);
1147 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
1148 pkeylen
= crypto_pk_keysize(env
);
1150 if (!force
&& fromlen
+overhead
<= pkeylen
) {
1151 /* It all fits in a single encrypt. */
1152 return crypto_pk_public_encrypt(env
,to
,
1154 from
,fromlen
,padding
);
1156 tor_assert(tolen
>= fromlen
+ overhead
+ CIPHER_KEY_LEN
);
1157 tor_assert(tolen
>= pkeylen
);
1159 cipher
= crypto_cipher_new(NULL
); /* generate a new key. */
1161 buf
= tor_malloc(pkeylen
+1);
1162 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
1163 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
1165 /* Length of symmetrically encrypted data. */
1166 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
1168 outlen
= crypto_pk_public_encrypt(env
,to
,tolen
,buf
,pkeylen
-overhead
,padding
);
1169 if (outlen
!=(int)pkeylen
) {
1172 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
1173 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
1176 memwipe(buf
, 0, pkeylen
);
1178 crypto_cipher_free(cipher
);
1179 tor_assert(outlen
+symlen
< INT_MAX
);
1180 return (int)(outlen
+ symlen
);
1183 memwipe(buf
, 0, pkeylen
);
1185 crypto_cipher_free(cipher
);
1189 /** Invert crypto_pk_public_hybrid_encrypt. */
1191 crypto_pk_private_hybrid_decrypt(crypto_pk_t
*env
,
1196 int padding
, int warnOnFailure
)
1200 crypto_cipher_t
*cipher
= NULL
;
1203 tor_assert(fromlen
< SIZE_T_CEILING
);
1204 pkeylen
= crypto_pk_keysize(env
);
1206 if (fromlen
<= pkeylen
) {
1207 return crypto_pk_private_decrypt(env
,to
,tolen
,from
,fromlen
,padding
,
1211 buf
= tor_malloc(pkeylen
);
1212 outlen
= crypto_pk_private_decrypt(env
,buf
,pkeylen
,from
,pkeylen
,padding
,
1215 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
1216 "Error decrypting public-key data");
1219 if (outlen
< CIPHER_KEY_LEN
) {
1220 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1221 "No room for a symmetric key");
1224 cipher
= crypto_cipher_new(buf
);
1228 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1229 outlen
-= CIPHER_KEY_LEN
;
1230 tor_assert(tolen
- outlen
>= fromlen
- pkeylen
);
1231 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1234 memwipe(buf
,0,pkeylen
);
1236 crypto_cipher_free(cipher
);
1237 tor_assert(outlen
+ fromlen
< INT_MAX
);
1238 return (int)(outlen
+ (fromlen
-pkeylen
));
1240 memwipe(buf
,0,pkeylen
);
1242 crypto_cipher_free(cipher
);
1246 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1247 * Return -1 on error, or the number of characters used on success.
1250 crypto_pk_asn1_encode(crypto_pk_t
*pk
, char *dest
, size_t dest_len
)
1253 unsigned char *buf
= NULL
;
1255 len
= i2d_RSAPublicKey(pk
->key
, &buf
);
1256 if (len
< 0 || buf
== NULL
)
1259 if ((size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
) {
1263 /* We don't encode directly into 'dest', because that would be illegal
1264 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1266 memcpy(dest
,buf
,len
);
1271 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1272 * success and NULL on failure.
1275 crypto_pk_asn1_decode(const char *str
, size_t len
)
1279 const unsigned char *cp
;
1280 cp
= buf
= tor_malloc(len
);
1281 memcpy(buf
,str
,len
);
1282 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1285 crypto_log_errors(LOG_WARN
,"decoding public key");
1288 return crypto_new_pk_from_rsa_(rsa
);
1291 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1292 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1293 * Return 0 on success, -1 on failure.
1296 crypto_pk_get_digest(const crypto_pk_t
*pk
, char *digest_out
)
1298 unsigned char *buf
= NULL
;
1301 len
= i2d_RSAPublicKey(pk
->key
, &buf
);
1302 if (len
< 0 || buf
== NULL
)
1304 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1312 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1313 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1315 crypto_pk_get_all_digests(crypto_pk_t
*pk
, digests_t
*digests_out
)
1317 unsigned char *buf
= NULL
;
1320 len
= i2d_RSAPublicKey(pk
->key
, &buf
);
1321 if (len
< 0 || buf
== NULL
)
1323 if (crypto_digest_all(digests_out
, (char*)buf
, len
) < 0) {
1331 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1332 * every four spaces. */
1334 crypto_add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1337 char *end
= out
+outlen
;
1338 tor_assert(outlen
< SIZE_T_CEILING
);
1340 while (*in
&& out
<end
) {
1342 if (++n
== 4 && *in
&& out
<end
) {
1347 tor_assert(out
<end
);
1351 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1352 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1353 * space). Return 0 on success, -1 on failure.
1355 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1356 * of the public key, converted to hexadecimal, in upper case, with a
1357 * space after every four digits.
1359 * If <b>add_space</b> is false, omit the spaces.
1362 crypto_pk_get_fingerprint(crypto_pk_t
*pk
, char *fp_out
, int add_space
)
1364 char digest
[DIGEST_LEN
];
1365 char hexdigest
[HEX_DIGEST_LEN
+1];
1366 if (crypto_pk_get_digest(pk
, digest
)) {
1369 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1371 crypto_add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1373 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1378 /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
1379 * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
1380 * bytes of space). Return 0 on success, -1 on failure.
1382 * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
1383 * of the ASN.1 encoding of the public key, converted to hexadecimal, in
1387 crypto_pk_get_hashed_fingerprint(crypto_pk_t
*pk
, char *fp_out
)
1389 char digest
[DIGEST_LEN
], hashed_digest
[DIGEST_LEN
];
1390 if (crypto_pk_get_digest(pk
, digest
)) {
1393 if (crypto_digest(hashed_digest
, digest
, DIGEST_LEN
)) {
1396 base16_encode(fp_out
, FINGERPRINT_LEN
+ 1, hashed_digest
, DIGEST_LEN
);
1400 /* symmetric crypto */
1402 /** Return a pointer to the key set for the cipher in <b>env</b>.
1405 crypto_cipher_get_key(crypto_cipher_t
*env
)
1410 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1411 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1412 * On failure, return -1.
1415 crypto_cipher_encrypt(crypto_cipher_t
*env
, char *to
,
1416 const char *from
, size_t fromlen
)
1419 tor_assert(env
->cipher
);
1421 tor_assert(fromlen
);
1423 tor_assert(fromlen
< SIZE_T_CEILING
);
1425 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1429 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1430 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1431 * On failure, return -1.
1434 crypto_cipher_decrypt(crypto_cipher_t
*env
, char *to
,
1435 const char *from
, size_t fromlen
)
1440 tor_assert(fromlen
< SIZE_T_CEILING
);
1442 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1446 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1447 * on success, return 0. On failure, return -1.
1450 crypto_cipher_crypt_inplace(crypto_cipher_t
*env
, char *buf
, size_t len
)
1452 tor_assert(len
< SIZE_T_CEILING
);
1453 aes_crypt_inplace(env
->cipher
, buf
, len
);
1457 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1458 * <b>key</b> to the buffer in <b>to</b> of length
1459 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1460 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1461 * number of bytes written, on failure, return -1.
1464 crypto_cipher_encrypt_with_iv(const char *key
,
1465 char *to
, size_t tolen
,
1466 const char *from
, size_t fromlen
)
1468 crypto_cipher_t
*cipher
;
1471 tor_assert(fromlen
< INT_MAX
);
1475 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1478 cipher
= crypto_cipher_new_with_iv(key
, NULL
);
1480 memcpy(to
, cipher
->iv
, CIPHER_IV_LEN
);
1481 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1482 crypto_cipher_free(cipher
);
1483 return (int)(fromlen
+ CIPHER_IV_LEN
);
1486 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1487 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1488 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1489 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1490 * number of bytes written, on failure, return -1.
1493 crypto_cipher_decrypt_with_iv(const char *key
,
1494 char *to
, size_t tolen
,
1495 const char *from
, size_t fromlen
)
1497 crypto_cipher_t
*cipher
;
1501 tor_assert(fromlen
< INT_MAX
);
1503 if (fromlen
<= CIPHER_IV_LEN
)
1505 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1508 cipher
= crypto_cipher_new_with_iv(key
, from
);
1510 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1511 crypto_cipher_free(cipher
);
1512 return (int)(fromlen
- CIPHER_IV_LEN
);
1517 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1518 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1519 * Return 0 on success, -1 on failure.
1522 crypto_digest(char *digest
, const char *m
, size_t len
)
1526 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1529 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1530 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1531 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1533 crypto_digest256(char *digest
, const char *m
, size_t len
,
1534 digest_algorithm_t algorithm
)
1538 tor_assert(algorithm
== DIGEST_SHA256
);
1539 return (SHA256((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1542 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1543 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1544 * success, -1 on failure. */
1546 crypto_digest_all(digests_t
*ds_out
, const char *m
, size_t len
)
1550 memset(ds_out
, 0, sizeof(*ds_out
));
1551 if (crypto_digest(ds_out
->d
[DIGEST_SHA1
], m
, len
) < 0)
1553 for (i
= DIGEST_SHA256
; i
< N_DIGEST_ALGORITHMS
; ++i
) {
1554 if (crypto_digest256(ds_out
->d
[i
], m
, len
, i
) < 0)
1560 /** Return the name of an algorithm, as used in directory documents. */
1562 crypto_digest_algorithm_get_name(digest_algorithm_t alg
)
1570 tor_fragile_assert();
1571 return "??unknown_digest??";
1575 /** Given the name of a digest algorithm, return its integer value, or -1 if
1576 * the name is not recognized. */
1578 crypto_digest_algorithm_parse_name(const char *name
)
1580 if (!strcmp(name
, "sha1"))
1582 else if (!strcmp(name
, "sha256"))
1583 return DIGEST_SHA256
;
1588 /** Intermediate information about the digest of a stream of data. */
1589 struct crypto_digest_t
{
1591 SHA_CTX sha1
; /**< state for SHA1 */
1592 SHA256_CTX sha2
; /**< state for SHA256 */
1593 } d
; /**< State for the digest we're using. Only one member of the
1594 * union is usable, depending on the value of <b>algorithm</b>. */
1595 digest_algorithm_bitfield_t algorithm
: 8; /**< Which algorithm is in use? */
1598 /** Allocate and return a new digest object to compute SHA1 digests.
1601 crypto_digest_new(void)
1604 r
= tor_malloc(sizeof(crypto_digest_t
));
1605 SHA1_Init(&r
->d
.sha1
);
1606 r
->algorithm
= DIGEST_SHA1
;
1610 /** Allocate and return a new digest object to compute 256-bit digests
1611 * using <b>algorithm</b>. */
1613 crypto_digest256_new(digest_algorithm_t algorithm
)
1616 tor_assert(algorithm
== DIGEST_SHA256
);
1617 r
= tor_malloc(sizeof(crypto_digest_t
));
1618 SHA256_Init(&r
->d
.sha2
);
1619 r
->algorithm
= algorithm
;
1623 /** Deallocate a digest object.
1626 crypto_digest_free(crypto_digest_t
*digest
)
1630 memwipe(digest
, 0, sizeof(crypto_digest_t
));
1634 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1637 crypto_digest_add_bytes(crypto_digest_t
*digest
, const char *data
,
1642 /* Using the SHA*_*() calls directly means we don't support doing
1643 * SHA in hardware. But so far the delay of getting the question
1644 * to the hardware, and hearing the answer, is likely higher than
1645 * just doing it ourselves. Hashes are fast.
1647 switch (digest
->algorithm
) {
1649 SHA1_Update(&digest
->d
.sha1
, (void*)data
, len
);
1652 SHA256_Update(&digest
->d
.sha2
, (void*)data
, len
);
1655 tor_fragile_assert();
1660 /** Compute the hash of the data that has been passed to the digest
1661 * object; write the first out_len bytes of the result to <b>out</b>.
1662 * <b>out_len</b> must be \<= DIGEST256_LEN.
1665 crypto_digest_get_digest(crypto_digest_t
*digest
,
1666 char *out
, size_t out_len
)
1668 unsigned char r
[DIGEST256_LEN
];
1669 crypto_digest_t tmpenv
;
1672 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1673 memcpy(&tmpenv
, digest
, sizeof(crypto_digest_t
));
1674 switch (digest
->algorithm
) {
1676 tor_assert(out_len
<= DIGEST_LEN
);
1677 SHA1_Final(r
, &tmpenv
.d
.sha1
);
1680 tor_assert(out_len
<= DIGEST256_LEN
);
1681 SHA256_Final(r
, &tmpenv
.d
.sha2
);
1684 log_warn(LD_BUG
, "Called with unknown algorithm %d", digest
->algorithm
);
1685 /* If fragile_assert is not enabled, then we should at least not
1687 memwipe(r
, 0xff, sizeof(r
));
1688 tor_fragile_assert();
1691 memcpy(out
, r
, out_len
);
1692 memwipe(r
, 0, sizeof(r
));
1695 /** Allocate and return a new digest object with the same state as
1699 crypto_digest_dup(const crypto_digest_t
*digest
)
1703 r
= tor_malloc(sizeof(crypto_digest_t
));
1704 memcpy(r
,digest
,sizeof(crypto_digest_t
));
1708 /** Replace the state of the digest object <b>into</b> with the state
1709 * of the digest object <b>from</b>.
1712 crypto_digest_assign(crypto_digest_t
*into
,
1713 const crypto_digest_t
*from
)
1717 memcpy(into
,from
,sizeof(crypto_digest_t
));
1720 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1721 * at <b>digest_out</b> to the hash of the concatenation of those strings,
1722 * plus the optional string <b>append</b>, computed with the algorithm
1724 * <b>out_len</b> must be \<= DIGEST256_LEN. */
1726 crypto_digest_smartlist(char *digest_out
, size_t len_out
,
1727 const smartlist_t
*lst
, const char *append
,
1728 digest_algorithm_t alg
)
1731 if (alg
== DIGEST_SHA1
)
1732 d
= crypto_digest_new();
1734 d
= crypto_digest256_new(alg
);
1735 SMARTLIST_FOREACH(lst
, const char *, cp
,
1736 crypto_digest_add_bytes(d
, cp
, strlen(cp
)));
1738 crypto_digest_add_bytes(d
, append
, strlen(append
));
1739 crypto_digest_get_digest(d
, digest_out
, len_out
);
1740 crypto_digest_free(d
);
1743 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1744 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
1745 * result in <b>hmac_out</b>.
1748 crypto_hmac_sha256(char *hmac_out
,
1749 const char *key
, size_t key_len
,
1750 const char *msg
, size_t msg_len
)
1752 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1753 tor_assert(key_len
< INT_MAX
);
1754 tor_assert(msg_len
< INT_MAX
);
1755 HMAC(EVP_sha256(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1756 (unsigned char*)hmac_out
, NULL
);
1761 /** Our DH 'g' parameter */
1762 #define DH_GENERATOR 2
1764 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1765 static BIGNUM
*dh_param_p
= NULL
;
1766 /** Shared P parameter for our TLS DH key exchanges. */
1767 static BIGNUM
*dh_param_p_tls
= NULL
;
1768 /** Shared G parameter for our DH key exchanges. */
1769 static BIGNUM
*dh_param_g
= NULL
;
1771 /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
1774 crypto_set_tls_dh_prime(void)
1776 BIGNUM
*tls_prime
= NULL
;
1779 /* If the space is occupied, free the previous TLS DH prime */
1780 if (dh_param_p_tls
) {
1781 BN_clear_free(dh_param_p_tls
);
1782 dh_param_p_tls
= NULL
;
1785 tls_prime
= BN_new();
1786 tor_assert(tls_prime
);
1788 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1789 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
1792 r
= BN_hex2bn(&tls_prime
,
1793 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1794 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1795 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1796 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1797 "B0E7393E0F24218EB3");
1800 tor_assert(tls_prime
);
1802 dh_param_p_tls
= tls_prime
;
1805 /** Initialize dh_param_p and dh_param_g if they are not already
1810 BIGNUM
*circuit_dh_prime
, *generator
;
1812 if (dh_param_p
&& dh_param_g
)
1815 circuit_dh_prime
= BN_new();
1816 generator
= BN_new();
1817 tor_assert(circuit_dh_prime
&& generator
);
1819 /* Set our generator for all DH parameters */
1820 r
= BN_set_word(generator
, DH_GENERATOR
);
1823 /* This is from rfc2409, section 6.2. It's a safe prime, and
1824 supposedly it equals:
1825 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1827 r
= BN_hex2bn(&circuit_dh_prime
,
1828 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1829 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1830 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1831 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1832 "49286651ECE65381FFFFFFFFFFFFFFFF");
1835 /* Set the new values as the global DH parameters. */
1836 dh_param_p
= circuit_dh_prime
;
1837 dh_param_g
= generator
;
1839 if (!dh_param_p_tls
) {
1840 crypto_set_tls_dh_prime();
1844 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
1845 * handshake. Since we exponentiate by this value, choosing a smaller one
1846 * lets our handhake go faster.
1848 #define DH_PRIVATE_KEY_BITS 320
1850 /** Allocate and return a new DH object for a key exchange.
1853 crypto_dh_new(int dh_type
)
1855 crypto_dh_t
*res
= tor_malloc_zero(sizeof(crypto_dh_t
));
1857 tor_assert(dh_type
== DH_TYPE_CIRCUIT
|| dh_type
== DH_TYPE_TLS
||
1858 dh_type
== DH_TYPE_REND
);
1863 if (!(res
->dh
= DH_new()))
1866 if (dh_type
== DH_TYPE_TLS
) {
1867 if (!(res
->dh
->p
= BN_dup(dh_param_p_tls
)))
1870 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1874 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1877 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1881 crypto_log_errors(LOG_WARN
, "creating DH object");
1882 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1887 /** Return a copy of <b>dh</b>, sharing its internal state. */
1889 crypto_dh_dup(const crypto_dh_t
*dh
)
1891 crypto_dh_t
*dh_new
= tor_malloc_zero(sizeof(crypto_dh_t
));
1892 dh_new
->dh
= dh
->dh
;
1897 /** Return the length of the DH key in <b>dh</b>, in bytes.
1900 crypto_dh_get_bytes(crypto_dh_t
*dh
)
1903 return DH_size(dh
->dh
);
1906 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1907 * success, -1 on failure.
1910 crypto_dh_generate_public(crypto_dh_t
*dh
)
1913 if (!DH_generate_key(dh
->dh
)) {
1914 crypto_log_errors(LOG_WARN
, "generating DH key");
1917 if (tor_check_dh_key(LOG_WARN
, dh
->dh
->pub_key
)<0) {
1918 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1919 "the-universe chances really do happen. Trying again.");
1920 /* Free and clear the keys, so OpenSSL will actually try again. */
1921 BN_clear_free(dh
->dh
->pub_key
);
1922 BN_clear_free(dh
->dh
->priv_key
);
1923 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1929 /** Generate g^x as necessary, and write the g^x for the key exchange
1930 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1931 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1934 crypto_dh_get_public(crypto_dh_t
*dh
, char *pubkey
, size_t pubkey_len
)
1938 if (!dh
->dh
->pub_key
) {
1939 if (crypto_dh_generate_public(dh
)<0)
1943 tor_assert(dh
->dh
->pub_key
);
1944 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1945 tor_assert(bytes
>= 0);
1946 if (pubkey_len
< (size_t)bytes
) {
1948 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1949 (int) pubkey_len
, bytes
);
1953 memset(pubkey
, 0, pubkey_len
);
1954 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1959 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1960 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1961 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1964 tor_check_dh_key(int severity
, BIGNUM
*bn
)
1974 if (BN_cmp(bn
,x
)<=0) {
1975 log_fn(severity
, LD_CRYPTO
, "DH key must be at least 2.");
1978 BN_copy(x
,dh_param_p
);
1980 if (BN_cmp(bn
,x
)>=0) {
1981 log_fn(severity
, LD_CRYPTO
, "DH key must be at most p-2.");
1989 log_fn(severity
, LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1995 #define MIN(a,b) ((a)<(b)?(a):(b))
1996 /** Given a DH key exchange object, and our peer's value of g^y (as a
1997 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1998 * <b>secret_bytes_out</b> bytes of shared key material and write them
1999 * to <b>secret_out</b>. Return the number of bytes generated on success,
2002 * (We generate key material by computing
2003 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2004 * where || is concatenation.)
2007 crypto_dh_compute_secret(int severity
, crypto_dh_t
*dh
,
2008 const char *pubkey
, size_t pubkey_len
,
2009 char *secret_out
, size_t secret_bytes_out
)
2011 char *secret_tmp
= NULL
;
2012 BIGNUM
*pubkey_bn
= NULL
;
2013 size_t secret_len
=0, secret_tmp_len
=0;
2016 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
2017 tor_assert(pubkey_len
< INT_MAX
);
2019 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
2020 (int)pubkey_len
, NULL
)))
2022 if (tor_check_dh_key(severity
, pubkey_bn
)<0) {
2023 /* Check for invalid public keys. */
2024 log_fn(severity
, LD_CRYPTO
,"Rejected invalid g^x");
2027 secret_tmp_len
= crypto_dh_get_bytes(dh
);
2028 secret_tmp
= tor_malloc(secret_tmp_len
);
2029 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
2031 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
2034 secret_len
= result
;
2035 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp
, secret_len
,
2036 (uint8_t*)secret_out
, secret_bytes_out
)<0)
2038 secret_len
= secret_bytes_out
;
2044 crypto_log_errors(LOG_WARN
, "completing DH handshake");
2046 BN_clear_free(pubkey_bn
);
2048 memwipe(secret_tmp
, 0, secret_tmp_len
);
2049 tor_free(secret_tmp
);
2057 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2058 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2059 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2060 * H(K | [00]) | H(K | [01]) | ....
2062 * This is the key expansion algorithm used in the "TAP" circuit extension
2063 * mechanism; it shouldn't be used for new protocols.
2065 * Return 0 on success, -1 on failure.
2068 crypto_expand_key_material_TAP(const uint8_t *key_in
, size_t key_in_len
,
2069 uint8_t *key_out
, size_t key_out_len
)
2072 uint8_t *cp
, *tmp
= tor_malloc(key_in_len
+1);
2073 uint8_t digest
[DIGEST_LEN
];
2075 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2076 tor_assert(key_out_len
<= DIGEST_LEN
*256);
2078 memcpy(tmp
, key_in
, key_in_len
);
2079 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
2080 ++i
, cp
+= DIGEST_LEN
) {
2081 tmp
[key_in_len
] = i
;
2082 if (crypto_digest((char*)digest
, (const char *)tmp
, key_in_len
+1))
2084 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
2086 memwipe(tmp
, 0, key_in_len
+1);
2088 memwipe(digest
, 0, sizeof(digest
));
2092 memwipe(tmp
, 0, key_in_len
+1);
2094 memwipe(digest
, 0, sizeof(digest
));
2098 /** Expand some secret key material according to RFC5869, using SHA256 as the
2099 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2100 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2101 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2102 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2103 * bytes to <b>key_out</b> and return 0. On failure, return -1.
2106 crypto_expand_key_material_rfc5869_sha256(
2107 const uint8_t *key_in
, size_t key_in_len
,
2108 const uint8_t *salt_in
, size_t salt_in_len
,
2109 const uint8_t *info_in
, size_t info_in_len
,
2110 uint8_t *key_out
, size_t key_out_len
)
2112 uint8_t prk
[DIGEST256_LEN
];
2113 uint8_t tmp
[DIGEST256_LEN
+ 128 + 1];
2114 uint8_t mac
[DIGEST256_LEN
];
2119 crypto_hmac_sha256((char*)prk
,
2120 (const char*)salt_in
, salt_in_len
,
2121 (const char*)key_in
, key_in_len
);
2123 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2124 tor_assert(key_out_len
<= DIGEST256_LEN
* 256);
2125 tor_assert(info_in_len
<= 128);
2126 memset(tmp
, 0, sizeof(tmp
));
2130 while (key_out_len
) {
2133 memcpy(tmp
, mac
, DIGEST256_LEN
);
2134 memcpy(tmp
+DIGEST256_LEN
, info_in
, info_in_len
);
2135 tmp
[DIGEST256_LEN
+info_in_len
] = i
;
2136 tmp_len
= DIGEST256_LEN
+ info_in_len
+ 1;
2138 memcpy(tmp
, info_in
, info_in_len
);
2139 tmp
[info_in_len
] = i
;
2140 tmp_len
= info_in_len
+ 1;
2142 crypto_hmac_sha256((char*)mac
,
2143 (const char*)prk
, DIGEST256_LEN
,
2144 (const char*)tmp
, tmp_len
);
2145 n
= key_out_len
< DIGEST256_LEN
? key_out_len
: DIGEST256_LEN
;
2146 memcpy(outp
, mac
, n
);
2152 memwipe(tmp
, 0, sizeof(tmp
));
2153 memwipe(mac
, 0, sizeof(mac
));
2157 /** Free a DH key exchange object.
2160 crypto_dh_free(crypto_dh_t
*dh
)
2169 /* random numbers */
2171 /** How many bytes of entropy we add at once.
2173 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2174 * work for us too. */
2175 #define ADD_ENTROPY 32
2177 /** True iff it's safe to use RAND_poll after setup.
2179 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2180 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2181 * that fd without checking whether it fit in the fd_set. Thus, if the
2182 * system has not just been started up, it is unsafe to call */
2183 #define RAND_POLL_IS_SAFE \
2184 (OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2186 /** Set the seed of the weak RNG to a random value. */
2188 crypto_seed_weak_rng(tor_weak_rng_t
*rng
)
2191 crypto_rand((void*)&seed
, sizeof(seed
));
2192 tor_init_weak_random(rng
, seed
);
2195 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2196 * storing it into <b>out</b>.
2199 crypto_strongest_rand(uint8_t *out
, size_t out_len
)
2202 static int provider_set
= 0;
2203 static HCRYPTPROV provider
;
2205 static const char *filenames
[] = {
2206 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2213 if (!provider_set
) {
2214 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
2215 CRYPT_VERIFYCONTEXT
)) {
2216 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
2221 if (!CryptGenRandom(provider
, out_len
, out
)) {
2222 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
2228 for (i
= 0; filenames
[i
]; ++i
) {
2229 log_debug(LD_FS
, "Opening %s for entropy", filenames
[i
]);
2230 fd
= open(sandbox_intern_string(filenames
[i
]), O_RDONLY
, 0);
2232 log_info(LD_CRYPTO
, "Reading entropy from \"%s\"", filenames
[i
]);
2233 n
= read_all(fd
, (char*)out
, out_len
, 0);
2237 "Error reading from entropy source (read only %lu bytes).",
2245 log_warn(LD_CRYPTO
, "Cannot get strong entropy: no entropy source found.");
2250 /** Seed OpenSSL's random number generator with bytes from the operating
2251 * system. <b>startup</b> should be true iff we have just started Tor and
2252 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2255 crypto_seed_rng(int startup
)
2257 int rand_poll_ok
= 0, load_entropy_ok
= 0;
2258 uint8_t buf
[ADD_ENTROPY
];
2260 /* OpenSSL has a RAND_poll function that knows about more kinds of
2261 * entropy than we do. We'll try calling that, *and* calling our own entropy
2262 * functions. If one succeeds, we'll accept the RNG as seeded. */
2263 if (startup
|| RAND_POLL_IS_SAFE
) {
2264 rand_poll_ok
= RAND_poll();
2265 if (rand_poll_ok
== 0)
2266 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
2269 load_entropy_ok
= !crypto_strongest_rand(buf
, sizeof(buf
));
2270 if (load_entropy_ok
) {
2271 RAND_seed(buf
, sizeof(buf
));
2274 memwipe(buf
, 0, sizeof(buf
));
2276 if (rand_poll_ok
|| load_entropy_ok
)
2282 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2283 * success, -1 on failure.
2286 crypto_rand
, (char *to
, size_t n
))
2289 tor_assert(n
< INT_MAX
);
2291 r
= RAND_bytes((unsigned char*)to
, (int)n
);
2293 crypto_log_errors(LOG_WARN
, "generating random data");
2294 return (r
== 1) ? 0 : -1;
2297 /** Return a pseudorandom integer, chosen uniformly from the values
2298 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2299 * INT_MAX+1, inclusive. */
2301 crypto_rand_int(unsigned int max
)
2304 unsigned int cutoff
;
2305 tor_assert(max
<= ((unsigned int)INT_MAX
)+1);
2306 tor_assert(max
> 0); /* don't div by 0 */
2308 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2309 * distribution with clipping at the upper end of unsigned int's
2312 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
2314 crypto_rand((char*)&val
, sizeof(val
));
2320 /** Return a pseudorandom integer, chosen uniformly from the values <i>i</i>
2321 * such that <b>min</b> <= <i>i</i> < <b>max</b>.
2323 * <b>min</b> MUST be in range [0, <b>max</b>).
2324 * <b>max</b> MUST be in range (min, INT_MAX].
2327 crypto_rand_int_range(unsigned int min
, unsigned int max
)
2329 tor_assert(min
< max
);
2330 tor_assert(max
<= INT_MAX
);
2332 /* The overflow is avoided here because crypto_rand_int() returns a value
2333 * between 0 and (max - min - 1) with max being <= INT_MAX and min <= max.
2334 * This is why we add 1 to the maximum value so we can actually get max as
2335 * a return value. */
2336 return min
+ crypto_rand_int(max
- min
);
2339 /** As crypto_rand_int_range, but supports uint64_t. */
2341 crypto_rand_uint64_range(uint64_t min
, uint64_t max
)
2343 tor_assert(min
< max
);
2344 return min
+ crypto_rand_uint64(max
- min
);
2347 /** As crypto_rand_int_range, but supports time_t. */
2349 crypto_rand_time_range(time_t min
, time_t max
)
2351 return (time_t) crypto_rand_uint64_range(min
, max
);
2354 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2355 * between 0 and <b>max</b>-1. */
2357 crypto_rand_uint64(uint64_t max
)
2361 tor_assert(max
< UINT64_MAX
);
2362 tor_assert(max
> 0); /* don't div by 0 */
2364 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2365 * distribution with clipping at the upper end of unsigned int's
2368 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
2370 crypto_rand((char*)&val
, sizeof(val
));
2376 /** Return a pseudorandom double d, chosen uniformly from the range
2380 crypto_rand_double(void)
2382 /* We just use an unsigned int here; we don't really care about getting
2383 * more than 32 bits of resolution */
2385 crypto_rand((char*)&uint
, sizeof(uint
));
2387 #define UINT_MAX_AS_DOUBLE 4294967296.0
2388 #elif SIZEOF_INT == 8
2389 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2391 #error SIZEOF_INT is neither 4 nor 8
2393 return ((double)uint
) / UINT_MAX_AS_DOUBLE
;
2396 /** Generate and return a new random hostname starting with <b>prefix</b>,
2397 * ending with <b>suffix</b>, and containing no fewer than
2398 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2399 * characters between.
2401 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2404 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
2407 char *result
, *rand_bytes
;
2408 int randlen
, rand_bytes_len
;
2409 size_t resultlen
, prefixlen
;
2411 if (max_rand_len
> MAX_DNS_LABEL_SIZE
)
2412 max_rand_len
= MAX_DNS_LABEL_SIZE
;
2413 if (min_rand_len
> max_rand_len
)
2414 min_rand_len
= max_rand_len
;
2416 randlen
= crypto_rand_int_range(min_rand_len
, max_rand_len
+1);
2418 prefixlen
= strlen(prefix
);
2419 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
2421 rand_bytes_len
= ((randlen
*5)+7)/8;
2422 if (rand_bytes_len
% 5)
2423 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
2424 rand_bytes
= tor_malloc(rand_bytes_len
);
2425 crypto_rand(rand_bytes
, rand_bytes_len
);
2427 result
= tor_malloc(resultlen
);
2428 memcpy(result
, prefix
, prefixlen
);
2429 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
2430 rand_bytes
, rand_bytes_len
);
2431 tor_free(rand_bytes
);
2432 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
2437 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2440 smartlist_choose(const smartlist_t
*sl
)
2442 int len
= smartlist_len(sl
);
2444 return smartlist_get(sl
,crypto_rand_int(len
));
2445 return NULL
; /* no elements to choose from */
2448 /** Scramble the elements of <b>sl</b> into a random order. */
2450 smartlist_shuffle(smartlist_t
*sl
)
2453 /* From the end of the list to the front, choose at random from the
2454 positions we haven't looked at yet, and swap that position into the
2455 current position. Remember to give "no swap" the same probability as
2457 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
2458 int j
= crypto_rand_int(i
+1);
2459 smartlist_swap(sl
, i
, j
);
2463 #define BASE64_OPENSSL_LINELEN 64
2465 /** Return the Base64 encoded size of <b>srclen</b> bytes of data in
2468 * If <b>flags</b>&BASE64_ENCODE_MULTILINE is true, return the size
2469 * of the encoded output as multiline output (64 character, `\n' terminated
2473 base64_encode_size(size_t srclen
, int flags
)
2476 tor_assert(srclen
< INT_MAX
);
2481 enclen
= ((srclen
- 1) / 3) * 4 + 4;
2482 if (flags
& BASE64_ENCODE_MULTILINE
) {
2483 size_t remainder
= enclen
% BASE64_OPENSSL_LINELEN
;
2484 enclen
+= enclen
/ BASE64_OPENSSL_LINELEN
;
2488 tor_assert(enclen
< INT_MAX
&& enclen
> srclen
);
2492 /** Internal table mapping 6 bit values to the Base64 alphabet. */
2493 static const char base64_encode_table
[64] = {
2494 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
2495 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
2496 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
2497 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
2498 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
2499 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
2500 'w', 'x', 'y', 'z', '0', '1', '2', '3',
2501 '4', '5', '6', '7', '8', '9', '+', '/'
2504 /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2505 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2506 * bytes. Return the number of bytes written on success; -1 if
2507 * destlen is too short, or other failure.
2509 * If <b>flags</b>&BASE64_ENCODE_MULTILINE is true, return encoded
2510 * output in multiline format (64 character, `\n' terminated lines).
2513 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
,
2516 const unsigned char *usrc
= (unsigned char *)src
;
2517 const unsigned char *eous
= usrc
+ srclen
;
2527 /* Ensure that there is sufficient space, including the NUL. */
2528 enclen
= base64_encode_size(srclen
, flags
);
2529 if (destlen
< enclen
+ 1)
2531 if (destlen
> SIZE_T_CEILING
)
2533 if (enclen
> INT_MAX
)
2536 memset(dest
, 0, enclen
);
2538 /* XXX/Yawning: If this ends up being too slow, this can be sped up
2539 * by separating the multiline format case and the normal case, and
2540 * processing 48 bytes of input at a time when newlines are desired.
2542 #define ENCODE_CHAR(ch) \
2545 if (flags & BASE64_ENCODE_MULTILINE) { \
2546 if (++linelen % BASE64_OPENSSL_LINELEN == 0) { \
2553 #define ENCODE_N(idx) \
2554 ENCODE_CHAR(base64_encode_table[(n >> ((3 - idx) * 6)) & 0x3f])
2556 #define ENCODE_PAD() ENCODE_CHAR('=')
2558 /* Iterate over all the bytes in src. Each one will add 8 bits to the
2559 * value we're encoding. Accumulate bits in <b>n</b>, and whenever we
2560 * have 24 bits, batch them into 4 bytes and flush those bytes to dest.
2562 for ( ; usrc
< eous
; ++usrc
) {
2563 n
= (n
<< 8) | *usrc
;
2564 if ((++n_idx
) == 3) {
2575 /* 0 leftover bits, no pading to add. */
2578 /* 8 leftover bits, pad to 12 bits, write the 2 6-bit values followed
2579 * by 2 padding characters.
2588 /* 16 leftover bits, pad to 18 bits, write the 3 6-bit values followed
2589 * by 1 padding character.
2598 /* Something went catastrophically wrong. */
2599 tor_fragile_assert();
2607 /* Multiline output always includes at least one newline. */
2608 if (flags
& BASE64_ENCODE_MULTILINE
&& linelen
!= 0)
2611 tor_assert(d
- dest
== (ptrdiff_t)enclen
);
2613 *d
++ = '\0'; /* NUL terminate the output. */
2615 return (int) enclen
;
2618 #undef BASE64_OPENSSL_LINELEN
2621 /** Special values used for the base64_decode_table */
2626 /** Internal table mapping byte values to what they represent in base64.
2627 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2628 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2630 static const uint8_t base64_decode_table
[256] = {
2631 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
2632 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2633 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
2634 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
2635 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2636 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
2637 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2638 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
2639 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2640 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2641 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2642 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2643 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2644 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2645 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2646 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2649 /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2650 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2651 * bytes. Return the number of bytes written on success; -1 if
2652 * destlen is too short, or other failure.
2654 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2655 * spaces or padding.
2657 * NOTE 2: This implementation does not check for the correct number of
2658 * padding "=" characters at the end of the string, and does not check
2659 * for internal padding characters.
2662 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2664 const char *eos
= src
+srclen
;
2667 char *dest_orig
= dest
;
2669 /* Max number of bits == srclen*6.
2670 * Number of bytes required to hold all bits == (srclen*6)/8.
2671 * Yes, we want to round down: anything that hangs over the end of a
2672 * byte is padding. */
2673 if (destlen
< (srclen
*3)/4)
2675 if (destlen
> SIZE_T_CEILING
)
2678 memset(dest
, 0, destlen
);
2680 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2681 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2682 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2684 for ( ; src
< eos
; ++src
) {
2685 unsigned char c
= (unsigned char) *src
;
2686 uint8_t v
= base64_decode_table
[c
];
2689 /* This character isn't allowed in base64. */
2692 /* This character is whitespace, and has no effect. */
2695 /* We've hit an = character: the data is over. */
2698 /* We have an actual 6-bit value. Append it to the bits in n. */
2700 if ((++n_idx
) == 4) {
2701 /* We've accumulated 24 bits in n. Flush them. */
2703 *dest
++ = (n
>>8) & 0xff;
2704 *dest
++ = (n
) & 0xff;
2711 /* If we have leftover bits, we need to cope. */
2715 /* No leftover bits. We win. */
2718 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2721 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2725 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2730 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2731 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2733 return (int)(dest
-dest_orig
);
2739 /** Base64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2740 * characters, and store the nul-terminated result in the first
2741 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2743 digest_to_base64(char *d64
, const char *digest
)
2746 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
, 0);
2747 buf
[BASE64_DIGEST_LEN
] = '\0';
2748 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2752 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2753 * trailing newline or = characters), decode it and store the result in the
2754 * first DIGEST_LEN bytes at <b>digest</b>. */
2756 digest_from_base64(char *digest
, const char *d64
)
2758 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2764 /** Base64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2765 * trailing = characters, and store the nul-terminated result in the first
2766 * BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2768 digest256_to_base64(char *d64
, const char *digest
)
2771 base64_encode(buf
, sizeof(buf
), digest
, DIGEST256_LEN
, 0);
2772 buf
[BASE64_DIGEST256_LEN
] = '\0';
2773 memcpy(d64
, buf
, BASE64_DIGEST256_LEN
+1);
2777 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2778 * trailing newline or = characters), decode it and store the result in the
2779 * first DIGEST256_LEN bytes at <b>digest</b>. */
2781 digest256_from_base64(char *digest
, const char *d64
)
2783 if (base64_decode(digest
, DIGEST256_LEN
, d64
, strlen(d64
)) == DIGEST256_LEN
)
2789 /** Implements base32 encoding as in RFC 4648. Limitation: Requires
2790 * that srclen*8 is a multiple of 5.
2793 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2795 unsigned int i
, v
, u
;
2796 size_t nbits
= srclen
* 8, bit
;
2798 tor_assert(srclen
< SIZE_T_CEILING
/8);
2799 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2800 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2801 tor_assert(destlen
< SIZE_T_CEILING
);
2803 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2804 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2805 v
= ((uint8_t)src
[bit
/8]) << 8;
2806 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2807 /* set u to the 5-bit value at the bit'th bit of src. */
2808 u
= (v
>> (11-(bit
%8))) & 0x1F;
2809 dest
[i
] = BASE32_CHARS
[u
];
2814 /** Implements base32 decoding as in RFC 4648. Limitation: Requires
2815 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2818 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2820 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2821 * it ever shows up in the profile. */
2823 size_t nbits
, j
, bit
;
2827 tor_assert(srclen
< SIZE_T_CEILING
/ 5);
2828 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2829 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2830 tor_assert(destlen
< SIZE_T_CEILING
);
2832 memset(dest
, 0, destlen
);
2834 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2835 tmp
= tor_malloc_zero(srclen
);
2836 for (j
= 0; j
< srclen
; ++j
) {
2837 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2838 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2839 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2841 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2847 /* Assemble result byte-wise by applying five possible cases. */
2848 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2851 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2852 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2855 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2856 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2857 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2860 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2861 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2864 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2865 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2866 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2869 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2870 ((uint8_t)tmp
[(bit
/5)+1]);
2875 memwipe(tmp
, 0, srclen
);
2882 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
2883 * the value <b>byte</b>.
2885 * This function is preferable to memset, since many compilers will happily
2886 * optimize out memset() when they can convince themselves that the data being
2887 * cleared will never be read.
2889 * Right now, our convention is to use this function when we are wiping data
2890 * that's about to become inaccessible, such as stack buffers that are about
2891 * to go out of scope or structures that are about to get freed. (In
2892 * practice, it appears that the compilers we're currently using will optimize
2893 * out the memset()s for stack-allocated buffers, but not those for
2894 * about-to-be-freed structures. That could change, though, so we're being
2895 * wary.) If there are live reads for the data, then you can just use
2899 memwipe(void *mem
, uint8_t byte
, size_t sz
)
2901 /* Because whole-program-optimization exists, we may not be able to just
2902 * have this function call "memset". A smart compiler could inline it, then
2903 * eliminate dead memsets, and declare itself to be clever. */
2905 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
2906 * based on the pointer value, then uses that junk to update a global
2907 * variable. It's an elaborate ruse to trick the compiler into not
2908 * optimizing out the "wipe this memory" code. Read it if you like zany
2909 * programming tricks! In later versions of Tor, we should look for better
2910 * not-optimized-out memory wiping stuff. */
2911 OPENSSL_cleanse(mem
, sz
);
2912 /* Just in case some caller of memwipe() is relying on getting a buffer
2913 * filled with a particular value, fill the buffer.
2915 * If this function gets inlined, this memset might get eliminated, but
2916 * that's okay: We only care about this particular memset in the case where
2917 * the caller should have been using memset(), and the memset() wouldn't get
2918 * eliminated. In other words, this is here so that we won't break anything
2919 * if somebody accidentally calls memwipe() instead of memset().
2921 memset(mem
, byte
, sz
);
2924 #ifndef OPENSSL_THREADS
2925 #error OpenSSL has been built without thread support. Tor requires an \
2926 OpenSSL library with thread support enabled.
2929 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2931 openssl_locking_cb_(int mode
, int n
, const char *file
, int line
)
2935 if (!openssl_mutexes_
)
2936 /* This is not a really good fix for the
2937 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2940 if (mode
& CRYPTO_LOCK
)
2941 tor_mutex_acquire(openssl_mutexes_
[n
]);
2943 tor_mutex_release(openssl_mutexes_
[n
]);
2946 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2948 struct CRYPTO_dynlock_value
{
2952 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2953 * documentation in OpenSSL's docs for more info. */
2954 static struct CRYPTO_dynlock_value
*
2955 openssl_dynlock_create_cb_(const char *file
, int line
)
2957 struct CRYPTO_dynlock_value
*v
;
2960 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
2961 v
->lock
= tor_mutex_new();
2965 /** OpenSSL callback function to acquire or release a lock: see
2966 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2968 openssl_dynlock_lock_cb_(int mode
, struct CRYPTO_dynlock_value
*v
,
2969 const char *file
, int line
)
2973 if (mode
& CRYPTO_LOCK
)
2974 tor_mutex_acquire(v
->lock
);
2976 tor_mutex_release(v
->lock
);
2979 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2980 * documentation in OpenSSL's docs for more info. */
2982 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value
*v
,
2983 const char *file
, int line
)
2987 tor_mutex_free(v
->lock
);
2991 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0)
2993 tor_set_openssl_thread_id(CRYPTO_THREADID
*threadid
)
2995 CRYPTO_THREADID_set_numeric(threadid
, tor_get_thread_id());
3000 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3003 setup_openssl_threading(void)
3006 int n
= CRYPTO_num_locks();
3007 n_openssl_mutexes_
= n
;
3008 openssl_mutexes_
= tor_calloc(n
, sizeof(tor_mutex_t
*));
3009 for (i
=0; i
< n
; ++i
)
3010 openssl_mutexes_
[i
] = tor_mutex_new();
3011 CRYPTO_set_locking_callback(openssl_locking_cb_
);
3012 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,0,0)
3013 CRYPTO_set_id_callback(tor_get_thread_id
);
3015 CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id
);
3017 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_
);
3018 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_
);
3019 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_
);
3023 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3026 crypto_global_cleanup(void)
3029 ERR_remove_state(0);
3033 BN_clear_free(dh_param_p
);
3035 BN_clear_free(dh_param_p_tls
);
3037 BN_clear_free(dh_param_g
);
3039 #ifndef DISABLE_ENGINES
3043 CONF_modules_unload(1);
3044 CRYPTO_cleanup_all_ex_data();
3046 if (n_openssl_mutexes_
) {
3047 int n
= n_openssl_mutexes_
;
3048 tor_mutex_t
**ms
= openssl_mutexes_
;
3050 openssl_mutexes_
= NULL
;
3051 n_openssl_mutexes_
= 0;
3053 tor_mutex_free(ms
[i
]);
3058 tor_free(crypto_openssl_version_str
);
3059 tor_free(crypto_openssl_header_version_str
);