1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar.
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
5 const char crypto_c_id
[] =
10 * \brief Wrapper functions to present a consistent interface to
11 * public-key and symmetric cryptography operations from OpenSSL.
17 #define WIN32_WINNT 0x400
18 #define _WIN32_WINNT 0x400
19 #define WIN32_LEAN_AND_MEAN
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/rand.h>
31 #include <openssl/opensslv.h>
32 #include <openssl/bn.h>
33 #include <openssl/dh.h>
34 #include <openssl/rsa.h>
35 #include <openssl/dh.h>
36 #include <openssl/conf.h>
52 #ifdef HAVE_SYS_FCNTL_H
53 #include <sys/fcntl.h>
60 #include "container.h"
63 #if OPENSSL_VERSION_NUMBER < 0x00905000l
64 #error "We require openssl >= 0.9.5"
65 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
69 #if OPENSSL_VERSION_NUMBER < 0x00907000l
70 #define OPENSSL_PRE_097
73 #include <openssl/engine.h>
76 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
77 * (and don't indicate errors) in OpenSSL version 0.9.5.
79 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
82 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
84 #define RETURN_SSL_OUTCOME(exp) return !(exp)
87 /** Macro: is k a valid RSA public or private key? */
88 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
89 /** Macro: is k a valid RSA private key? */
90 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
92 #ifdef TOR_IS_MULTITHREADED
93 static tor_mutex_t
**_openssl_mutexes
= NULL
;
94 static int _n_openssl_mutexes
= -1;
97 /** A public key, or a public/private keypair. */
98 struct crypto_pk_env_t
100 int refs
; /* reference counting so we don't have to copy keys */
104 /** Key and stream information for a stream cipher. */
105 struct crypto_cipher_env_t
107 char key
[CIPHER_KEY_LEN
];
108 aes_cnt_cipher_t
*cipher
;
111 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
112 * while we're waiting for the second.*/
113 struct crypto_dh_env_t
{
117 /* Prototypes for functions only used by tortls.c */
118 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
119 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
);
120 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
121 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
123 static int setup_openssl_threading(void);
124 static int tor_check_dh_key(BIGNUM
*bn
);
126 /** Return the number of bytes added by padding method <b>padding</b>.
129 crypto_get_rsa_padding_overhead(int padding
)
133 case RSA_NO_PADDING
: return 0;
134 case RSA_PKCS1_OAEP_PADDING
: return 42;
135 case RSA_PKCS1_PADDING
: return 11;
136 default: tor_assert(0); return -1;
140 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
143 crypto_get_rsa_padding(int padding
)
147 case PK_NO_PADDING
: return RSA_NO_PADDING
;
148 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
149 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
150 default: tor_assert(0); return -1;
154 /** Boolean: has OpenSSL's crypto been initialized? */
155 static int _crypto_global_initialized
= 0;
157 /** Log all pending crypto errors at level <b>severity</b>. Use
158 * <b>doing</b> to describe our current activities.
161 crypto_log_errors(int severity
, const char *doing
)
164 const char *msg
, *lib
, *func
;
165 while ((err
= ERR_get_error()) != 0) {
166 msg
= (const char*)ERR_reason_error_string(err
);
167 lib
= (const char*)ERR_lib_error_string(err
);
168 func
= (const char*)ERR_func_error_string(err
);
169 if (!msg
) msg
= "(null)";
171 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)",
172 doing
, msg
, lib
, func
);
174 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
181 log_engine(const char *fn
, ENGINE
*e
)
184 const char *name
, *id
;
185 name
= ENGINE_get_name(e
);
186 id
= ENGINE_get_id(e
);
187 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
188 name
?name
:"?", id
?id
:"?", fn
);
190 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
195 /** Initialize the crypto library. Return 0 on success, -1 on failure.
198 crypto_global_init(int useAccel
)
200 if (!_crypto_global_initialized
) {
201 ERR_load_crypto_strings();
202 OpenSSL_add_all_algorithms();
203 _crypto_global_initialized
= 1;
204 setup_openssl_threading();
208 warn(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
209 info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
210 ENGINE_load_builtin_engines();
211 if (!ENGINE_register_all_complete())
214 /* XXXX make sure this isn't leaking. */
215 log_engine("RSA", ENGINE_get_default_RSA());
216 log_engine("DH", ENGINE_get_default_DH());
217 log_engine("RAND", ENGINE_get_default_RAND());
218 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
219 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
220 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
227 /** Free crypto resources held by this thread. */
229 crypto_thread_cleanup(void)
231 #ifndef ENABLE_0119_PARANOIA_B1
236 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
239 crypto_global_cleanup(void)
242 #ifndef ENABLE_0119_PARANOIA_C
248 #ifndef ENABLE_0119_PARANOIA_C
249 CONF_modules_unload(1);
250 CRYPTO_cleanup_all_ex_data();
253 #ifdef TOR_IS_MULTITHREADED
254 if (_n_openssl_mutexes
) {
255 int n
= _n_openssl_mutexes
;
256 tor_mutex_t
**ms
= _openssl_mutexes
;
258 _openssl_mutexes
= NULL
;
259 _n_openssl_mutexes
= 0;
261 tor_mutex_free(ms
[i
]);
269 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
271 _crypto_new_pk_env_rsa(RSA
*rsa
)
273 crypto_pk_env_t
*env
;
275 env
= tor_malloc(sizeof(crypto_pk_env_t
));
281 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
283 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
288 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
289 * private is set, include the private-key portion of the key. */
291 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
294 EVP_PKEY
*pkey
= NULL
;
295 tor_assert(env
->key
);
297 if (!(key
= RSAPrivateKey_dup(env
->key
)))
300 if (!(key
= RSAPublicKey_dup(env
->key
)))
303 if (!(pkey
= EVP_PKEY_new()))
305 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
316 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
319 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
324 /** Allocate and return storage for a public key. The key itself will not yet
328 crypto_new_pk_env(void)
333 if (!rsa
) return NULL
;
334 return _crypto_new_pk_env_rsa(rsa
);
337 /** Release a reference to an asymmetric key; when all the references
338 * are released, free the key.
341 crypto_free_pk_env(crypto_pk_env_t
*env
)
354 /** Create a new symmetric cipher for a given key and encryption flag
355 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
358 crypto_cipher_env_t
*
359 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
362 crypto_cipher_env_t
*crypto
= NULL
;
364 if (! (crypto
= crypto_new_cipher_env())) {
365 warn(LD_CRYPTO
, "Unable to allocate crypto object");
369 if (crypto_cipher_set_key(crypto
, key
)) {
370 crypto_log_errors(LOG_WARN
, "setting symmetric key");
375 r
= crypto_cipher_encrypt_init_cipher(crypto
);
377 r
= crypto_cipher_decrypt_init_cipher(crypto
);
385 crypto_free_cipher_env(crypto
);
389 /** Allocate and return a new symmetric cipher.
391 crypto_cipher_env_t
*
392 crypto_new_cipher_env(void)
394 crypto_cipher_env_t
*env
;
396 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
397 env
->cipher
= aes_new_cipher();
401 /** Free a symmetric cipher.
404 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
408 tor_assert(env
->cipher
);
409 aes_free_cipher(env
->cipher
);
413 /* public key crypto */
415 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
416 * success, -1 on failure.
419 crypto_pk_generate_key(crypto_pk_env_t
*env
)
425 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
427 crypto_log_errors(LOG_WARN
, "generating RSA key");
434 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
435 * Return 0 on success, -1 on failure.
438 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
446 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
447 b
= BIO_new_mem_buf((char*)s
, -1);
452 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
457 crypto_log_errors(LOG_WARN
, "Error parsing private key");
463 /** Read a PEM-encoded private key from the file named by
464 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
467 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
,
473 /* Read the file into a string. */
474 contents
= read_file_to_str(keyfile
, 0);
476 warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
480 /* Try to parse it. */
481 r
= crypto_pk_read_private_key_from_string(env
, contents
);
484 return -1; /* read_private_key_from_string already warned, so we don't.*/
486 /* Make sure it's valid. */
487 if (crypto_pk_check_key(env
) <= 0)
493 /** PEM-encode the public key portion of <b>env</b> and write it to a
494 * newly allocated string. On success, set *<b>dest</b> to the new
495 * string, *<b>len</b> to the string's length, and return 0. On
496 * failure, return -1.
499 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
,
506 tor_assert(env
->key
);
509 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
511 /* Now you can treat b as if it were a file. Just use the
512 * PEM_*_bio_* functions instead of the non-bio variants.
514 if (!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
515 crypto_log_errors(LOG_WARN
, "writing public key to string");
519 BIO_get_mem_ptr(b
, &buf
);
520 BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
523 tor_assert(buf
->length
>= 0);
524 *dest
= tor_malloc(buf
->length
+1);
525 memcpy(*dest
, buf
->data
, buf
->length
);
526 (*dest
)[buf
->length
] = 0; /* null terminate it */
533 /** Read a PEM-encoded public key from the first <b>len</b> characters of
534 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
538 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
,
546 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
548 BIO_write(b
, src
, len
);
552 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
555 crypto_log_errors(LOG_WARN
, "reading public key from string");
562 /* Write the private key from 'env' into the file named by 'fname',
563 * PEM-encoded. Return 0 on success, -1 on failure.
566 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
575 tor_assert(PRIVATE_KEY_OK(env
));
577 if (!(bio
= BIO_new(BIO_s_mem())))
579 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
581 crypto_log_errors(LOG_WARN
, "writing private key");
585 len
= BIO_get_mem_data(bio
, &cp
);
586 tor_assert(len
>= 0);
587 s
= tor_malloc(len
+1);
590 r
= write_str_to_file(fname
, s
, 0);
596 /** Allocate a new string in *<b>out</b>, containing the public portion of the
597 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
598 * length of the encoded representation on success, and -1 on failure.
600 * <i>This function is for temporary use only. We need a simple
601 * one-line representation for keys to work around a bug in parsing
602 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
603 * in versions of Tor up to 0.0.9pre2.</i>
606 crypto_pk_DER64_encode_public_key(crypto_pk_env_t
*env
, char **out
)
609 char buf
[PK_BYTES
*2]; /* Too long, but hey, stacks are big. */
612 len
= crypto_pk_asn1_encode(env
, buf
, sizeof(buf
));
616 *out
= tor_malloc(len
* 2); /* too long, but safe. */
617 if (base64_encode(*out
, len
*2, buf
, len
) < 0) {
618 warn(LD_CRYPTO
, "Error base64-encoding DER-encoded key");
623 tor_strstrip(*out
, " \r\n\t");
627 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
628 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
630 * <i>This function is for temporary use only. We need a simple
631 * one-line representation for keys to work around a bug in parsing
632 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
633 * in versions of Tor up to 0.0.9pre2.</i>
636 crypto_pk_DER64_decode_public_key(const char *in
)
638 char partitioned
[PK_BYTES
*2 + 16];
639 char buf
[PK_BYTES
*2];
644 if (strlen(in
) > PK_BYTES
*2) {
647 /* base64_decode doesn't work unless we insert linebreaks every 64
648 * characters. how dumb. */
649 if (tor_strpartition(partitioned
, sizeof(partitioned
), in
, "\n", 64,
652 len
= base64_decode(buf
, sizeof(buf
), partitioned
, strlen(partitioned
));
654 warn(LD_CRYPTO
,"Error base-64 decoding key");
657 return crypto_pk_asn1_decode(buf
, len
);
660 /** Return true iff <b>env</b> has a valid key.
663 crypto_pk_check_key(crypto_pk_env_t
*env
)
668 r
= RSA_check_key(env
->key
);
670 crypto_log_errors(LOG_WARN
,"checking RSA key");
674 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
675 * if a==b, and 1 if a\>b.
678 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
685 if (!a
->key
|| !b
->key
)
688 tor_assert(PUBLIC_KEY_OK(a
));
689 tor_assert(PUBLIC_KEY_OK(b
));
690 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
693 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
696 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
698 crypto_pk_keysize(crypto_pk_env_t
*env
)
701 tor_assert(env
->key
);
703 return (size_t) RSA_size(env
->key
);
706 /** Increase the reference count of <b>env</b>, and return it.
709 crypto_pk_dup_key(crypto_pk_env_t
*env
)
712 tor_assert(env
->key
);
718 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
719 * in <b>env</b>, using the padding method <b>padding</b>. On success,
720 * write the result to <b>to</b>, and return the number of bytes
721 * written. On failure, return -1.
724 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
725 const char *from
, size_t fromlen
, int padding
)
732 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
733 env
->key
, crypto_get_rsa_padding(padding
));
735 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
741 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
742 * in <b>env</b>, using the padding method <b>padding</b>. On success,
743 * write the result to <b>to</b>, and return the number of bytes
744 * written. On failure, return -1.
747 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
748 const char *from
, size_t fromlen
,
749 int padding
, int warnOnFailure
)
755 tor_assert(env
->key
);
757 /* Not a private key */
760 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
761 env
->key
, crypto_get_rsa_padding(padding
));
764 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
765 "performing RSA decryption");
771 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
772 * public key in <b>env</b>, using PKCS1 padding. On success, write the
773 * signed data to <b>to</b>, and return the number of bytes written.
774 * On failure, return -1.
777 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
778 const char *from
, size_t fromlen
)
784 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
785 env
->key
, RSA_PKCS1_PADDING
);
788 crypto_log_errors(LOG_WARN
, "checking RSA signature");
794 /** Check a siglen-byte long signature at <b>sig</b> against
795 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
796 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
797 * SHA1(data). Else return -1.
800 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
801 int datalen
, const char *sig
, int siglen
)
803 char digest
[DIGEST_LEN
];
804 char buf
[PK_BYTES
+1];
811 if (crypto_digest(digest
,data
,datalen
)<0) {
812 warn(LD_CRYPTO
, "couldn't compute digest");
815 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
816 if (r
!= DIGEST_LEN
) {
817 warn(LD_CRYPTO
, "Invalid signature");
820 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
821 warn(LD_CRYPTO
, "Signature mismatched with digest.");
828 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
829 * <b>env</b>, using PKCS1 padding. On success, write the signature to
830 * <b>to</b>, and return the number of bytes written. On failure, return
834 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
835 const char *from
, size_t fromlen
)
842 /* Not a private key */
845 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
846 env
->key
, RSA_PKCS1_PADDING
);
848 crypto_log_errors(LOG_WARN
, "generating RSA signature");
854 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
855 * <b>from</b>; sign the data with the private key in <b>env</b>, and
856 * store it in <b>to</b>. Return the number of bytes written on
857 * success, and -1 on failure.
860 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
861 const char *from
, size_t fromlen
)
863 char digest
[DIGEST_LEN
];
864 if (crypto_digest(digest
,from
,fromlen
)<0)
866 return crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
869 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
870 * bytes of data from <b>from</b>, with padding type 'padding',
871 * storing the results on <b>to</b>.
873 * If no padding is used, the public key must be at least as large as
876 * Returns the number of bytes written on success, -1 on failure.
878 * The encrypted data consists of:
879 * - The source data, padded and encrypted with the public key, if the
880 * padded source data is no longer than the public key, and <b>force</b>
882 * - The beginning of the source data prefixed with a 16-byte symmetric key,
883 * padded and encrypted with the public key; followed by the rest of
884 * the source data encrypted in AES-CTR mode with the symmetric key.
887 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
891 int padding
, int force
)
893 int overhead
, outlen
, r
, symlen
;
895 crypto_cipher_env_t
*cipher
= NULL
;
896 char buf
[PK_BYTES
+1];
902 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
903 pkeylen
= crypto_pk_keysize(env
);
905 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
908 if (!force
&& fromlen
+overhead
<= pkeylen
) {
909 /* It all fits in a single encrypt. */
910 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
912 cipher
= crypto_new_cipher_env();
913 if (!cipher
) return -1;
914 if (crypto_cipher_generate_key(cipher
)<0)
916 /* You can't just run around RSA-encrypting any bitstream: if it's
917 * greater than the RSA key, then OpenSSL will happily encrypt, and
918 * later decrypt to the wrong value. So we set the first bit of
919 * 'cipher->key' to 0 if we aren't padding. This means that our
920 * symmetric key is really only 127 bits.
922 if (padding
== PK_NO_PADDING
)
923 cipher
->key
[0] &= 0x7f;
924 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
926 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
927 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
929 /* Length of symmetrically encrypted data. */
930 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
932 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
933 if (outlen
!=(int)pkeylen
) {
936 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
937 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
940 memset(buf
, 0, sizeof(buf
));
941 crypto_free_cipher_env(cipher
);
942 return outlen
+ symlen
;
944 memset(buf
, 0, sizeof(buf
));
945 if (cipher
) crypto_free_cipher_env(cipher
);
949 /** Invert crypto_pk_public_hybrid_encrypt. */
951 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
955 int padding
, int warnOnFailure
)
957 int overhead
, outlen
, r
;
959 crypto_cipher_env_t
*cipher
= NULL
;
960 char buf
[PK_BYTES
+1];
962 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
963 pkeylen
= crypto_pk_keysize(env
);
965 if (fromlen
<= pkeylen
) {
966 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,
969 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,
972 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
973 "Error decrypting public-key data");
976 if (outlen
< CIPHER_KEY_LEN
) {
977 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
978 "No room for a symmetric key");
981 cipher
= crypto_create_init_cipher(buf
, 0);
985 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
986 outlen
-= CIPHER_KEY_LEN
;
987 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
990 memset(buf
,0,sizeof(buf
));
991 crypto_free_cipher_env(cipher
);
992 return outlen
+ (fromlen
-pkeylen
);
994 memset(buf
,0,sizeof(buf
));
995 if (cipher
) crypto_free_cipher_env(cipher
);
999 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1000 * Return -1 on error, or the number of characters used on success.
1003 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
1006 unsigned char *buf
, *cp
;
1007 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1008 if (len
< 0 || len
> dest_len
)
1010 cp
= buf
= tor_malloc(len
+1);
1011 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
1013 crypto_log_errors(LOG_WARN
,"encoding public key");
1017 /* We don't encode directly into 'dest', because that would be illegal
1018 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1020 memcpy(dest
,buf
,len
);
1025 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1026 * success and NULL on failure.
1029 crypto_pk_asn1_decode(const char *str
, size_t len
)
1033 /* This ifdef suppresses a type warning. Take out the first case once
1034 * everybody is using openssl 0.9.7 or later.
1036 #if OPENSSL_VERSION_NUMBER < 0x00907000l
1039 const unsigned char *cp
;
1041 cp
= buf
= tor_malloc(len
);
1042 memcpy(buf
,str
,len
);
1043 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1046 crypto_log_errors(LOG_WARN
,"decoding public key");
1049 return _crypto_new_pk_env_rsa(rsa
);
1052 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1053 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1054 * Return 0 on success, -1 on failure.
1057 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1059 unsigned char *buf
, *bufp
;
1062 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1065 buf
= bufp
= tor_malloc(len
+1);
1066 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1068 crypto_log_errors(LOG_WARN
,"encoding public key");
1072 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1080 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1081 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1082 * space). Return 0 on success, -1 on failure.
1084 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1085 * of the public key, converted to hexadecimal, in upper case, with a
1086 * space after every four digits.
1088 * If <b>add_space</b> is false, omit the spaces.
1091 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1093 char digest
[DIGEST_LEN
];
1094 char hexdigest
[HEX_DIGEST_LEN
+1];
1095 if (crypto_pk_get_digest(pk
, digest
)) {
1098 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1100 if (tor_strpartition(fp_out
, FINGERPRINT_LEN
+1, hexdigest
, " ", 4,
1104 strcpy(fp_out
, hexdigest
);
1109 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1112 crypto_pk_check_fingerprint_syntax(const char *s
)
1115 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1117 if (!TOR_ISSPACE(s
[i
])) return 0;
1119 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1122 if (s
[FINGERPRINT_LEN
]) return 0;
1126 /* symmetric crypto */
1128 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1129 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1132 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1136 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1139 /** Set the symmetric key for the cipher in <b>env</b> to the first
1140 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1141 * Return 0 on success, -1 on failure.
1144 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1152 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1157 /** Return a pointer to the key set for the cipher in <b>env</b>.
1160 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1165 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1166 * success, -1 on failure.
1169 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1173 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1177 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1178 * success, -1 on failure.
1181 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1185 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1189 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1190 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1191 * On failure, return -1.
1194 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1195 const char *from
, size_t fromlen
)
1198 tor_assert(env
->cipher
);
1200 tor_assert(fromlen
);
1203 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1207 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1208 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1209 * On failure, return -1.
1212 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1213 const char *from
, size_t fromlen
)
1219 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1225 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1226 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1227 * Return 0 on success, -1 on failure.
1230 crypto_digest(char *digest
, const char *m
, size_t len
)
1234 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1237 /** Intermediate information about the digest of a stream of data. */
1238 struct crypto_digest_env_t
{
1242 /** Allocate and return a new digest object.
1244 crypto_digest_env_t
*
1245 crypto_new_digest_env(void)
1247 crypto_digest_env_t
*r
;
1248 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1253 /** Deallocate a digest object.
1256 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1261 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1264 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1269 /* Using the SHA1_*() calls directly means we don't support doing
1270 * sha1 in hardware. But so far the delay of getting the question
1271 * to the hardware, and hearing the answer, is likely higher than
1272 * just doing it ourselves. Hashes are fast.
1274 SHA1_Update(&digest
->d
, (void*)data
, len
);
1277 /** Compute the hash of the data that has been passed to the digest
1278 * object; write the first out_len bytes of the result to <b>out</b>.
1279 * <b>out_len</b> must be \<= DIGEST_LEN.
1282 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1283 char *out
, size_t out_len
)
1285 static unsigned char r
[DIGEST_LEN
];
1289 tor_assert(out_len
<= DIGEST_LEN
);
1290 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1291 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1292 SHA1_Final(r
, &tmpctx
);
1293 memcpy(out
, r
, out_len
);
1296 /** Allocate and return a new digest object with the same state as
1299 crypto_digest_env_t
*
1300 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1302 crypto_digest_env_t
*r
;
1304 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1305 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1309 /** Replace the state of the digest object <b>into</b> with the state
1310 * of the digest object <b>from</b>.
1313 crypto_digest_assign(crypto_digest_env_t
*into
,
1314 const crypto_digest_env_t
*from
)
1318 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1323 /** Shared P parameter for our DH key exchanged. */
1324 static BIGNUM
*dh_param_p
= NULL
;
1325 /** Shared G parameter for our DH key exchanges. */
1326 static BIGNUM
*dh_param_g
= NULL
;
1328 /** Initialize dh_param_p and dh_param_g if they are not already
1335 if (dh_param_p
&& dh_param_g
)
1343 /* This is from rfc2409, section 6.2. It's a safe prime, and
1344 supposedly it equals:
1345 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1348 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1349 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1350 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1351 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1352 "49286651ECE65381FFFFFFFFFFFFFFFF");
1355 r
= BN_set_word(g
, 2);
1361 #define DH_PRIVATE_KEY_BITS 320
1363 /** Allocate and return a new DH object for a key exchange.
1368 crypto_dh_env_t
*res
= NULL
;
1373 res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1375 if (!(res
->dh
= DH_new()))
1378 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1381 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1384 #ifndef ENABLE_0119_PARANOIA_A
1385 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1390 crypto_log_errors(LOG_WARN
, "creating DH object");
1391 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1392 if (res
) tor_free(res
);
1396 /** Return the length of the DH key in <b>dh</b>, in bytes.
1399 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1402 return DH_size(dh
->dh
);
1405 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1406 * success, -1 on failure.
1409 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1412 if (!DH_generate_key(dh
->dh
)) {
1413 crypto_log_errors(LOG_WARN
, "generating DH key");
1416 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1417 warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-"
1418 "the-universe chances really do happen. Trying again.");
1419 /* Free and clear the keys, so openssl will actually try again. */
1420 BN_free(dh
->dh
->pub_key
);
1421 BN_free(dh
->dh
->priv_key
);
1422 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1428 /** Generate g^x as necessary, and write the g^x for the key exchange
1429 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1430 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1433 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1437 if (!dh
->dh
->pub_key
) {
1438 if (crypto_dh_generate_public(dh
)<0)
1442 tor_assert(dh
->dh
->pub_key
);
1443 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1444 tor_assert(bytes
>= 0);
1445 if (pubkey_len
< (size_t)bytes
) {
1446 warn(LD_CRYPTO
, "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1447 (int) pubkey_len
, bytes
);
1451 memset(pubkey
, 0, pubkey_len
);
1452 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1457 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1458 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1459 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1462 tor_check_dh_key(BIGNUM
*bn
)
1472 if (BN_cmp(bn
,x
)<=0) {
1473 warn(LD_CRYPTO
, "DH key must be at least 2.");
1476 BN_copy(x
,dh_param_p
);
1478 if (BN_cmp(bn
,x
)>=0) {
1479 warn(LD_CRYPTO
, "DH key must be at most p-2.");
1487 warn(LD_CRYPTO
, "Rejecting insecure DH key [%s]", s
);
1493 #define MIN(a,b) ((a)<(b)?(a):(b))
1494 /** Given a DH key exchange object, and our peer's value of g^y (as a
1495 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1496 * <b>secret_bytes_out</b> bytes of shared key material and write them
1497 * to <b>secret_out</b>. Return the number of bytes generated on success,
1500 * (We generate key material by computing
1501 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1502 * where || is concatenation.)
1505 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1506 const char *pubkey
, size_t pubkey_len
,
1507 char *secret_out
, size_t secret_bytes_out
)
1509 char *secret_tmp
= NULL
;
1510 BIGNUM
*pubkey_bn
= NULL
;
1511 size_t secret_len
=0;
1514 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1516 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
, pubkey_len
, NULL
)))
1518 if (tor_check_dh_key(pubkey_bn
)<0) {
1519 /* Check for invalid public keys. */
1520 warn(LD_CRYPTO
,"Rejected invalid g^x");
1523 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
));
1524 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1526 warn(LD_CRYPTO
,"DH_compute_key() failed.");
1529 secret_len
= result
;
1530 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1531 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1532 * Leading zeros MUST be preserved, so that ZZ occupies as many
1533 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1535 * What are the security implications here?
1537 if (crypto_expand_key_material(secret_tmp
, secret_len
,
1538 secret_out
, secret_bytes_out
)<0)
1540 secret_len
= secret_bytes_out
;
1546 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1549 tor_free(secret_tmp
);
1556 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1557 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1558 * <b>key_out</b> by taking the first key_out_len bytes of
1559 * H(K | [00]) | H(K | [01]) | ....
1561 * Return 0 on success, -1 on failure.
1564 crypto_expand_key_material(const char *key_in
, size_t key_in_len
,
1565 char *key_out
, size_t key_out_len
)
1568 char *cp
, *tmp
= tor_malloc(key_in_len
+1);
1569 char digest
[DIGEST_LEN
];
1571 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1572 tor_assert(key_out_len
<= DIGEST_LEN
*256);
1574 memcpy(tmp
, key_in
, key_in_len
);
1575 for (cp
= key_out
, i
=0; key_out_len
; ++i
, cp
+= DIGEST_LEN
) {
1576 tmp
[key_in_len
] = i
;
1577 if (crypto_digest(digest
, tmp
, key_in_len
+1))
1579 memcpy(cp
, digest
, MIN(DIGEST_LEN
, key_out_len
));
1580 if (key_out_len
< DIGEST_LEN
)
1582 key_out_len
-= DIGEST_LEN
;
1584 memset(tmp
, 0, key_in_len
+1);
1589 memset(tmp
, 0, key_in_len
+1);
1594 /** Free a DH key exchange object.
1597 crypto_dh_free(crypto_dh_env_t
*dh
)
1605 /* random numbers */
1607 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1608 * work for us too. */
1609 #define ADD_ENTROPY 32
1611 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1613 #ifndef ENABLE_0119_PARANOIA_B2
1614 #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1616 #define USE_RAND_POLL 0
1619 /** Seed OpenSSL's random number generator with bytes from the
1620 * operating system. Return 0 on success, -1 on failure.
1623 crypto_seed_rng(void)
1625 char buf
[ADD_ENTROPY
];
1626 int rand_poll_status
;
1628 /* local variables */
1630 static int provider_set
= 0;
1631 static HCRYPTPROV provider
;
1633 static const char *filenames
[] = {
1634 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1641 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1642 * entropy than we do. We'll try calling that, *and* calling our own entropy
1643 * functions. If one succeeds, we'll accept the RNG as seeded. */
1644 rand_poll_status
= RAND_poll();
1645 if (rand_poll_status
== 0)
1646 warn(LD_CRYPTO
, "RAND_poll() failed.");
1648 rand_poll_status
= 0;
1652 if (!provider_set
) {
1653 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1654 CRYPT_VERIFYCONTEXT
)) {
1655 if (GetLastError() != NTE_BAD_KEYSET
) {
1656 warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1657 return rand_poll_status
? 0 : -1;
1662 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1663 warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1664 return rand_poll_status
? 0 : -1;
1666 RAND_seed(buf
, sizeof(buf
));
1669 for (i
= 0; filenames
[i
]; ++i
) {
1670 fd
= open(filenames
[i
], O_RDONLY
, 0);
1672 info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1673 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1675 if (n
!= sizeof(buf
)) {
1677 "Error reading from entropy source (read only %d bytes).", n
);
1680 RAND_seed(buf
, sizeof(buf
));
1684 warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1685 return rand_poll_status
? 0 : -1;
1689 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1690 * success, -1 on failure.
1693 crypto_rand(char *to
, size_t n
)
1697 r
= RAND_bytes((unsigned char*)to
, n
);
1699 crypto_log_errors(LOG_WARN
, "generating random data");
1700 return (r
== 1) ? 0 : -1;
1703 /** Return a pseudorandom integer, chosen uniformly from the values
1704 * between 0 and max-1. */
1706 crypto_rand_int(unsigned int max
)
1709 unsigned int cutoff
;
1710 tor_assert(max
< UINT_MAX
);
1711 tor_assert(max
> 0); /* don't div by 0 */
1713 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1714 * distribution with clipping at the upper end of unsigned int's
1717 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1719 crypto_rand((char*)&val
, sizeof(val
));
1725 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1728 smartlist_choose(const smartlist_t
*sl
)
1731 len
= smartlist_len(sl
);
1733 return smartlist_get(sl
,crypto_rand_int(len
));
1734 return NULL
; /* no elements to choose from */
1737 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1738 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1739 * bytes. Return the number of bytes written on success; -1 if
1740 * destlen is too short, or other failure.
1743 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1748 /* 48 bytes of input -> 64 bytes of output plus newline.
1749 Plus one more byte, in case I'm wrong.
1751 if (destlen
< ((srclen
/48)+1)*66)
1753 if (destlen
> SIZE_T_CEILING
)
1756 EVP_EncodeInit(&ctx
);
1757 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1758 (unsigned char*)src
, srclen
);
1759 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1764 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1765 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1766 * bytes. Return the number of bytes written on success; -1 if
1767 * destlen is too short, or other failure.
1769 * NOTE: destlen should be a little longer than the amount of data it
1770 * will contain, since we check for sufficient space conservatively.
1771 * Here, "a little" is around 64-ish bytes.
1774 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1778 /* 64 bytes of input -> *up to* 48 bytes of output.
1779 Plus one more byte, in case I'm wrong.
1781 if (destlen
< ((srclen
/64)+1)*49)
1783 if (destlen
> SIZE_T_CEILING
)
1786 EVP_DecodeInit(&ctx
);
1787 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
,
1788 (unsigned char*)src
, srclen
);
1789 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
1795 digest_to_base64(char *d64
, const char *digest
)
1798 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
1799 buf
[BASE64_DIGEST_LEN
] = '\0';
1800 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
1805 digest_from_base64(char *digest
, const char *d64
)
1807 char buf_in
[BASE64_DIGEST_LEN
+3];
1809 if (strlen(d64
) != BASE64_DIGEST_LEN
)
1811 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
1812 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
1813 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
1815 memcpy(digest
, buf
, DIGEST_LEN
);
1819 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1820 * that srclen*8 is a multiple of 5.
1823 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1825 unsigned int nbits
, i
, bit
, v
, u
;
1828 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
1829 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
1830 tor_assert(destlen
< SIZE_T_CEILING
);
1832 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1833 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1834 v
= ((uint8_t)src
[bit
/8]) << 8;
1835 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1836 /* set u to the 5-bit value at the bit'th bit of src. */
1837 u
= (v
>> (11-(bit
%8))) & 0x1F;
1838 dest
[i
] = BASE32_CHARS
[u
];
1843 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1844 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1845 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1846 * are a salt; the 9th byte describes how much iteration to do.
1847 * Does not support <b>key_out_len</b> > DIGEST_LEN.
1850 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
1851 size_t secret_len
, const char *s2k_specifier
)
1853 crypto_digest_env_t
*d
;
1857 tor_assert(key_out_len
< SIZE_T_CEILING
);
1860 c
= s2k_specifier
[8];
1861 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
1864 tor_assert(key_out_len
<= DIGEST_LEN
);
1866 d
= crypto_new_digest_env();
1867 tmp
= tor_malloc(8+secret_len
);
1868 memcpy(tmp
,s2k_specifier
,8);
1869 memcpy(tmp
+8,secret
,secret_len
);
1872 if (count
>= secret_len
) {
1873 crypto_digest_add_bytes(d
, tmp
, secret_len
);
1874 count
-= secret_len
;
1876 crypto_digest_add_bytes(d
, tmp
, count
);
1880 crypto_digest_get_digest(d
, key_out
, key_out_len
);
1882 crypto_free_digest_env(d
);
1885 #ifdef TOR_IS_MULTITHREADED
1887 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
1889 if (!_openssl_mutexes
)
1890 /* This is not a really good fix for the
1891 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1894 if (mode
& CRYPTO_LOCK
)
1895 tor_mutex_acquire(_openssl_mutexes
[n
]);
1897 tor_mutex_release(_openssl_mutexes
[n
]);
1901 setup_openssl_threading(void)
1904 int n
= CRYPTO_num_locks();
1905 _n_openssl_mutexes
= n
;
1906 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
1907 for (i
=0; i
< n
; ++i
)
1908 _openssl_mutexes
[i
] = tor_mutex_new();
1909 CRYPTO_set_locking_callback(_openssl_locking_cb
);
1910 CRYPTO_set_id_callback(tor_get_thread_id
);
1915 setup_openssl_threading(void)