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.
17 #define WIN32_WINNT 0x400
20 #define _WIN32_WINNT 0x400
22 #define WIN32_LEAN_AND_MEAN
25 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
26 * use either definition. */
30 #include <openssl/err.h>
31 #include <openssl/rsa.h>
32 #include <openssl/pem.h>
33 #include <openssl/evp.h>
34 #include <openssl/engine.h>
35 #include <openssl/rand.h>
36 #include <openssl/opensslv.h>
37 #include <openssl/bn.h>
38 #include <openssl/dh.h>
39 #include <openssl/conf.h>
40 #include <openssl/hmac.h>
51 #ifdef HAVE_SYS_FCNTL_H
52 #include <sys/fcntl.h>
55 #define CRYPTO_PRIVATE
57 #include "../common/torlog.h"
59 #include "../common/util.h"
60 #include "container.h"
63 #if OPENSSL_VERSION_NUMBER < 0x00907000l
64 #error "We require OpenSSL >= 0.9.7"
68 /* Android's OpenSSL seems to have removed all of its Engine support. */
69 #define DISABLE_ENGINES
72 #if OPENSSL_VERSION_NUMBER < 0x00908000l
74 /** On OpenSSL versions before 0.9.8, there is no working SHA256
75 * implementation, so we use Tom St Denis's nice speedy one, slightly adapted
76 * to our needs. These macros make it usable by us. */
77 #define SHA256_CTX sha256_state
78 #define SHA256_Init sha256_init
79 #define SHA256_Update sha256_process
80 #define LTC_ARGCHK(x) tor_assert(x)
83 #define SHA256_Final(a,b) sha256_done(b,a)
85 static unsigned char *
86 SHA256(const unsigned char *m
, size_t len
, unsigned char *d
)
90 SHA256_Update(&ctx
, m
, len
);
91 SHA256_Final(d
, &ctx
);
96 /** Macro: is k a valid RSA public or private key? */
97 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
98 /** Macro: is k a valid RSA private key? */
99 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
101 #ifdef TOR_IS_MULTITHREADED
102 /** A number of preallocated mutexes for use by OpenSSL. */
103 static tor_mutex_t
**_openssl_mutexes
= NULL
;
104 /** How many mutexes have we allocated for use by OpenSSL? */
105 static int _n_openssl_mutexes
= 0;
108 /** A public key, or a public/private key-pair. */
109 struct crypto_pk_env_t
111 int refs
; /**< reference count, so we don't have to copy keys */
112 RSA
*key
; /**< The key itself */
115 /** Key and stream information for a stream cipher. */
116 struct crypto_cipher_env_t
118 char key
[CIPHER_KEY_LEN
]; /**< The raw key. */
119 aes_cnt_cipher_t
*cipher
; /**< The key in format usable for counter-mode AES
123 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
124 * while we're waiting for the second.*/
125 struct crypto_dh_env_t
{
126 DH
*dh
; /**< The openssl DH object */
129 static int setup_openssl_threading(void);
130 static int tor_check_dh_key(int severity
, BIGNUM
*bn
);
132 /** Return the number of bytes added by padding method <b>padding</b>.
135 crypto_get_rsa_padding_overhead(int padding
)
139 case RSA_NO_PADDING
: return 0;
140 case RSA_PKCS1_OAEP_PADDING
: return 42;
141 case RSA_PKCS1_PADDING
: return 11;
142 default: tor_assert(0); return -1;
146 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
149 crypto_get_rsa_padding(int padding
)
153 case PK_NO_PADDING
: return RSA_NO_PADDING
;
154 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
155 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
156 default: tor_assert(0); return -1;
160 /** Boolean: has OpenSSL's crypto been initialized? */
161 static int _crypto_global_initialized
= 0;
163 /** Log all pending crypto errors at level <b>severity</b>. Use
164 * <b>doing</b> to describe our current activities.
167 crypto_log_errors(int severity
, const char *doing
)
170 const char *msg
, *lib
, *func
;
171 while ((err
= ERR_get_error()) != 0) {
172 msg
= (const char*)ERR_reason_error_string(err
);
173 lib
= (const char*)ERR_lib_error_string(err
);
174 func
= (const char*)ERR_func_error_string(err
);
175 if (!msg
) msg
= "(null)";
176 if (!lib
) lib
= "(null)";
177 if (!func
) func
= "(null)";
179 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
180 doing
, msg
, lib
, func
);
182 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
187 #ifndef DISABLE_ENGINES
188 /** Log any OpenSSL engines we're using at NOTICE. */
190 log_engine(const char *fn
, ENGINE
*e
)
193 const char *name
, *id
;
194 name
= ENGINE_get_name(e
);
195 id
= ENGINE_get_id(e
);
196 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
197 name
?name
:"?", id
?id
:"?", fn
);
199 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
204 #ifndef DISABLE_ENGINES
205 /** Try to load an engine in a shared library via fully qualified path.
208 try_load_engine(const char *path
, const char *engine
)
210 ENGINE
*e
= ENGINE_by_id("dynamic");
212 if (!ENGINE_ctrl_cmd_string(e
, "ID", engine
, 0) ||
213 !ENGINE_ctrl_cmd_string(e
, "DIR_LOAD", "2", 0) ||
214 !ENGINE_ctrl_cmd_string(e
, "DIR_ADD", path
, 0) ||
215 !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
224 /** Initialize the crypto library. Return 0 on success, -1 on failure.
227 crypto_global_init(int useAccel
, const char *accelName
, const char *accelDir
,
230 if (!_crypto_global_initialized
) {
231 ERR_load_crypto_strings();
232 OpenSSL_add_all_algorithms();
233 _crypto_global_initialized
= 1;
234 setup_openssl_threading();
235 use_dynamic_primes
= DynamicPrimes
;
237 #ifdef DISABLE_ENGINES
240 log_warn(LD_CRYPTO
, "No OpenSSL hardware acceleration support enabled.");
244 log_info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
245 ENGINE_load_builtin_engines();
246 ENGINE_register_all_complete();
250 log_info(LD_CRYPTO
, "Trying to load dynamic OpenSSL engine \"%s\""
251 " via path \"%s\".", accelName
, accelDir
);
252 e
= try_load_engine(accelName
, accelDir
);
254 log_info(LD_CRYPTO
, "Initializing dynamic OpenSSL engine \"%s\""
255 " acceleration support.", accelName
);
256 e
= ENGINE_by_id(accelName
);
259 log_warn(LD_CRYPTO
, "Unable to load dynamic OpenSSL engine \"%s\".",
262 log_info(LD_CRYPTO
, "Loaded dynamic OpenSSL engine \"%s\".",
267 log_info(LD_CRYPTO
, "Loaded OpenSSL hardware acceleration engine,"
268 " setting default ciphers.");
269 ENGINE_set_default(e
, ENGINE_METHOD_ALL
);
271 log_engine("RSA", ENGINE_get_default_RSA());
272 log_engine("DH", ENGINE_get_default_DH());
273 log_engine("RAND", ENGINE_get_default_RAND());
274 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
275 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
276 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
279 log_info(LD_CRYPTO
, "NOT using OpenSSL engine support.");
281 return crypto_seed_rng(1);
286 /** Free crypto resources held by this thread. */
288 crypto_thread_cleanup(void)
293 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
296 crypto_global_cleanup(void)
302 #ifndef DISABLE_ENGINES
306 CONF_modules_unload(1);
307 CRYPTO_cleanup_all_ex_data();
308 #ifdef TOR_IS_MULTITHREADED
309 if (_n_openssl_mutexes
) {
310 int n
= _n_openssl_mutexes
;
311 tor_mutex_t
**ms
= _openssl_mutexes
;
313 _openssl_mutexes
= NULL
;
314 _n_openssl_mutexes
= 0;
316 tor_mutex_free(ms
[i
]);
324 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
326 _crypto_new_pk_env_rsa(RSA
*rsa
)
328 crypto_pk_env_t
*env
;
330 env
= tor_malloc(sizeof(crypto_pk_env_t
));
336 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
337 * crypto_pk_env_t. */
339 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
344 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
345 * private is set, include the private-key portion of the key. */
347 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
350 EVP_PKEY
*pkey
= NULL
;
351 tor_assert(env
->key
);
353 if (!(key
= RSAPrivateKey_dup(env
->key
)))
356 if (!(key
= RSAPublicKey_dup(env
->key
)))
359 if (!(pkey
= EVP_PKEY_new()))
361 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
372 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
375 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
380 /** Allocate and return storage for a public key. The key itself will not yet
384 crypto_new_pk_env(void)
390 return _crypto_new_pk_env_rsa(rsa
);
393 /** Release a reference to an asymmetric key; when all the references
394 * are released, free the key.
397 crypto_free_pk_env(crypto_pk_env_t
*env
)
404 tor_assert(env
->refs
== 0);
412 /** Create a new symmetric cipher for a given key and encryption flag
413 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
416 crypto_cipher_env_t
*
417 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
420 crypto_cipher_env_t
*crypto
= NULL
;
422 if (! (crypto
= crypto_new_cipher_env())) {
423 log_warn(LD_CRYPTO
, "Unable to allocate crypto object");
427 crypto_cipher_set_key(crypto
, key
);
430 r
= crypto_cipher_encrypt_init_cipher(crypto
);
432 r
= crypto_cipher_decrypt_init_cipher(crypto
);
440 crypto_free_cipher_env(crypto
);
444 /** Allocate and return a new symmetric cipher.
446 crypto_cipher_env_t
*
447 crypto_new_cipher_env(void)
449 crypto_cipher_env_t
*env
;
451 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
452 env
->cipher
= aes_new_cipher();
456 /** Free a symmetric cipher.
459 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
464 tor_assert(env
->cipher
);
465 aes_free_cipher(env
->cipher
);
466 memset(env
, 0, sizeof(crypto_cipher_env_t
));
470 /* public key crypto */
472 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
473 * Return 0 on success, -1 on failure.
476 crypto_pk_generate_key_with_bits(crypto_pk_env_t
*env
, int bits
)
482 #if OPENSSL_VERSION_NUMBER < 0x00908000l
483 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
484 env
->key
= RSA_generate_key(bits
, 65537, NULL
, NULL
);
486 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
488 BIGNUM
*e
= BN_new();
492 if (! BN_set_word(e
, 65537))
497 if (RSA_generate_key_ex(r
, bits
, e
, NULL
) == -1)
510 crypto_log_errors(LOG_WARN
, "generating RSA key");
517 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
518 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
519 * the string is nul-terminated.
521 /* Used here, and used for testing. */
523 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
524 const char *s
, ssize_t len
)
530 tor_assert(len
< INT_MAX
&& len
< SSIZE_T_CEILING
);
532 /* Create a read-only memory BIO, backed by the string 's' */
533 b
= BIO_new_mem_buf((char*)s
, (int)len
);
540 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
545 crypto_log_errors(LOG_WARN
, "Error parsing private key");
551 /** Read a PEM-encoded private key from the file named by
552 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
555 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
561 /* Read the file into a string. */
562 contents
= read_file_to_str(keyfile
, 0, NULL
);
564 log_warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
568 /* Try to parse it. */
569 r
= crypto_pk_read_private_key_from_string(env
, contents
, -1);
570 memset(contents
, 0, strlen(contents
));
573 return -1; /* read_private_key_from_string already warned, so we don't.*/
575 /* Make sure it's valid. */
576 if (crypto_pk_check_key(env
) <= 0)
582 /** Helper function to implement crypto_pk_write_*_key_to_string. */
584 crypto_pk_write_key_to_string_impl(crypto_pk_env_t
*env
, char **dest
,
585 size_t *len
, int is_public
)
592 tor_assert(env
->key
);
595 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
599 /* Now you can treat b as if it were a file. Just use the
600 * PEM_*_bio_* functions instead of the non-bio variants.
603 r
= PEM_write_bio_RSAPublicKey(b
, env
->key
);
605 r
= PEM_write_bio_RSAPrivateKey(b
, env
->key
, NULL
,NULL
,0,NULL
,NULL
);
608 crypto_log_errors(LOG_WARN
, "writing RSA key to string");
613 BIO_get_mem_ptr(b
, &buf
);
614 (void)BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
617 *dest
= tor_malloc(buf
->length
+1);
618 memcpy(*dest
, buf
->data
, buf
->length
);
619 (*dest
)[buf
->length
] = 0; /* nul terminate it */
626 /** PEM-encode the public key portion of <b>env</b> and write it to a
627 * newly allocated string. On success, set *<b>dest</b> to the new
628 * string, *<b>len</b> to the string's length, and return 0. On
629 * failure, return -1.
632 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
635 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 1);
638 /** PEM-encode the private key portion of <b>env</b> and write it to a
639 * newly allocated string. On success, set *<b>dest</b> to the new
640 * string, *<b>len</b> to the string's length, and return 0. On
641 * failure, return -1.
644 crypto_pk_write_private_key_to_string(crypto_pk_env_t
*env
, char **dest
,
647 return crypto_pk_write_key_to_string_impl(env
, dest
, len
, 0);
650 /** Read a PEM-encoded public key from the first <b>len</b> characters of
651 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
655 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
662 tor_assert(len
<INT_MAX
);
664 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
668 BIO_write(b
, src
, (int)len
);
672 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
675 crypto_log_errors(LOG_WARN
, "reading public key from string");
682 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
683 * PEM-encoded. Return 0 on success, -1 on failure.
686 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
695 tor_assert(PRIVATE_KEY_OK(env
));
697 if (!(bio
= BIO_new(BIO_s_mem())))
699 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
701 crypto_log_errors(LOG_WARN
, "writing private key");
705 len
= BIO_get_mem_data(bio
, &cp
);
706 tor_assert(len
>= 0);
707 s
= tor_malloc(len
+1);
710 r
= write_str_to_file(fname
, s
, 0);
712 memset(s
, 0, strlen(s
));
717 /** Return true iff <b>env</b> has a valid key.
720 crypto_pk_check_key(crypto_pk_env_t
*env
)
725 r
= RSA_check_key(env
->key
);
727 crypto_log_errors(LOG_WARN
,"checking RSA key");
731 /** Return true iff <b>key</b> contains the private-key portion of the RSA
734 crypto_pk_key_is_private(const crypto_pk_env_t
*key
)
737 return PRIVATE_KEY_OK(key
);
740 /** Return true iff <b>env</b> contains a public key whose public exponent
744 crypto_pk_public_exponent_ok(crypto_pk_env_t
*env
)
747 tor_assert(env
->key
);
749 return BN_is_word(env
->key
->e
, 65537);
752 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
753 * if a==b, and 1 if a\>b.
756 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
763 if (!a
->key
|| !b
->key
)
766 tor_assert(PUBLIC_KEY_OK(a
));
767 tor_assert(PUBLIC_KEY_OK(b
));
768 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
771 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
774 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
776 crypto_pk_keysize(crypto_pk_env_t
*env
)
779 tor_assert(env
->key
);
781 return (size_t) RSA_size(env
->key
);
784 /** Return the size of the public key modulus of <b>env</b>, in bits. */
786 crypto_pk_num_bits(crypto_pk_env_t
*env
)
789 tor_assert(env
->key
);
790 tor_assert(env
->key
->n
);
792 return BN_num_bits(env
->key
->n
);
795 /** Increase the reference count of <b>env</b>, and return it.
798 crypto_pk_dup_key(crypto_pk_env_t
*env
)
801 tor_assert(env
->key
);
807 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
809 crypto_pk_copy_full(crypto_pk_env_t
*env
)
814 tor_assert(env
->key
);
816 if (PRIVATE_KEY_OK(env
)) {
817 new_key
= RSAPrivateKey_dup(env
->key
);
820 new_key
= RSAPublicKey_dup(env
->key
);
823 log_err(LD_CRYPTO
, "Unable to duplicate a %s key: openssl failed.",
824 privatekey
?"private":"public");
825 crypto_log_errors(LOG_ERR
,
826 privatekey
? "Duplicating a private key" :
827 "Duplicating a public key");
828 tor_fragile_assert();
832 return _crypto_new_pk_env_rsa(new_key
);
835 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
836 * in <b>env</b>, using the padding method <b>padding</b>. On success,
837 * write the result to <b>to</b>, and return the number of bytes
838 * written. On failure, return -1.
840 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
841 * at least the length of the modulus of <b>env</b>.
844 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
845 const char *from
, size_t fromlen
, int padding
)
851 tor_assert(fromlen
<INT_MAX
);
852 tor_assert(tolen
>= crypto_pk_keysize(env
));
854 r
= RSA_public_encrypt((int)fromlen
,
855 (unsigned char*)from
, (unsigned char*)to
,
856 env
->key
, crypto_get_rsa_padding(padding
));
858 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
864 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
865 * in <b>env</b>, using the padding method <b>padding</b>. On success,
866 * write the result to <b>to</b>, and return the number of bytes
867 * written. On failure, return -1.
869 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
870 * at least the length of the modulus of <b>env</b>.
873 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
875 const char *from
, size_t fromlen
,
876 int padding
, int warnOnFailure
)
882 tor_assert(env
->key
);
883 tor_assert(fromlen
<INT_MAX
);
884 tor_assert(tolen
>= crypto_pk_keysize(env
));
886 /* Not a private key */
889 r
= RSA_private_decrypt((int)fromlen
,
890 (unsigned char*)from
, (unsigned char*)to
,
891 env
->key
, crypto_get_rsa_padding(padding
));
894 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
895 "performing RSA decryption");
901 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
902 * public key in <b>env</b>, using PKCS1 padding. On success, write the
903 * signed data to <b>to</b>, and return the number of bytes written.
904 * On failure, return -1.
906 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
907 * at least the length of the modulus of <b>env</b>.
910 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
912 const char *from
, size_t fromlen
)
918 tor_assert(fromlen
< INT_MAX
);
919 tor_assert(tolen
>= crypto_pk_keysize(env
));
920 r
= RSA_public_decrypt((int)fromlen
,
921 (unsigned char*)from
, (unsigned char*)to
,
922 env
->key
, RSA_PKCS1_PADDING
);
925 crypto_log_errors(LOG_WARN
, "checking RSA signature");
931 /** Check a siglen-byte long signature at <b>sig</b> against
932 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
933 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
934 * SHA1(data). Else return -1.
937 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
938 size_t datalen
, const char *sig
, size_t siglen
)
940 char digest
[DIGEST_LEN
];
948 tor_assert(datalen
< SIZE_T_CEILING
);
949 tor_assert(siglen
< SIZE_T_CEILING
);
951 if (crypto_digest(digest
,data
,datalen
)<0) {
952 log_warn(LD_BUG
, "couldn't compute digest");
955 buflen
= crypto_pk_keysize(env
);
956 buf
= tor_malloc(buflen
);
957 r
= crypto_pk_public_checksig(env
,buf
,buflen
,sig
,siglen
);
958 if (r
!= DIGEST_LEN
) {
959 log_warn(LD_CRYPTO
, "Invalid signature");
963 if (tor_memneq(buf
, digest
, DIGEST_LEN
)) {
964 log_warn(LD_CRYPTO
, "Signature mismatched with digest.");
973 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
974 * <b>env</b>, using PKCS1 padding. On success, write the signature to
975 * <b>to</b>, and return the number of bytes written. On failure, return
978 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
979 * at least the length of the modulus of <b>env</b>.
982 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
983 const char *from
, size_t fromlen
)
989 tor_assert(fromlen
< INT_MAX
);
990 tor_assert(tolen
>= crypto_pk_keysize(env
));
992 /* Not a private key */
995 r
= RSA_private_encrypt((int)fromlen
,
996 (unsigned char*)from
, (unsigned char*)to
,
997 env
->key
, RSA_PKCS1_PADDING
);
999 crypto_log_errors(LOG_WARN
, "generating RSA signature");
1005 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1006 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1007 * store it in <b>to</b>. Return the number of bytes written on
1008 * success, and -1 on failure.
1010 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1011 * at least the length of the modulus of <b>env</b>.
1014 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
, size_t tolen
,
1015 const char *from
, size_t fromlen
)
1018 char digest
[DIGEST_LEN
];
1019 if (crypto_digest(digest
,from
,fromlen
)<0)
1021 r
= crypto_pk_private_sign(env
,to
,tolen
,digest
,DIGEST_LEN
);
1022 memset(digest
, 0, sizeof(digest
));
1026 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1027 * bytes of data from <b>from</b>, with padding type 'padding',
1028 * storing the results on <b>to</b>.
1030 * If no padding is used, the public key must be at least as large as
1033 * Returns the number of bytes written on success, -1 on failure.
1035 * The encrypted data consists of:
1036 * - The source data, padded and encrypted with the public key, if the
1037 * padded source data is no longer than the public key, and <b>force</b>
1039 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1040 * padded and encrypted with the public key; followed by the rest of
1041 * the source data encrypted in AES-CTR mode with the symmetric key.
1044 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
1045 char *to
, size_t tolen
,
1048 int padding
, int force
)
1050 int overhead
, outlen
, r
;
1051 size_t pkeylen
, symlen
;
1052 crypto_cipher_env_t
*cipher
= NULL
;
1058 tor_assert(fromlen
< SIZE_T_CEILING
);
1060 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
1061 pkeylen
= crypto_pk_keysize(env
);
1063 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
1066 if (!force
&& fromlen
+overhead
<= pkeylen
) {
1067 /* It all fits in a single encrypt. */
1068 return crypto_pk_public_encrypt(env
,to
,
1070 from
,fromlen
,padding
);
1072 tor_assert(tolen
>= fromlen
+ overhead
+ CIPHER_KEY_LEN
);
1073 tor_assert(tolen
>= pkeylen
);
1075 cipher
= crypto_new_cipher_env();
1076 if (!cipher
) return -1;
1077 if (crypto_cipher_generate_key(cipher
)<0)
1079 /* You can't just run around RSA-encrypting any bitstream: if it's
1080 * greater than the RSA key, then OpenSSL will happily encrypt, and
1081 * later decrypt to the wrong value. So we set the first bit of
1082 * 'cipher->key' to 0 if we aren't padding. This means that our
1083 * symmetric key is really only 127 bits.
1085 if (padding
== PK_NO_PADDING
)
1086 cipher
->key
[0] &= 0x7f;
1087 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
1089 buf
= tor_malloc(pkeylen
+1);
1090 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
1091 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
1093 /* Length of symmetrically encrypted data. */
1094 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
1096 outlen
= crypto_pk_public_encrypt(env
,to
,tolen
,buf
,pkeylen
-overhead
,padding
);
1097 if (outlen
!=(int)pkeylen
) {
1100 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
1101 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
1104 memset(buf
, 0, pkeylen
);
1106 crypto_free_cipher_env(cipher
);
1107 tor_assert(outlen
+symlen
< INT_MAX
);
1108 return (int)(outlen
+ symlen
);
1111 memset(buf
, 0, pkeylen
);
1114 if (cipher
) crypto_free_cipher_env(cipher
);
1118 /** Invert crypto_pk_public_hybrid_encrypt. */
1120 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
1125 int padding
, int warnOnFailure
)
1129 crypto_cipher_env_t
*cipher
= NULL
;
1132 tor_assert(fromlen
< SIZE_T_CEILING
);
1133 pkeylen
= crypto_pk_keysize(env
);
1135 if (fromlen
<= pkeylen
) {
1136 return crypto_pk_private_decrypt(env
,to
,tolen
,from
,fromlen
,padding
,
1140 buf
= tor_malloc(pkeylen
);
1141 outlen
= crypto_pk_private_decrypt(env
,buf
,pkeylen
,from
,pkeylen
,padding
,
1144 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
1145 "Error decrypting public-key data");
1148 if (outlen
< CIPHER_KEY_LEN
) {
1149 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
1150 "No room for a symmetric key");
1153 cipher
= crypto_create_init_cipher(buf
, 0);
1157 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
1158 outlen
-= CIPHER_KEY_LEN
;
1159 tor_assert(tolen
- outlen
>= fromlen
- pkeylen
);
1160 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
1163 memset(buf
,0,pkeylen
);
1165 crypto_free_cipher_env(cipher
);
1166 tor_assert(outlen
+ fromlen
< INT_MAX
);
1167 return (int)(outlen
+ (fromlen
-pkeylen
));
1169 memset(buf
,0,pkeylen
);
1171 if (cipher
) crypto_free_cipher_env(cipher
);
1175 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1176 * Return -1 on error, or the number of characters used on success.
1179 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, size_t dest_len
)
1182 unsigned char *buf
, *cp
;
1183 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1184 if (len
< 0 || (size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
)
1186 cp
= buf
= tor_malloc(len
+1);
1187 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1189 crypto_log_errors(LOG_WARN
,"encoding public key");
1193 /* We don't encode directly into 'dest', because that would be illegal
1194 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1196 memcpy(dest
,buf
,len
);
1201 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1202 * success and NULL on failure.
1205 crypto_pk_asn1_decode(const char *str
, size_t len
)
1209 const unsigned char *cp
;
1210 cp
= buf
= tor_malloc(len
);
1211 memcpy(buf
,str
,len
);
1212 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1215 crypto_log_errors(LOG_WARN
,"decoding public key");
1218 return _crypto_new_pk_env_rsa(rsa
);
1221 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1222 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1223 * Return 0 on success, -1 on failure.
1226 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1228 unsigned char *buf
, *bufp
;
1231 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1234 buf
= bufp
= tor_malloc(len
+1);
1235 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1237 crypto_log_errors(LOG_WARN
,"encoding public key");
1241 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1249 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1250 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1252 crypto_pk_get_all_digests(crypto_pk_env_t
*pk
, digests_t
*digests_out
)
1254 unsigned char *buf
, *bufp
;
1257 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1260 buf
= bufp
= tor_malloc(len
+1);
1261 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1263 crypto_log_errors(LOG_WARN
,"encoding public key");
1267 if (crypto_digest_all(digests_out
, (char*)buf
, len
) < 0) {
1275 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1276 * every four spaces. */
1278 add_spaces_to_fp(char *out
, size_t outlen
, const char *in
)
1281 char *end
= out
+outlen
;
1282 tor_assert(outlen
< SIZE_T_CEILING
);
1284 while (*in
&& out
<end
) {
1286 if (++n
== 4 && *in
&& out
<end
) {
1291 tor_assert(out
<end
);
1295 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1296 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1297 * space). Return 0 on success, -1 on failure.
1299 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1300 * of the public key, converted to hexadecimal, in upper case, with a
1301 * space after every four digits.
1303 * If <b>add_space</b> is false, omit the spaces.
1306 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1308 char digest
[DIGEST_LEN
];
1309 char hexdigest
[HEX_DIGEST_LEN
+1];
1310 if (crypto_pk_get_digest(pk
, digest
)) {
1313 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1315 add_spaces_to_fp(fp_out
, FINGERPRINT_LEN
+1, hexdigest
);
1317 strncpy(fp_out
, hexdigest
, HEX_DIGEST_LEN
+1);
1322 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1325 crypto_pk_check_fingerprint_syntax(const char *s
)
1328 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1330 if (!TOR_ISSPACE(s
[i
])) return 0;
1332 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1335 if (s
[FINGERPRINT_LEN
]) return 0;
1339 /* symmetric crypto */
1341 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1342 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1345 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1349 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1352 /** Set the symmetric key for the cipher in <b>env</b> to the first
1353 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1356 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1361 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1364 /** Generate an initialization vector for our AES-CTR cipher; store it
1365 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1367 crypto_cipher_generate_iv(char *iv_out
)
1369 crypto_rand(iv_out
, CIPHER_IV_LEN
);
1372 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1373 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1376 crypto_cipher_set_iv(crypto_cipher_env_t
*env
, const char *iv
)
1380 aes_set_iv(env
->cipher
, iv
);
1384 /** Return a pointer to the key set for the cipher in <b>env</b>.
1387 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1392 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1393 * success, -1 on failure.
1396 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1400 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1404 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1405 * success, -1 on failure.
1408 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1412 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1416 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1417 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1418 * On failure, return -1.
1421 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1422 const char *from
, size_t fromlen
)
1425 tor_assert(env
->cipher
);
1427 tor_assert(fromlen
);
1429 tor_assert(fromlen
< SIZE_T_CEILING
);
1431 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1435 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1436 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1437 * On failure, return -1.
1440 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1441 const char *from
, size_t fromlen
)
1446 tor_assert(fromlen
< SIZE_T_CEILING
);
1448 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1452 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1453 * on success, return 0. On failure, return -1.
1456 crypto_cipher_crypt_inplace(crypto_cipher_env_t
*env
, char *buf
, size_t len
)
1458 tor_assert(len
< SIZE_T_CEILING
);
1459 aes_crypt_inplace(env
->cipher
, buf
, len
);
1463 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1464 * <b>cipher</b> to the buffer in <b>to</b> of length
1465 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1466 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1467 * number of bytes written, on failure, return -1.
1469 * This function adjusts the current position of the counter in <b>cipher</b>
1470 * to immediately after the encrypted data.
1473 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t
*cipher
,
1474 char *to
, size_t tolen
,
1475 const char *from
, size_t fromlen
)
1480 tor_assert(fromlen
< INT_MAX
);
1484 if (tolen
< fromlen
+ CIPHER_IV_LEN
)
1487 crypto_cipher_generate_iv(to
);
1488 if (crypto_cipher_set_iv(cipher
, to
)<0)
1490 crypto_cipher_encrypt(cipher
, to
+CIPHER_IV_LEN
, from
, fromlen
);
1491 return (int)(fromlen
+ CIPHER_IV_LEN
);
1494 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1495 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1496 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1497 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1498 * number of bytes written, on failure, return -1.
1500 * This function adjusts the current position of the counter in <b>cipher</b>
1501 * to immediately after the decrypted data.
1504 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t
*cipher
,
1505 char *to
, size_t tolen
,
1506 const char *from
, size_t fromlen
)
1511 tor_assert(fromlen
< INT_MAX
);
1513 if (fromlen
<= CIPHER_IV_LEN
)
1515 if (tolen
< fromlen
- CIPHER_IV_LEN
)
1518 if (crypto_cipher_set_iv(cipher
, from
)<0)
1520 crypto_cipher_encrypt(cipher
, to
, from
+CIPHER_IV_LEN
, fromlen
-CIPHER_IV_LEN
);
1521 return (int)(fromlen
- CIPHER_IV_LEN
);
1526 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1527 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1528 * Return 0 on success, -1 on failure.
1531 crypto_digest(char *digest
, const char *m
, size_t len
)
1535 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1538 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1539 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1540 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1542 crypto_digest256(char *digest
, const char *m
, size_t len
,
1543 digest_algorithm_t algorithm
)
1547 tor_assert(algorithm
== DIGEST_SHA256
);
1548 return (SHA256((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1551 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1552 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1553 * success, -1 on failure. */
1555 crypto_digest_all(digests_t
*ds_out
, const char *m
, size_t len
)
1557 digest_algorithm_t i
;
1559 memset(ds_out
, 0, sizeof(*ds_out
));
1560 if (crypto_digest(ds_out
->d
[DIGEST_SHA1
], m
, len
) < 0)
1562 for (i
= DIGEST_SHA256
; i
< N_DIGEST_ALGORITHMS
; ++i
) {
1563 if (crypto_digest256(ds_out
->d
[i
], m
, len
, i
) < 0)
1569 /** Return the name of an algorithm, as used in directory documents. */
1571 crypto_digest_algorithm_get_name(digest_algorithm_t alg
)
1579 tor_fragile_assert();
1580 return "??unknown_digest??";
1584 /** Given the name of a digest algorithm, return its integer value, or -1 if
1585 * the name is not recognized. */
1587 crypto_digest_algorithm_parse_name(const char *name
)
1589 if (!strcmp(name
, "sha1"))
1591 else if (!strcmp(name
, "sha256"))
1592 return DIGEST_SHA256
;
1597 /** Intermediate information about the digest of a stream of data. */
1598 struct crypto_digest_env_t
{
1600 SHA_CTX sha1
; /**< state for SHA1 */
1601 SHA256_CTX sha2
; /**< state for SHA256 */
1602 } d
; /**< State for the digest we're using. Only one member of the
1603 * union is usable, depending on the value of <b>algorithm</b>. */
1604 digest_algorithm_t algorithm
: 8; /**< Which algorithm is in use? */
1607 /** Allocate and return a new digest object to compute SHA1 digests.
1609 crypto_digest_env_t
*
1610 crypto_new_digest_env(void)
1612 crypto_digest_env_t
*r
;
1613 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1614 SHA1_Init(&r
->d
.sha1
);
1615 r
->algorithm
= DIGEST_SHA1
;
1619 /** Allocate and return a new digest object to compute 256-bit digests
1620 * using <b>algorithm</b>. */
1621 crypto_digest_env_t
*
1622 crypto_new_digest256_env(digest_algorithm_t algorithm
)
1624 crypto_digest_env_t
*r
;
1625 tor_assert(algorithm
== DIGEST_SHA256
);
1626 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1627 SHA256_Init(&r
->d
.sha2
);
1628 r
->algorithm
= algorithm
;
1632 /** Deallocate a digest object.
1635 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1639 memset(digest
, 0, sizeof(crypto_digest_env_t
));
1643 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1646 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1651 /* Using the SHA*_*() calls directly means we don't support doing
1652 * SHA in hardware. But so far the delay of getting the question
1653 * to the hardware, and hearing the answer, is likely higher than
1654 * just doing it ourselves. Hashes are fast.
1656 switch (digest
->algorithm
) {
1658 SHA1_Update(&digest
->d
.sha1
, (void*)data
, len
);
1661 SHA256_Update(&digest
->d
.sha2
, (void*)data
, len
);
1664 tor_fragile_assert();
1669 /** Compute the hash of the data that has been passed to the digest
1670 * object; write the first out_len bytes of the result to <b>out</b>.
1671 * <b>out_len</b> must be \<= DIGEST256_LEN.
1674 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1675 char *out
, size_t out_len
)
1677 unsigned char r
[DIGEST256_LEN
];
1678 crypto_digest_env_t tmpenv
;
1681 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1682 memcpy(&tmpenv
, digest
, sizeof(crypto_digest_env_t
));
1683 switch (digest
->algorithm
) {
1685 tor_assert(out_len
<= DIGEST_LEN
);
1686 SHA1_Final(r
, &tmpenv
.d
.sha1
);
1689 tor_assert(out_len
<= DIGEST256_LEN
);
1690 SHA256_Final(r
, &tmpenv
.d
.sha2
);
1693 log_warn(LD_BUG
, "Called with unknown algorithm %d", digest
->algorithm
);
1694 /* If fragile_assert is not enabled, then we should at least not
1696 memset(r
, 0xff, sizeof(r
));
1697 tor_fragile_assert();
1700 memcpy(out
, r
, out_len
);
1701 memset(r
, 0, sizeof(r
));
1704 /** Allocate and return a new digest object with the same state as
1707 crypto_digest_env_t
*
1708 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1710 crypto_digest_env_t
*r
;
1712 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1713 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1717 /** Replace the state of the digest object <b>into</b> with the state
1718 * of the digest object <b>from</b>.
1721 crypto_digest_assign(crypto_digest_env_t
*into
,
1722 const crypto_digest_env_t
*from
)
1726 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1729 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1730 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1731 * in <b>hmac_out</b>.
1734 crypto_hmac_sha1(char *hmac_out
,
1735 const char *key
, size_t key_len
,
1736 const char *msg
, size_t msg_len
)
1738 tor_assert(key_len
< INT_MAX
);
1739 tor_assert(msg_len
< INT_MAX
);
1740 HMAC(EVP_sha1(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1741 (unsigned char*)hmac_out
, NULL
);
1744 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1745 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1746 * in <b>hmac_out</b>.
1749 crypto_hmac_sha256(char *hmac_out
,
1750 const char *key
, size_t key_len
,
1751 const char *msg
, size_t msg_len
)
1753 #if (OPENSSL_VERSION_NUMBER >= 0x00908000l)
1754 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1755 tor_assert(key_len
< INT_MAX
);
1756 tor_assert(msg_len
< INT_MAX
);
1757 HMAC(EVP_sha256(), key
, (int)key_len
, (unsigned char*)msg
, (int)msg_len
,
1758 (unsigned char*)hmac_out
, NULL
);
1760 /* OpenSSL doesn't have an EVP implementation for SHA256. We'll need
1761 to do HMAC on our own.
1763 HMAC isn't so hard: To compute HMAC(key, msg):
1764 1. If len(key) > blocksize, key = H(key).
1765 2. If len(key) < blocksize, right-pad key up to blocksize with 0 bytes.
1766 3. let ipad = key xor 0x363636363636....36
1767 let opad = key xor 0x5c5c5c5c5c5c....5c
1768 The result is H(opad | H( ipad | msg ) )
1770 #define BLOCKSIZE 64
1771 #define DIGESTSIZE 32
1772 uint8_t k
[BLOCKSIZE
];
1773 uint8_t pad
[BLOCKSIZE
];
1774 uint8_t d
[DIGESTSIZE
];
1778 tor_assert(key_len
< INT_MAX
);
1779 tor_assert(msg_len
< INT_MAX
);
1781 if (key_len
<= BLOCKSIZE
) {
1782 memset(k
, 0, sizeof(k
));
1783 memcpy(k
, key
, key_len
); /* not time invariant in key_len */
1785 SHA256((const uint8_t *)key
, key_len
, k
);
1786 memset(k
+DIGESTSIZE
, 0, sizeof(k
)-DIGESTSIZE
);
1788 for (i
= 0; i
< BLOCKSIZE
; ++i
)
1789 pad
[i
] = k
[i
] ^ 0x36;
1791 SHA256_Update(&st
, pad
, BLOCKSIZE
);
1792 SHA256_Update(&st
, (uint8_t*)msg
, msg_len
);
1793 SHA256_Final(d
, &st
);
1795 for (i
= 0; i
< BLOCKSIZE
; ++i
)
1796 pad
[i
] = k
[i
] ^ 0x5c;
1798 SHA256_Update(&st
, pad
, BLOCKSIZE
);
1799 SHA256_Update(&st
, d
, DIGESTSIZE
);
1800 SHA256_Final((uint8_t*)hmac_out
, &st
);
1802 /* Now clear everything. */
1803 memset(k
, 0, sizeof(k
));
1804 memset(pad
, 0, sizeof(pad
));
1805 memset(d
, 0, sizeof(d
));
1806 memset(&st
, 0, sizeof(st
));
1814 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1815 static BIGNUM
*dh_param_p
= NULL
;
1816 /** Shared P parameter for our TLS DH key exchanges. */
1817 static BIGNUM
*dh_param_p_tls
= NULL
;
1818 /** Shared G parameter for our DH key exchanges. */
1819 static BIGNUM
*dh_param_g
= NULL
;
1820 /** True if we use dynamic primes. */
1821 static int use_dynamic_primes
= 0;
1823 /** Generate and return a reasonable and safe DH parameter p. */
1824 static BIGNUM
*generate_rakshasa_prime(void)
1826 BIGNUM
*rakshasa_prime
, *misc
;
1830 int rakshasa_bits
= RAKSHASA_BITS
;
1831 int generator
= DH_GENERATOR
;
1833 dh_parameters
= DH_new();
1834 rakshasa_prime
= BN_new();
1837 /** XXX - do we want to cache the result in a file? Or perhaps load from a file? */
1838 /* This implements the prime number strategy outlined in prop 179 */
1839 tor_assert(rakshasa_prime
);
1840 log_notice(LD_OR
, "Generating Rakshasa prime; this will take a while...");
1841 dh_parameters
= DH_generate_parameters(rakshasa_bits
, generator
, NULL
, NULL
); // XXX Do we want a pretty call back?
1842 tor_assert(dh_parameters
);
1843 log_notice(LD_OR
, "Rakshasa prime generated!");
1844 log_notice(LD_OR
, "Testing our Rakshasa prime; this will take a while...");
1845 r
= DH_check(dh_parameters
, &dh_codes
);
1847 log_notice(LD_OR
, "Rakshasa prime seems probabilistically reasonable!");
1848 misc
= BN_copy(rakshasa_prime
, dh_parameters
->p
);
1850 DH_free(dh_parameters
);
1852 return rakshasa_prime
;
1855 /** Initialize dh_param_p and dh_param_g if they are not already
1860 BIGNUM
*rakshasa_prime
, *p
, *p2
, *g
;
1862 if (dh_param_p
&& dh_param_g
&& dh_param_p_tls
)
1865 rakshasa_prime
= BN_new();
1869 tor_assert(rakshasa_prime
);
1874 /* Set our generator for all DH parameters */
1875 r
= BN_set_word(g
, generator
);
1878 /* This implements the prime number strategy outlined in prop 179 */
1879 if (use_dynamic_primes
) {
1880 rakshasa_prime
= generate_rakshasa_prime();
1883 /* This is from rfc2409, section 6.2. It's a safe prime, and
1884 supposedly it equals:
1885 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1888 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1889 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1890 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1891 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1892 "49286651ECE65381FFFFFFFFFFFFFFFF");
1894 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1895 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
1899 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1900 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1901 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1902 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1903 "B0E7393E0F24218EB3");
1906 r
= BN_set_word(g
, 2);
1910 dh_param_p_tls
= rakshasa_prime
;
1912 dh_param_p_tls
= p2
;
1917 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
1918 * handshake. Since we exponentiate by this value, choosing a smaller one
1919 * lets our handhake go faster.
1921 #define DH_PRIVATE_KEY_BITS 320
1923 /** Allocate and return a new DH object for a key exchange.
1926 crypto_dh_new(int dh_type
)
1928 crypto_dh_env_t
*res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1930 tor_assert(dh_type
== DH_TYPE_CIRCUIT
|| dh_type
== DH_TYPE_TLS
||
1931 dh_type
== DH_TYPE_REND
);
1936 if (!(res
->dh
= DH_new()))
1939 if (dh_type
== DH_TYPE_TLS
) {
1940 if (!(res
->dh
->p
= BN_dup(dh_param_p_tls
)))
1943 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1947 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1950 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1954 crypto_log_errors(LOG_WARN
, "creating DH object");
1955 if (res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1960 /** Return the length of the DH key in <b>dh</b>, in bytes.
1963 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1966 return DH_size(dh
->dh
);
1969 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1970 * success, -1 on failure.
1973 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1976 if (!DH_generate_key(dh
->dh
)) {
1977 crypto_log_errors(LOG_WARN
, "generating DH key");
1980 if (tor_check_dh_key(LOG_WARN
, dh
->dh
->pub_key
)<0) {
1981 log_warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1982 "the-universe chances really do happen. Trying again.");
1983 /* Free and clear the keys, so OpenSSL will actually try again. */
1984 BN_free(dh
->dh
->pub_key
);
1985 BN_free(dh
->dh
->priv_key
);
1986 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1992 /** Generate g^x as necessary, and write the g^x for the key exchange
1993 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1994 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1997 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
2001 if (!dh
->dh
->pub_key
) {
2002 if (crypto_dh_generate_public(dh
)<0)
2006 tor_assert(dh
->dh
->pub_key
);
2007 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
2008 tor_assert(bytes
>= 0);
2009 if (pubkey_len
< (size_t)bytes
) {
2011 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2012 (int) pubkey_len
, bytes
);
2016 memset(pubkey
, 0, pubkey_len
);
2017 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
2022 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2023 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2024 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2027 tor_check_dh_key(int severity
, BIGNUM
*bn
)
2037 if (BN_cmp(bn
,x
)<=0) {
2038 log_fn(severity
, LD_CRYPTO
, "DH key must be at least 2.");
2041 BN_copy(x
,dh_param_p
);
2043 if (BN_cmp(bn
,x
)>=0) {
2044 log_fn(severity
, LD_CRYPTO
, "DH key must be at most p-2.");
2052 log_fn(severity
, LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
2058 #define MIN(a,b) ((a)<(b)?(a):(b))
2059 /** Given a DH key exchange object, and our peer's value of g^y (as a
2060 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2061 * <b>secret_bytes_out</b> bytes of shared key material and write them
2062 * to <b>secret_out</b>. Return the number of bytes generated on success,
2065 * (We generate key material by computing
2066 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2067 * where || is concatenation.)
2070 crypto_dh_compute_secret(int severity
, crypto_dh_env_t
*dh
,
2071 const char *pubkey
, size_t pubkey_len
,
2072 char *secret_out
, size_t secret_bytes_out
)
2074 char *secret_tmp
= NULL
;
2075 BIGNUM
*pubkey_bn
= NULL
;
2076 size_t secret_len
=0, secret_tmp_len
=0;
2079 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
2080 tor_assert(pubkey_len
< INT_MAX
);
2082 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
,
2083 (int)pubkey_len
, NULL
)))
2085 if (tor_check_dh_key(severity
, pubkey_bn
)<0) {
2086 /* Check for invalid public keys. */
2087 log_fn(severity
, LD_CRYPTO
,"Rejected invalid g^x");
2090 secret_tmp_len
= crypto_dh_get_bytes(dh
);
2091 secret_tmp
= tor_malloc(secret_tmp_len
);
2092 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
2094 log_warn(LD_CRYPTO
,"DH_compute_key() failed.");
2097 secret_len
= result
;
2098 if (crypto_expand_key_material(secret_tmp
, secret_len
,
2099 secret_out
, secret_bytes_out
)<0)
2101 secret_len
= secret_bytes_out
;
2107 crypto_log_errors(LOG_WARN
, "completing DH handshake");
2111 memset(secret_tmp
, 0, secret_tmp_len
);
2112 tor_free(secret_tmp
);
2120 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2121 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2122 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2123 * H(K | [00]) | H(K | [01]) | ....
2125 * Return 0 on success, -1 on failure.
2128 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
2129 char *key_out
, size_t key_out_len
)
2132 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
2133 char digest
[DIGEST_LEN
];
2135 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2136 tor_assert(key_out_len
<= DIGEST_LEN
*256);
2138 memcpy(tmp
, key_in
, key_in_len
);
2139 for (cp
= key_out
, i
=0; cp
< key_out
+key_out_len
;
2140 ++i
, cp
+= DIGEST_LEN
) {
2141 tmp
[key_in_len
] = i
;
2142 if (crypto_digest(digest
, tmp
, key_in_len
+1))
2144 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
-(cp
-key_out
)));
2146 memset(tmp
, 0, key_in_len
+1);
2148 memset(digest
, 0, sizeof(digest
));
2152 memset(tmp
, 0, key_in_len
+1);
2154 memset(digest
, 0, sizeof(digest
));
2158 /** Free a DH key exchange object.
2161 crypto_dh_free(crypto_dh_env_t
*dh
)
2170 /* random numbers */
2172 /** How many bytes of entropy we add at once.
2174 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2175 * work for us too. */
2176 #define ADD_ENTROPY 32
2178 /** True iff we should use OpenSSL's RAND_poll function to add entropy to its
2181 * Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
2183 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
2185 /** True iff it's safe to use RAND_poll after setup.
2187 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2188 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2189 * that fd without checking whether it fit in the fd_set. Thus, if the
2190 * system has not just been started up, it is unsafe to call */
2191 #define RAND_POLL_IS_SAFE \
2192 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
2193 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
2194 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
2196 /** Set the seed of the weak RNG to a random value. */
2201 crypto_rand((void*)&seed
, sizeof(seed
));
2202 tor_init_weak_random(seed
);
2205 /** Seed OpenSSL's random number generator with bytes from the operating
2206 * system. <b>startup</b> should be true iff we have just started Tor and
2207 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2210 crypto_seed_rng(int startup
)
2212 int rand_poll_status
= 0;
2214 /* local variables */
2216 unsigned char buf
[ADD_ENTROPY
];
2217 static int provider_set
= 0;
2218 static HCRYPTPROV provider
;
2220 char buf
[ADD_ENTROPY
];
2221 static const char *filenames
[] = {
2222 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2229 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
2230 * entropy than we do. We'll try calling that, *and* calling our own entropy
2231 * functions. If one succeeds, we'll accept the RNG as seeded. */
2232 if (startup
|| RAND_POLL_IS_SAFE
) {
2233 rand_poll_status
= RAND_poll();
2234 if (rand_poll_status
== 0)
2235 log_warn(LD_CRYPTO
, "RAND_poll() failed.");
2240 if (!provider_set
) {
2241 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
2242 CRYPT_VERIFYCONTEXT
)) {
2243 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET
) {
2244 log_warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
2245 return rand_poll_status
? 0 : -1;
2250 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
2251 log_warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
2252 return rand_poll_status
? 0 : -1;
2254 RAND_seed(buf
, sizeof(buf
));
2255 memset(buf
, 0, sizeof(buf
));
2259 for (i
= 0; filenames
[i
]; ++i
) {
2260 fd
= open(filenames
[i
], O_RDONLY
, 0);
2262 log_info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
2263 n
= read_all(fd
, buf
, sizeof(buf
), 0);
2265 if (n
!= sizeof(buf
)) {
2267 "Error reading from entropy source (read only %lu bytes).",
2271 RAND_seed(buf
, (int)sizeof(buf
));
2272 memset(buf
, 0, sizeof(buf
));
2277 log_warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
2278 return rand_poll_status
? 0 : -1;
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 64-bit integer, chosen uniformly from the values
2321 * between 0 and <b>max</b>-1. */
2323 crypto_rand_uint64(uint64_t max
)
2327 tor_assert(max
< UINT64_MAX
);
2328 tor_assert(max
> 0); /* don't div by 0 */
2330 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2331 * distribution with clipping at the upper end of unsigned int's
2334 cutoff
= UINT64_MAX
- (UINT64_MAX
%max
);
2336 crypto_rand((char*)&val
, sizeof(val
));
2342 /** Return a pseudorandom double d, chosen uniformly from the range
2346 crypto_rand_double(void)
2348 /* We just use an unsigned int here; we don't really care about getting
2349 * more than 32 bits of resolution */
2351 crypto_rand((char*)&uint
, sizeof(uint
));
2353 #define UINT_MAX_AS_DOUBLE 4294967296.0
2354 #elif SIZEOF_INT == 8
2355 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2357 #error SIZEOF_INT is neither 4 nor 8
2359 return ((double)uint
) / UINT_MAX_AS_DOUBLE
;
2362 /** Generate and return a new random hostname starting with <b>prefix</b>,
2363 * ending with <b>suffix</b>, and containing no less than
2364 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2365 * characters between. */
2367 crypto_random_hostname(int min_rand_len
, int max_rand_len
, const char *prefix
,
2370 char *result
, *rand_bytes
;
2371 int randlen
, rand_bytes_len
;
2372 size_t resultlen
, prefixlen
;
2374 tor_assert(max_rand_len
>= min_rand_len
);
2375 randlen
= min_rand_len
+ crypto_rand_int(max_rand_len
- min_rand_len
+ 1);
2376 prefixlen
= strlen(prefix
);
2377 resultlen
= prefixlen
+ strlen(suffix
) + randlen
+ 16;
2379 rand_bytes_len
= ((randlen
*5)+7)/8;
2380 if (rand_bytes_len
% 5)
2381 rand_bytes_len
+= 5 - (rand_bytes_len
%5);
2382 rand_bytes
= tor_malloc(rand_bytes_len
);
2383 crypto_rand(rand_bytes
, rand_bytes_len
);
2385 result
= tor_malloc(resultlen
);
2386 memcpy(result
, prefix
, prefixlen
);
2387 base32_encode(result
+prefixlen
, resultlen
-prefixlen
,
2388 rand_bytes
, rand_bytes_len
);
2389 tor_free(rand_bytes
);
2390 strlcpy(result
+prefixlen
+randlen
, suffix
, resultlen
-(prefixlen
+randlen
));
2395 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2398 smartlist_choose(const smartlist_t
*sl
)
2400 int len
= smartlist_len(sl
);
2402 return smartlist_get(sl
,crypto_rand_int(len
));
2403 return NULL
; /* no elements to choose from */
2406 /** Scramble the elements of <b>sl</b> into a random order. */
2408 smartlist_shuffle(smartlist_t
*sl
)
2411 /* From the end of the list to the front, choose at random from the
2412 positions we haven't looked at yet, and swap that position into the
2413 current position. Remember to give "no swap" the same probability as
2415 for (i
= smartlist_len(sl
)-1; i
> 0; --i
) {
2416 int j
= crypto_rand_int(i
+1);
2417 smartlist_swap(sl
, i
, j
);
2421 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2422 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2423 * bytes. Return the number of bytes written on success; -1 if
2424 * destlen is too short, or other failure.
2427 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2429 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2430 * it ever shows up in the profile. */
2433 tor_assert(srclen
< INT_MAX
);
2435 /* 48 bytes of input -> 64 bytes of output plus newline.
2436 Plus one more byte, in case I'm wrong.
2438 if (destlen
< ((srclen
/48)+1)*66)
2440 if (destlen
> SIZE_T_CEILING
)
2443 EVP_EncodeInit(&ctx
);
2444 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2445 (unsigned char*)src
, (int)srclen
);
2446 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
2452 /** Special values used for the base64_decode_table */
2457 /** Internal table mapping byte values to what they represent in base64.
2458 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2459 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2461 static const uint8_t base64_decode_table
[256] = {
2462 X
, X
, X
, X
, X
, X
, X
, X
, X
, SP
, SP
, SP
, X
, SP
, X
, X
, /* */
2463 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2464 SP
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, 62, X
, X
, X
, 63,
2465 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X
, X
, X
, PAD
, X
, X
,
2466 X
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2467 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X
, X
, X
, X
, X
,
2468 X
, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2469 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X
, X
, X
, X
, X
,
2470 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2471 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2472 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2473 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2474 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2475 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2476 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2477 X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
, X
,
2480 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2481 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2482 * bytes. Return the number of bytes written on success; -1 if
2483 * destlen is too short, or other failure.
2485 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2486 * spaces or padding.
2488 * NOTE 2: This implementation does not check for the correct number of
2489 * padding "=" characters at the end of the string, and does not check
2490 * for internal padding characters.
2493 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2495 #ifdef USE_OPENSSL_BASE64
2498 /* 64 bytes of input -> *up to* 48 bytes of output.
2499 Plus one more byte, in case I'm wrong.
2501 if (destlen
< ((srclen
/64)+1)*49)
2503 if (destlen
> SIZE_T_CEILING
)
2506 EVP_DecodeInit(&ctx
);
2507 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
2508 (unsigned char*)src
, srclen
);
2509 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
2513 const char *eos
= src
+srclen
;
2516 char *dest_orig
= dest
;
2518 /* Max number of bits == srclen*6.
2519 * Number of bytes required to hold all bits == (srclen*6)/8.
2520 * Yes, we want to round down: anything that hangs over the end of a
2521 * byte is padding. */
2522 if (destlen
< (srclen
*3)/4)
2524 if (destlen
> SIZE_T_CEILING
)
2527 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2528 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2529 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2531 for ( ; src
< eos
; ++src
) {
2532 unsigned char c
= (unsigned char) *src
;
2533 uint8_t v
= base64_decode_table
[c
];
2536 /* This character isn't allowed in base64. */
2539 /* This character is whitespace, and has no effect. */
2542 /* We've hit an = character: the data is over. */
2545 /* We have an actual 6-bit value. Append it to the bits in n. */
2547 if ((++n_idx
) == 4) {
2548 /* We've accumulated 24 bits in n. Flush them. */
2550 *dest
++ = (n
>>8) & 0xff;
2551 *dest
++ = (n
) & 0xff;
2558 /* If we have leftover bits, we need to cope. */
2562 /* No leftover bits. We win. */
2565 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2568 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2572 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2577 tor_assert((dest
-dest_orig
) <= (ssize_t
)destlen
);
2578 tor_assert((dest
-dest_orig
) <= INT_MAX
);
2580 return (int)(dest
-dest_orig
);
2587 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2588 * and newline characters, and store the nul-terminated result in the first
2589 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2591 digest_to_base64(char *d64
, const char *digest
)
2594 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
2595 buf
[BASE64_DIGEST_LEN
] = '\0';
2596 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
2600 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2601 * trailing newline or = characters), decode it and store the result in the
2602 * first DIGEST_LEN bytes at <b>digest</b>. */
2604 digest_from_base64(char *digest
, const char *d64
)
2606 #ifdef USE_OPENSSL_BASE64
2607 char buf_in
[BASE64_DIGEST_LEN
+3];
2609 if (strlen(d64
) != BASE64_DIGEST_LEN
)
2611 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
2612 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
2613 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
2615 memcpy(digest
, buf
, DIGEST_LEN
);
2618 if (base64_decode(digest
, DIGEST_LEN
, d64
, strlen(d64
)) == DIGEST_LEN
)
2625 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2626 * trailing = and newline characters, and store the nul-terminated result in
2627 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2629 digest256_to_base64(char *d64
, const char *digest
)
2632 base64_encode(buf
, sizeof(buf
), digest
, DIGEST256_LEN
);
2633 buf
[BASE64_DIGEST256_LEN
] = '\0';
2634 memcpy(d64
, buf
, BASE64_DIGEST256_LEN
+1);
2638 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2639 * trailing newline or = characters), decode it and store the result in the
2640 * first DIGEST256_LEN bytes at <b>digest</b>. */
2642 digest256_from_base64(char *digest
, const char *d64
)
2644 #ifdef USE_OPENSSL_BASE64
2645 char buf_in
[BASE64_DIGEST256_LEN
+3];
2647 if (strlen(d64
) != BASE64_DIGEST256_LEN
)
2649 memcpy(buf_in
, d64
, BASE64_DIGEST256_LEN
);
2650 memcpy(buf_in
+BASE64_DIGEST256_LEN
, "=\n\0", 3);
2651 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST256_LEN
)
2653 memcpy(digest
, buf
, DIGEST256_LEN
);
2656 if (base64_decode(digest
, DIGEST256_LEN
, d64
, strlen(d64
)) == DIGEST256_LEN
)
2663 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2664 * that srclen*8 is a multiple of 5.
2667 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2669 unsigned int i
, v
, u
;
2670 size_t nbits
= srclen
* 8, bit
;
2672 tor_assert(srclen
< SIZE_T_CEILING
/8);
2673 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
2674 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
2675 tor_assert(destlen
< SIZE_T_CEILING
);
2677 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
2678 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2679 v
= ((uint8_t)src
[bit
/8]) << 8;
2680 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
2681 /* set u to the 5-bit value at the bit'th bit of src. */
2682 u
= (v
>> (11-(bit
%8))) & 0x1F;
2683 dest
[i
] = BASE32_CHARS
[u
];
2688 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2689 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2692 base32_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
2694 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2695 * it ever shows up in the profile. */
2697 size_t nbits
, j
, bit
;
2701 tor_assert(srclen
< SIZE_T_CEILING
/ 5);
2702 tor_assert((nbits
%8) == 0); /* We need an even multiple of 8 bits. */
2703 tor_assert((nbits
/8) <= destlen
); /* We need enough space. */
2704 tor_assert(destlen
< SIZE_T_CEILING
);
2706 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2707 tmp
= tor_malloc_zero(srclen
);
2708 for (j
= 0; j
< srclen
; ++j
) {
2709 if (src
[j
] > 0x60 && src
[j
] < 0x7B) tmp
[j
] = src
[j
] - 0x61;
2710 else if (src
[j
] > 0x31 && src
[j
] < 0x38) tmp
[j
] = src
[j
] - 0x18;
2711 else if (src
[j
] > 0x40 && src
[j
] < 0x5B) tmp
[j
] = src
[j
] - 0x41;
2713 log_warn(LD_BUG
, "illegal character in base32 encoded string");
2719 /* Assemble result byte-wise by applying five possible cases. */
2720 for (i
= 0, bit
= 0; bit
< nbits
; ++i
, bit
+= 8) {
2723 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 3) +
2724 (((uint8_t)tmp
[(bit
/5)+1]) >> 2);
2727 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 6) +
2728 (((uint8_t)tmp
[(bit
/5)+1]) << 1) +
2729 (((uint8_t)tmp
[(bit
/5)+2]) >> 4);
2732 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 4) +
2733 (((uint8_t)tmp
[(bit
/5)+1]) >> 1);
2736 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 7) +
2737 (((uint8_t)tmp
[(bit
/5)+1]) << 2) +
2738 (((uint8_t)tmp
[(bit
/5)+2]) >> 3);
2741 dest
[i
] = (((uint8_t)tmp
[(bit
/5)]) << 5) +
2742 ((uint8_t)tmp
[(bit
/5)+1]);
2747 memset(tmp
, 0, srclen
);
2753 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2754 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2755 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2756 * are a salt; the 9th byte describes how much iteration to do.
2757 * Does not support <b>key_out_len</b> > DIGEST_LEN.
2760 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
2761 size_t secret_len
, const char *s2k_specifier
)
2763 crypto_digest_env_t
*d
;
2765 size_t count
, tmplen
;
2767 tor_assert(key_out_len
< SIZE_T_CEILING
);
2770 c
= s2k_specifier
[8];
2771 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
2774 tor_assert(key_out_len
<= DIGEST_LEN
);
2776 d
= crypto_new_digest_env();
2777 tmplen
= 8+secret_len
;
2778 tmp
= tor_malloc(tmplen
);
2779 memcpy(tmp
,s2k_specifier
,8);
2780 memcpy(tmp
+8,secret
,secret_len
);
2783 if (count
>= secret_len
) {
2784 crypto_digest_add_bytes(d
, tmp
, secret_len
);
2785 count
-= secret_len
;
2787 crypto_digest_add_bytes(d
, tmp
, count
);
2791 crypto_digest_get_digest(d
, key_out
, key_out_len
);
2792 memset(tmp
, 0, tmplen
);
2794 crypto_free_digest_env(d
);
2797 #ifdef TOR_IS_MULTITHREADED
2798 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2800 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
2804 if (!_openssl_mutexes
)
2805 /* This is not a really good fix for the
2806 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2809 if (mode
& CRYPTO_LOCK
)
2810 tor_mutex_acquire(_openssl_mutexes
[n
]);
2812 tor_mutex_release(_openssl_mutexes
[n
]);
2815 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2817 struct CRYPTO_dynlock_value
{
2821 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2822 * documentation in OpenSSL's docs for more info. */
2823 static struct CRYPTO_dynlock_value
*
2824 _openssl_dynlock_create_cb(const char *file
, int line
)
2826 struct CRYPTO_dynlock_value
*v
;
2829 v
= tor_malloc(sizeof(struct CRYPTO_dynlock_value
));
2830 v
->lock
= tor_mutex_new();
2834 /** OpenSSL callback function to acquire or release a lock: see
2835 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2837 _openssl_dynlock_lock_cb(int mode
, struct CRYPTO_dynlock_value
*v
,
2838 const char *file
, int line
)
2842 if (mode
& CRYPTO_LOCK
)
2843 tor_mutex_acquire(v
->lock
);
2845 tor_mutex_release(v
->lock
);
2848 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2849 * documentation in OpenSSL's docs for more info. */
2851 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value
*v
,
2852 const char *file
, int line
)
2856 tor_mutex_free(v
->lock
);
2861 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2864 setup_openssl_threading(void)
2867 int n
= CRYPTO_num_locks();
2868 _n_openssl_mutexes
= n
;
2869 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
2870 for (i
=0; i
< n
; ++i
)
2871 _openssl_mutexes
[i
] = tor_mutex_new();
2872 CRYPTO_set_locking_callback(_openssl_locking_cb
);
2873 CRYPTO_set_id_callback(tor_get_thread_id
);
2874 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb
);
2875 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb
);
2876 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb
);
2881 setup_openssl_threading(void)