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
[] = "$Id$";
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
16 #define WIN32_WINNT 0x400
17 #define _WIN32_WINNT 0x400
18 #define WIN32_LEAN_AND_MEAN
25 #include <openssl/err.h>
26 #include <openssl/rsa.h>
27 #include <openssl/pem.h>
28 #include <openssl/evp.h>
29 #include <openssl/rand.h>
30 #include <openssl/opensslv.h>
31 #include <openssl/bn.h>
32 #include <openssl/dh.h>
33 #include <openssl/rsa.h>
34 #include <openssl/dh.h>
35 #include <openssl/conf.h>
51 #ifdef HAVE_SYS_FCNTL_H
52 #include <sys/fcntl.h>
59 #include "container.h"
62 #if OPENSSL_VERSION_NUMBER < 0x00905000l
63 #error "We require openssl >= 0.9.5"
64 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
68 #if OPENSSL_VERSION_NUMBER < 0x00907000l
71 #include <openssl/engine.h>
74 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
75 * (and don't indicate errors) in OpenSSL version 0.9.5.
77 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
80 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
82 #define RETURN_SSL_OUTCOME(exp) return !(exp)
85 /** Macro: is k a valid RSA public or private key? */
86 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
87 /** Macro: is k a valid RSA private key? */
88 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
90 #ifdef TOR_IS_MULTITHREADED
91 static tor_mutex_t
**_openssl_mutexes
= NULL
;
92 static int _n_openssl_mutexes
= -1;
95 /** A public key, or a public/private keypair. */
96 struct crypto_pk_env_t
98 int refs
; /* reference counting so we don't have to copy keys */
102 /** Key and stream information for a stream cipher. */
103 struct crypto_cipher_env_t
105 char key
[CIPHER_KEY_LEN
];
106 aes_cnt_cipher_t
*cipher
;
109 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
110 * while we're waiting for the second.*/
111 struct crypto_dh_env_t
{
115 /* Prototypes for functions only used by tortls.c */
116 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
117 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
);
118 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
119 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
121 static int setup_openssl_threading(void);
122 static int tor_check_dh_key(BIGNUM
*bn
);
124 /** Return the number of bytes added by padding method <b>padding</b>.
127 crypto_get_rsa_padding_overhead(int padding
)
131 case RSA_NO_PADDING
: return 0;
132 case RSA_PKCS1_OAEP_PADDING
: return 42;
133 case RSA_PKCS1_PADDING
: return 11;
134 default: tor_assert(0); return -1;
138 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
141 crypto_get_rsa_padding(int padding
)
145 case PK_NO_PADDING
: return RSA_NO_PADDING
;
146 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
147 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
148 default: tor_assert(0); return -1;
152 /** Boolean: has OpenSSL's crypto been initialized? */
153 static int _crypto_global_initialized
= 0;
155 /** Log all pending crypto errors at level <b>severity</b>. Use
156 * <b>doing</b> to describe our current activities.
159 crypto_log_errors(int severity
, const char *doing
)
162 const char *msg
, *lib
, *func
;
163 while ((err
= ERR_get_error()) != 0) {
164 msg
= (const char*)ERR_reason_error_string(err
);
165 lib
= (const char*)ERR_lib_error_string(err
);
166 func
= (const char*)ERR_func_error_string(err
);
167 if (!msg
) msg
= "(null)";
169 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)", doing
, msg
, lib
, func
);
171 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
178 log_engine(const char *fn
, ENGINE
*e
)
181 const char *name
, *id
;
182 name
= ENGINE_get_name(e
);
183 id
= ENGINE_get_id(e
);
184 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
185 name
?name
:"?", id
?id
:"?", fn
);
187 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
192 /** Initialize the crypto library. Return 0 on success, -1 on failure.
195 crypto_global_init(int useAccel
)
197 if (!_crypto_global_initialized
) {
198 ERR_load_crypto_strings();
199 OpenSSL_add_all_algorithms();
200 _crypto_global_initialized
= 1;
201 setup_openssl_threading();
205 warn(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
206 info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
207 ENGINE_load_builtin_engines();
208 if (!ENGINE_register_all_complete())
211 /* XXXX make sure this isn't leaking. */
212 log_engine("RSA", ENGINE_get_default_RSA());
213 log_engine("DH", ENGINE_get_default_DH());
214 log_engine("RAND", ENGINE_get_default_RAND());
215 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
216 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
217 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
224 /** Free crypto resources held by this thread. */
226 crypto_thread_cleanup(void)
231 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
234 crypto_global_cleanup(void)
242 CONF_modules_unload(1);
243 CRYPTO_cleanup_all_ex_data();
244 #ifdef TOR_IS_MULTITHREADED
245 if (_n_openssl_mutexes
) {
246 int n
= _n_openssl_mutexes
;
247 tor_mutex_t
**ms
= _openssl_mutexes
;
249 _openssl_mutexes
= NULL
;
250 _n_openssl_mutexes
= 0;
252 tor_mutex_free(ms
[i
]);
260 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
262 _crypto_new_pk_env_rsa(RSA
*rsa
)
264 crypto_pk_env_t
*env
;
266 env
= tor_malloc(sizeof(crypto_pk_env_t
));
272 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
274 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
279 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
280 * private is set, include the private-key portion of the key. */
282 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
285 EVP_PKEY
*pkey
= NULL
;
286 tor_assert(env
->key
);
288 if (!(key
= RSAPrivateKey_dup(env
->key
)))
291 if (!(key
= RSAPublicKey_dup(env
->key
)))
294 if (!(pkey
= EVP_PKEY_new()))
296 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
307 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
310 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
315 /** Allocate and return storage for a public key. The key itself will not yet
319 crypto_new_pk_env(void)
324 if (!rsa
) return NULL
;
325 return _crypto_new_pk_env_rsa(rsa
);
328 /** Release a reference to an asymmetric key; when all the references
329 * are released, free the key.
332 crypto_free_pk_env(crypto_pk_env_t
*env
)
345 /** Create a new symmetric cipher for a given key and encryption flag
346 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
349 crypto_cipher_env_t
*
350 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
353 crypto_cipher_env_t
*crypto
= NULL
;
355 if (! (crypto
= crypto_new_cipher_env())) {
356 warn(LD_CRYPTO
, "Unable to allocate crypto object");
360 if (crypto_cipher_set_key(crypto
, key
)) {
361 crypto_log_errors(LOG_WARN
, "setting symmetric key");
366 r
= crypto_cipher_encrypt_init_cipher(crypto
);
368 r
= crypto_cipher_decrypt_init_cipher(crypto
);
376 crypto_free_cipher_env(crypto
);
380 /** Allocate and return a new symmetric cipher.
382 crypto_cipher_env_t
*
383 crypto_new_cipher_env(void)
385 crypto_cipher_env_t
*env
;
387 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
388 env
->cipher
= aes_new_cipher();
392 /** Free a symmetric cipher.
395 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
399 tor_assert(env
->cipher
);
400 aes_free_cipher(env
->cipher
);
404 /* public key crypto */
406 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
407 * success, -1 on failure.
410 crypto_pk_generate_key(crypto_pk_env_t
*env
)
416 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
418 crypto_log_errors(LOG_WARN
, "generating RSA key");
425 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
426 * Return 0 on success, -1 on failure.
429 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
437 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
438 b
= BIO_new_mem_buf((char*)s
, -1);
443 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
448 crypto_log_errors(LOG_WARN
, "Error parsing private key");
454 /** Read a PEM-encoded private key from the file named by
455 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
458 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
, const char *keyfile
)
463 /* Read the file into a string. */
464 contents
= read_file_to_str(keyfile
, 0);
466 warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
470 /* Try to parse it. */
471 r
= crypto_pk_read_private_key_from_string(env
, contents
);
474 return -1; /* read_private_key_from_string already warned, so we don't.*/
476 /* Make sure it's valid. */
477 if (crypto_pk_check_key(env
) <= 0)
483 /** PEM-encode the public key portion of <b>env</b> and write it to a
484 * newly allocated string. On success, set *<b>dest</b> to the new
485 * string, *<b>len</b> to the string's length, and return 0. On
486 * failure, return -1.
489 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
, size_t *len
)
495 tor_assert(env
->key
);
498 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
500 /* Now you can treat b as if it were a file. Just use the
501 * PEM_*_bio_* functions instead of the non-bio variants.
503 if (!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
504 crypto_log_errors(LOG_WARN
, "writing public key to string");
508 BIO_get_mem_ptr(b
, &buf
);
509 BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
512 tor_assert(buf
->length
>= 0);
513 *dest
= tor_malloc(buf
->length
+1);
514 memcpy(*dest
, buf
->data
, buf
->length
);
515 (*dest
)[buf
->length
] = 0; /* null terminate it */
522 /** Read a PEM-encoded public key from the first <b>len</b> characters of
523 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
527 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
, size_t len
)
534 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
536 BIO_write(b
, src
, len
);
540 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
543 crypto_log_errors(LOG_WARN
, "reading public key from string");
550 /* Write the private key from 'env' into the file named by 'fname',
551 * PEM-encoded. Return 0 on success, -1 on failure.
554 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
563 tor_assert(PRIVATE_KEY_OK(env
));
565 if (!(bio
= BIO_new(BIO_s_mem())))
567 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
569 crypto_log_errors(LOG_WARN
, "writing private key");
573 len
= BIO_get_mem_data(bio
, &cp
);
574 tor_assert(len
>= 0);
575 s
= tor_malloc(len
+1);
578 r
= write_str_to_file(fname
, s
, 0);
584 /** Allocate a new string in *<b>out</b>, containing the public portion of the
585 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
586 * length of the encoded representation on success, and -1 on failure.
588 * <i>This function is for temporary use only. We need a simple
589 * one-line representation for keys to work around a bug in parsing
590 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
591 * in versions of Tor up to 0.0.9pre2.</i>
594 crypto_pk_DER64_encode_public_key(crypto_pk_env_t
*env
, char **out
)
597 char buf
[PK_BYTES
*2]; /* Too long, but hey, stacks are big. */
600 len
= crypto_pk_asn1_encode(env
, buf
, sizeof(buf
));
604 *out
= tor_malloc(len
* 2); /* too long, but safe. */
605 if (base64_encode(*out
, len
*2, buf
, len
) < 0) {
606 warn(LD_CRYPTO
, "Error base64-encoding DER-encoded key");
611 tor_strstrip(*out
, " \r\n\t");
615 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
616 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
618 * <i>This function is for temporary use only. We need a simple
619 * one-line representation for keys to work around a bug in parsing
620 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
621 * in versions of Tor up to 0.0.9pre2.</i>
624 crypto_pk_DER64_decode_public_key(const char *in
)
626 char partitioned
[PK_BYTES
*2 + 16];
627 char buf
[PK_BYTES
*2];
632 if (strlen(in
) > PK_BYTES
*2) {
635 /* base64_decode doesn't work unless we insert linebreaks every 64
636 * characters. how dumb. */
637 if (tor_strpartition(partitioned
, sizeof(partitioned
), in
, "\n", 64,
640 len
= base64_decode(buf
, sizeof(buf
), partitioned
, strlen(partitioned
));
642 warn(LD_CRYPTO
,"Error base-64 decoding key");
645 return crypto_pk_asn1_decode(buf
, len
);
648 /** Return true iff <b>env</b> has a valid key.
651 crypto_pk_check_key(crypto_pk_env_t
*env
)
656 r
= RSA_check_key(env
->key
);
658 crypto_log_errors(LOG_WARN
,"checking RSA key");
662 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
663 * if a==b, and 1 if a\>b.
666 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
673 if (!a
->key
|| !b
->key
)
676 tor_assert(PUBLIC_KEY_OK(a
));
677 tor_assert(PUBLIC_KEY_OK(b
));
678 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
681 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
684 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
686 crypto_pk_keysize(crypto_pk_env_t
*env
)
689 tor_assert(env
->key
);
691 return (size_t) RSA_size(env
->key
);
694 /** Increase the reference count of <b>env</b>, and return it.
697 crypto_pk_dup_key(crypto_pk_env_t
*env
)
700 tor_assert(env
->key
);
706 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
707 * in <b>env</b>, using the padding method <b>padding</b>. On success,
708 * write the result to <b>to</b>, and return the number of bytes
709 * written. On failure, return -1.
712 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
713 const char *from
, size_t fromlen
, int padding
)
720 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
721 env
->key
, crypto_get_rsa_padding(padding
));
723 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
729 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
730 * in <b>env</b>, using the padding method <b>padding</b>. On success,
731 * write the result to <b>to</b>, and return the number of bytes
732 * written. On failure, return -1.
735 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
736 const char *from
, size_t fromlen
,
737 int padding
, int warnOnFailure
)
743 tor_assert(env
->key
);
745 /* Not a private key */
748 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
749 env
->key
, crypto_get_rsa_padding(padding
));
752 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
753 "performing RSA decryption");
759 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
760 * public key in <b>env</b>, using PKCS1 padding. On success, write the
761 * signed data to <b>to</b>, and return the number of bytes written.
762 * On failure, return -1.
765 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
766 const char *from
, size_t fromlen
)
772 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
, env
->key
, RSA_PKCS1_PADDING
);
775 crypto_log_errors(LOG_WARN
, "checking RSA signature");
781 /** Check a siglen-byte long signature at <b>sig</b> against
782 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
783 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
784 * SHA1(data). Else return -1.
787 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
788 int datalen
, const char *sig
, int siglen
)
790 char digest
[DIGEST_LEN
];
791 char buf
[PK_BYTES
+1];
798 if (crypto_digest(digest
,data
,datalen
)<0) {
799 warn(LD_CRYPTO
, "couldn't compute digest");
802 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
803 if (r
!= DIGEST_LEN
) {
804 warn(LD_CRYPTO
, "Invalid signature");
807 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
808 warn(LD_CRYPTO
, "Signature mismatched with digest.");
815 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
816 * <b>env</b>, using PKCS1 padding. On success, write the signature to
817 * <b>to</b>, and return the number of bytes written. On failure, return
821 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
822 const char *from
, size_t fromlen
)
829 /* Not a private key */
832 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
, env
->key
, RSA_PKCS1_PADDING
);
834 crypto_log_errors(LOG_WARN
, "generating RSA signature");
840 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
841 * <b>from</b>; sign the data with the private key in <b>env</b>, and
842 * store it in <b>to</b>. Return the number of bytes written on
843 * success, and -1 on failure.
846 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
847 const char *from
, size_t fromlen
)
849 char digest
[DIGEST_LEN
];
850 if (crypto_digest(digest
,from
,fromlen
)<0)
852 return crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
855 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
856 * bytes of data from <b>from</b>, with padding type 'padding',
857 * storing the results on <b>to</b>.
859 * If no padding is used, the public key must be at least as large as
862 * Returns the number of bytes written on success, -1 on failure.
864 * The encrypted data consists of:
865 * - The source data, padded and encrypted with the public key, if the
866 * padded source data is no longer than the public key, and <b>force</b>
868 * - The beginning of the source data prefixed with a 16-byte symmetric key,
869 * padded and encrypted with the public key; followed by the rest of
870 * the source data encrypted in AES-CTR mode with the symmetric key.
873 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
877 int padding
, int force
)
879 int overhead
, outlen
, r
, symlen
;
881 crypto_cipher_env_t
*cipher
= NULL
;
882 char buf
[PK_BYTES
+1];
888 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
889 pkeylen
= crypto_pk_keysize(env
);
891 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
894 if (!force
&& fromlen
+overhead
<= pkeylen
) {
895 /* It all fits in a single encrypt. */
896 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
898 cipher
= crypto_new_cipher_env();
899 if (!cipher
) return -1;
900 if (crypto_cipher_generate_key(cipher
)<0)
902 /* You can't just run around RSA-encrypting any bitstream: if it's
903 * greater than the RSA key, then OpenSSL will happily encrypt, and
904 * later decrypt to the wrong value. So we set the first bit of
905 * 'cipher->key' to 0 if we aren't padding. This means that our
906 * symmetric key is really only 127 bits.
908 if (padding
== PK_NO_PADDING
)
909 cipher
->key
[0] &= 0x7f;
910 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
912 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
913 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
915 /* Length of symmetrically encrypted data. */
916 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
918 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
919 if (outlen
!=(int)pkeylen
) {
922 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
923 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
926 memset(buf
, 0, sizeof(buf
));
927 crypto_free_cipher_env(cipher
);
928 return outlen
+ symlen
;
930 memset(buf
, 0, sizeof(buf
));
931 if (cipher
) crypto_free_cipher_env(cipher
);
935 /** Invert crypto_pk_public_hybrid_encrypt. */
937 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
941 int padding
, int warnOnFailure
)
943 int overhead
, outlen
, r
;
945 crypto_cipher_env_t
*cipher
= NULL
;
946 char buf
[PK_BYTES
+1];
948 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
949 pkeylen
= crypto_pk_keysize(env
);
951 if (fromlen
<= pkeylen
) {
952 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,warnOnFailure
);
954 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,warnOnFailure
);
956 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
957 "Error decrypting public-key data");
960 if (outlen
< CIPHER_KEY_LEN
) {
961 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
962 "No room for a symmetric key");
965 cipher
= crypto_create_init_cipher(buf
, 0);
969 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
970 outlen
-= CIPHER_KEY_LEN
;
971 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
974 memset(buf
,0,sizeof(buf
));
975 crypto_free_cipher_env(cipher
);
976 return outlen
+ (fromlen
-pkeylen
);
978 memset(buf
,0,sizeof(buf
));
979 if (cipher
) crypto_free_cipher_env(cipher
);
983 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
984 * Return -1 on error, or the number of characters used on success.
987 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
990 unsigned char *buf
, *cp
;
991 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
992 if (len
< 0 || len
> dest_len
)
994 cp
= buf
= tor_malloc(len
+1);
995 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
997 crypto_log_errors(LOG_WARN
,"encoding public key");
1001 /* We don't encode directly into 'dest', because that would be illegal
1002 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1004 memcpy(dest
,buf
,len
);
1009 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1010 * success and NULL on failure.
1013 crypto_pk_asn1_decode(const char *str
, size_t len
)
1017 /* This ifdef suppresses a type warning. Take out the first case once
1018 * everybody is using openssl 0.9.7 or later.
1020 #if OPENSSL_VERSION_NUMBER < 0x00907000l
1023 const unsigned char *cp
;
1025 cp
= buf
= tor_malloc(len
);
1026 memcpy(buf
,str
,len
);
1027 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1030 crypto_log_errors(LOG_WARN
,"decoding public key");
1033 return _crypto_new_pk_env_rsa(rsa
);
1036 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1037 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1038 * Return 0 on success, -1 on failure.
1041 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1043 unsigned char *buf
, *bufp
;
1046 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1049 buf
= bufp
= tor_malloc(len
+1);
1050 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1052 crypto_log_errors(LOG_WARN
,"encoding public key");
1056 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1064 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1065 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1066 * space). Return 0 on success, -1 on failure.
1068 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1069 * of the public key, converted to hexadecimal, in upper case, with a
1070 * space after every four digits.
1072 * If <b>add_space</b> is false, omit the spaces.
1075 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1077 char digest
[DIGEST_LEN
];
1078 char hexdigest
[HEX_DIGEST_LEN
+1];
1079 if (crypto_pk_get_digest(pk
, digest
)) {
1082 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1084 if (tor_strpartition(fp_out
, FINGERPRINT_LEN
+1, hexdigest
, " ", 4,
1088 strcpy(fp_out
, hexdigest
);
1093 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1096 crypto_pk_check_fingerprint_syntax(const char *s
)
1099 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1101 if (!TOR_ISSPACE(s
[i
])) return 0;
1103 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1106 if (s
[FINGERPRINT_LEN
]) return 0;
1110 /* symmetric crypto */
1112 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1113 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1116 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1120 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1123 /** Set the symmetric key for the cipher in <b>env</b> to the first
1124 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1125 * Return 0 on success, -1 on failure.
1128 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1136 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1141 /** Return a pointer to the key set for the cipher in <b>env</b>.
1144 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1149 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1150 * success, -1 on failure.
1153 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1157 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1161 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1162 * success, -1 on failure.
1165 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1169 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1173 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1174 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1175 * On failure, return -1.
1178 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1179 const char *from
, size_t fromlen
)
1182 tor_assert(env
->cipher
);
1184 tor_assert(fromlen
);
1187 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1191 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1192 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1193 * On failure, return -1.
1196 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1197 const char *from
, size_t fromlen
)
1203 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1207 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1208 * Return 0 on success, -1 on failure.
1211 crypto_cipher_rewind(crypto_cipher_env_t
*env
, long delta
)
1213 return crypto_cipher_advance(env
, -delta
);
1216 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1217 * Return 0 on success, -1 on failure.
1220 crypto_cipher_advance(crypto_cipher_env_t
*env
, long delta
)
1222 aes_adjust_counter(env
->cipher
, delta
);
1228 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1229 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1230 * Return 0 on success, -1 on failure.
1233 crypto_digest(char *digest
, const char *m
, size_t len
)
1237 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1240 /** Intermediate information about the digest of a stream of data. */
1241 struct crypto_digest_env_t
{
1245 /** Allocate and return a new digest object.
1247 crypto_digest_env_t
*
1248 crypto_new_digest_env(void)
1250 crypto_digest_env_t
*r
;
1251 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1256 /** Deallocate a digest object.
1259 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1264 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1267 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1272 /* Using the SHA1_*() calls directly means we don't support doing
1273 * sha1 in hardware. But so far the delay of getting the question
1274 * to the hardware, and hearing the answer, is likely higher than
1275 * just doing it ourselves. Hashes are fast.
1277 SHA1_Update(&digest
->d
, (void*)data
, len
);
1280 /** Compute the hash of the data that has been passed to the digest
1281 * object; write the first out_len bytes of the result to <b>out</b>.
1282 * <b>out_len</b> must be \<= DIGEST_LEN.
1285 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1286 char *out
, size_t out_len
)
1288 static unsigned char r
[DIGEST_LEN
];
1292 tor_assert(out_len
<= DIGEST_LEN
);
1293 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1294 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1295 SHA1_Final(r
, &tmpctx
);
1296 memcpy(out
, r
, out_len
);
1299 /** Allocate and return a new digest object with the same state as
1302 crypto_digest_env_t
*
1303 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1305 crypto_digest_env_t
*r
;
1307 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1308 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1312 /** Replace the state of the digest object <b>into</b> with the state
1313 * of the digest object <b>from</b>.
1316 crypto_digest_assign(crypto_digest_env_t
*into
,
1317 const crypto_digest_env_t
*from
)
1321 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1326 /** Shared P parameter for our DH key exchanged. */
1327 static BIGNUM
*dh_param_p
= NULL
;
1328 /** Shared G parameter for our DH key exchanges. */
1329 static BIGNUM
*dh_param_g
= NULL
;
1331 /** Initialize dh_param_p and dh_param_g if they are not already
1338 if (dh_param_p
&& dh_param_g
)
1346 /* This is from rfc2409, section 6.2. It's a safe prime, and
1347 supposedly it equals:
1348 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1351 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1352 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1353 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1354 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1355 "49286651ECE65381FFFFFFFFFFFFFFFF");
1358 r
= BN_set_word(g
, 2);
1364 #define DH_PRIVATE_KEY_BITS 320
1366 /** Allocate and return a new DH object for a key exchange.
1371 crypto_dh_env_t
*res
= NULL
;
1376 res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1378 if (!(res
->dh
= DH_new()))
1381 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1384 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1387 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1391 crypto_log_errors(LOG_WARN
, "creating DH object");
1392 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1393 if (res
) tor_free(res
);
1397 /** Return the length of the DH key in <b>dh</b>, in bytes.
1400 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1403 return DH_size(dh
->dh
);
1406 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1407 * success, -1 on failure.
1410 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1413 if (!DH_generate_key(dh
->dh
)) {
1414 crypto_log_errors(LOG_WARN
, "generating DH key");
1417 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1418 warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-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)", (int) pubkey_len
, bytes
);
1450 memset(pubkey
, 0, pubkey_len
);
1451 BN_bn2bin(dh
->dh
->pub_key
, (unsigned char*)(pubkey
+(pubkey_len
-bytes
)));
1456 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1457 * okay, or -1 if it's bad.
1458 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1461 tor_check_dh_key(BIGNUM
*bn
)
1463 /* There are about 2^116 ways to have a 1024-bit key with <= 16 bits set,
1464 * and similarly for <= 16 bits unset. This is negligible compared to the
1465 * 2^1024 entry keyspace. */
1466 #define MIN_DIFFERING_BITS 16
1467 /* This covers another 2^25 keys, which is still negligible. */
1468 #define MIN_DIST_FROM_EDGE (1<<24)
1469 /* XXXX Note that this is basically voodoo. Really, we only care about 0,
1470 * 1, and p-1. The "number of bits set" business is inherited from some
1471 * dire warnings in the OpenSSH comments. Real Cryptographers assure us
1472 * that these dire warnings are misplaced.
1474 * Still, it can't hurt. -NM We will likely remove all the crud from this
1475 * function in a future version, though. -RD
1477 int i
, n_bits
, n_set
;
1485 warn(LD_CRYPTO
, "Rejecting DH key < 0");
1488 if (BN_cmp(bn
, dh_param_p
)>=0) {
1489 warn(LD_CRYPTO
, "Rejecting DH key >= p");
1492 n_bits
= BN_num_bits(bn
);
1494 for (i
=0; i
<= n_bits
; ++i
) {
1495 if (BN_is_bit_set(bn
, i
))
1498 if (n_set
< MIN_DIFFERING_BITS
|| n_set
>= n_bits
-MIN_DIFFERING_BITS
) {
1499 warn(LD_CRYPTO
, "Too few/many bits in DH key (%d)", n_set
);
1502 BN_set_word(x
, MIN_DIST_FROM_EDGE
);
1503 if (BN_cmp(bn
,x
)<=0) {
1504 warn(LD_CRYPTO
, "DH key is too close to 0");
1507 BN_copy(x
,dh_param_p
);
1508 BN_sub_word(x
, MIN_DIST_FROM_EDGE
);
1509 if (BN_cmp(bn
,x
)>=0) {
1510 warn(LD_CRYPTO
, "DH key is too close to p");
1518 warn(LD_CRYPTO
, "Rejecting invalid DH key [%s]", s
);
1524 #define MIN(a,b) ((a)<(b)?(a):(b))
1525 /** Given a DH key exchange object, and our peer's value of g^y (as a
1526 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1527 * <b>secret_bytes_out</b> bytes of shared key material and write them
1528 * to <b>secret_out</b>. Return the number of bytes generated on success,
1531 * (We generate key material by computing
1532 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1533 * where || is concatenation.)
1536 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1537 const char *pubkey
, size_t pubkey_len
,
1538 char *secret_out
, size_t secret_bytes_out
)
1540 char hash
[DIGEST_LEN
];
1541 char *secret_tmp
= NULL
;
1542 BIGNUM
*pubkey_bn
= NULL
;
1543 size_t secret_len
=0;
1547 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1549 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
, pubkey_len
, NULL
)))
1551 if (tor_check_dh_key(pubkey_bn
)<0) {
1552 /* Check for invalid public keys. */
1553 warn(LD_CRYPTO
,"Rejected invalid g^x");
1556 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
)+1);
1557 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1559 warn(LD_CRYPTO
,"DH_compute_key() failed.");
1562 secret_len
= result
;
1563 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1564 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1565 * Leading zeros MUST be preserved, so that ZZ occupies as many
1566 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1568 * What are the security implications here?
1570 for (i
= 0; i
< secret_bytes_out
; i
+= DIGEST_LEN
) {
1571 secret_tmp
[secret_len
] = (unsigned char) i
/DIGEST_LEN
;
1572 if (crypto_digest(hash
, secret_tmp
, secret_len
+1))
1574 memcpy(secret_out
+i
, hash
, MIN(DIGEST_LEN
, secret_bytes_out
-i
));
1576 secret_len
= secret_bytes_out
;
1582 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1585 tor_free(secret_tmp
);
1592 /** Free a DH key exchange object.
1595 crypto_dh_free(crypto_dh_env_t
*dh
)
1603 /* random numbers */
1605 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1606 * work for us too. */
1607 #define ADD_ENTROPY 32
1609 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1611 #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1613 /** Seed OpenSSL's random number generator with bytes from the
1614 * operating system. Return 0 on success, -1 on failure.
1617 crypto_seed_rng(void)
1619 char buf
[ADD_ENTROPY
];
1620 int rand_poll_status
;
1622 /* local variables */
1624 static int provider_set
= 0;
1625 static HCRYPTPROV provider
;
1627 static const char *filenames
[] = {
1628 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1635 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1636 * entropy than we do. We'll try calling that, *and* calling our own entropy
1637 * functions. If one succeeds, we'll accept the RNG as seeded. */
1638 rand_poll_status
= RAND_poll();
1639 if (rand_poll_status
== 0)
1640 warn(LD_CRYPTO
, "RAND_poll() failed.");
1642 rand_poll_status
= 0;
1646 if (!provider_set
) {
1647 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
)) {
1648 if (GetLastError() != NTE_BAD_KEYSET
) {
1649 warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1650 return rand_poll_status
? 0 : -1;
1655 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1656 warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1657 return rand_poll_status
? 0 : -1;
1659 RAND_seed(buf
, sizeof(buf
));
1662 for (i
= 0; filenames
[i
]; ++i
) {
1663 fd
= open(filenames
[i
], O_RDONLY
, 0);
1665 info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1666 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1668 if (n
!= sizeof(buf
)) {
1669 warn(LD_CRYPTO
, "Error reading from entropy source");
1672 RAND_seed(buf
, sizeof(buf
));
1676 warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1677 return rand_poll_status
? 0 : -1;
1681 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1682 * success, -1 on failure.
1685 crypto_rand(char *to
, size_t n
)
1689 r
= RAND_bytes((unsigned char*)to
, n
);
1691 crypto_log_errors(LOG_WARN
, "generating random data");
1692 return (r
== 1) ? 0 : -1;
1695 /** Return a pseudorandom integer, chosen uniformly from the values
1696 * between 0 and max-1. */
1698 crypto_rand_int(unsigned int max
)
1701 unsigned int cutoff
;
1702 tor_assert(max
< UINT_MAX
);
1703 tor_assert(max
> 0); /* don't div by 0 */
1705 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1706 * distribution with clipping at the upper end of unsigned int's
1709 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1711 crypto_rand((char*)&val
, sizeof(val
));
1717 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1720 smartlist_choose(const smartlist_t
*sl
)
1723 len
= smartlist_len(sl
);
1725 return smartlist_get(sl
,crypto_rand_int(len
));
1726 return NULL
; /* no elements to choose from */
1729 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1730 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1731 * bytes. Return the number of bytes written on success; -1 if
1732 * destlen is too short, or other failure.
1735 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1740 /* 48 bytes of input -> 64 bytes of output plus newline.
1741 Plus one more byte, in case I'm wrong.
1743 if (destlen
< ((srclen
/48)+1)*66)
1745 if (destlen
> SIZE_T_CEILING
)
1748 EVP_EncodeInit(&ctx
);
1749 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
, (unsigned char*)src
, srclen
);
1750 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1755 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1756 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1757 * bytes. Return the number of bytes written on success; -1 if
1758 * destlen is too short, or other failure.
1760 * NOTE: destlen should be a little longer than the amount of data it
1761 * will contain, since we check for sufficient space conservatively.
1762 * Here, "a little" is around 64-ish bytes.
1765 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1769 /* 64 bytes of input -> *up to* 48 bytes of output.
1770 Plus one more byte, in case I'm wrong.
1772 if (destlen
< ((srclen
/64)+1)*49)
1774 if (destlen
> SIZE_T_CEILING
)
1777 EVP_DecodeInit(&ctx
);
1778 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
, (unsigned char*)src
, srclen
);
1779 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
1785 digest_to_base64(char *d64
, const char *digest
)
1788 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
1789 buf
[BASE64_DIGEST_LEN
] = '\0';
1790 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
1795 digest_from_base64(char *digest
, const char *d64
)
1797 char buf_in
[BASE64_DIGEST_LEN
+3];
1799 if (strlen(d64
) != BASE64_DIGEST_LEN
)
1801 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
1802 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
1803 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
1805 memcpy(digest
, buf
, DIGEST_LEN
);
1809 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1810 * that srclen*8 is a multiple of 5.
1813 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1815 unsigned int nbits
, i
, bit
, v
, u
;
1818 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
1819 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
1820 tor_assert(destlen
< SIZE_T_CEILING
);
1822 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1823 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1824 v
= ((uint8_t)src
[bit
/8]) << 8;
1825 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1826 /* set u to the 5-bit value at the bit'th bit of src. */
1827 u
= (v
>> (11-(bit
%8))) & 0x1F;
1828 dest
[i
] = BASE32_CHARS
[u
];
1833 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1834 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1835 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1836 * are a salt; the 9th byte describes how much iteration to do.
1837 * Does not support <b>key_out_len</b> > DIGEST_LEN.
1840 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
1841 size_t secret_len
, const char *s2k_specifier
)
1843 crypto_digest_env_t
*d
;
1847 tor_assert(key_out_len
< SIZE_T_CEILING
);
1850 c
= s2k_specifier
[8];
1851 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
1854 tor_assert(key_out_len
<= DIGEST_LEN
);
1856 d
= crypto_new_digest_env();
1857 tmp
= tor_malloc(8+secret_len
);
1858 memcpy(tmp
,s2k_specifier
,8);
1859 memcpy(tmp
+8,secret
,secret_len
);
1862 if (count
>= secret_len
) {
1863 crypto_digest_add_bytes(d
, tmp
, secret_len
);
1864 count
-= secret_len
;
1866 crypto_digest_add_bytes(d
, tmp
, count
);
1870 crypto_digest_get_digest(d
, key_out
, key_out_len
);
1872 crypto_free_digest_env(d
);
1875 #ifdef TOR_IS_MULTITHREADED
1877 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
1879 if (!_openssl_mutexes
)
1880 /* This is not a really good fix for the
1881 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1884 if (mode
& CRYPTO_LOCK
)
1885 tor_mutex_acquire(_openssl_mutexes
[n
]);
1887 tor_mutex_release(_openssl_mutexes
[n
]);
1891 setup_openssl_threading(void)
1894 int n
= CRYPTO_num_locks();
1895 _n_openssl_mutexes
= n
;
1896 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
1897 for (i
=0; i
< n
; ++i
)
1898 _openssl_mutexes
[i
] = tor_mutex_new();
1899 CRYPTO_set_locking_callback(_openssl_locking_cb
);
1900 CRYPTO_set_id_callback(tor_get_thread_id
);
1905 setup_openssl_threading(void)