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
69 #define OPENSSL_PRE_097
72 #include <openssl/engine.h>
75 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
76 * (and don't indicate errors) in OpenSSL version 0.9.5.
78 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
81 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
83 #define RETURN_SSL_OUTCOME(exp) return !(exp)
86 /** Macro: is k a valid RSA public or private key? */
87 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
88 /** Macro: is k a valid RSA private key? */
89 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
91 #ifdef TOR_IS_MULTITHREADED
92 static tor_mutex_t
**_openssl_mutexes
= NULL
;
93 static int _n_openssl_mutexes
= -1;
96 /** A public key, or a public/private keypair. */
97 struct crypto_pk_env_t
99 int refs
; /* reference counting so we don't have to copy keys */
103 /** Key and stream information for a stream cipher. */
104 struct crypto_cipher_env_t
106 char key
[CIPHER_KEY_LEN
];
107 aes_cnt_cipher_t
*cipher
;
110 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
111 * while we're waiting for the second.*/
112 struct crypto_dh_env_t
{
116 /* Prototypes for functions only used by tortls.c */
117 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
118 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
);
119 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
120 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
122 static int setup_openssl_threading(void);
123 static int tor_check_dh_key(BIGNUM
*bn
);
125 /** Return the number of bytes added by padding method <b>padding</b>.
128 crypto_get_rsa_padding_overhead(int padding
)
132 case RSA_NO_PADDING
: return 0;
133 case RSA_PKCS1_OAEP_PADDING
: return 42;
134 case RSA_PKCS1_PADDING
: return 11;
135 default: tor_assert(0); return -1;
139 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
142 crypto_get_rsa_padding(int padding
)
146 case PK_NO_PADDING
: return RSA_NO_PADDING
;
147 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
148 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
149 default: tor_assert(0); return -1;
153 /** Boolean: has OpenSSL's crypto been initialized? */
154 static int _crypto_global_initialized
= 0;
156 /** Log all pending crypto errors at level <b>severity</b>. Use
157 * <b>doing</b> to describe our current activities.
160 crypto_log_errors(int severity
, const char *doing
)
163 const char *msg
, *lib
, *func
;
164 while ((err
= ERR_get_error()) != 0) {
165 msg
= (const char*)ERR_reason_error_string(err
);
166 lib
= (const char*)ERR_lib_error_string(err
);
167 func
= (const char*)ERR_func_error_string(err
);
168 if (!msg
) msg
= "(null)";
170 log(severity
, LD_CRYPTO
, "crypto error while %s: %s (in %s:%s)", doing
, msg
, lib
, func
);
172 log(severity
, LD_CRYPTO
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
179 log_engine(const char *fn
, ENGINE
*e
)
182 const char *name
, *id
;
183 name
= ENGINE_get_name(e
);
184 id
= ENGINE_get_id(e
);
185 log(LOG_NOTICE
, LD_CRYPTO
, "Using OpenSSL engine %s [%s] for %s",
186 name
?name
:"?", id
?id
:"?", fn
);
188 log(LOG_INFO
, LD_CRYPTO
, "Using default implementation for %s", fn
);
193 /** Initialize the crypto library. Return 0 on success, -1 on failure.
196 crypto_global_init(int useAccel
)
198 if (!_crypto_global_initialized
) {
199 ERR_load_crypto_strings();
200 OpenSSL_add_all_algorithms();
201 _crypto_global_initialized
= 1;
202 setup_openssl_threading();
206 warn(LD_CRYPTO
, "Initializing OpenSSL via tor_tls_init().");
207 info(LD_CRYPTO
, "Initializing OpenSSL engine support.");
208 ENGINE_load_builtin_engines();
209 if (!ENGINE_register_all_complete())
212 /* XXXX make sure this isn't leaking. */
213 log_engine("RSA", ENGINE_get_default_RSA());
214 log_engine("DH", ENGINE_get_default_DH());
215 log_engine("RAND", ENGINE_get_default_RAND());
216 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1
));
217 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb
));
218 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb
));
225 /** Free crypto resources held by this thread. */
227 crypto_thread_cleanup(void)
232 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
235 crypto_global_cleanup(void)
242 CONF_modules_unload(1);
243 CRYPTO_cleanup_all_ex_data();
245 #ifdef TOR_IS_MULTITHREADED
246 if (_n_openssl_mutexes
) {
247 int n
= _n_openssl_mutexes
;
248 tor_mutex_t
**ms
= _openssl_mutexes
;
250 _openssl_mutexes
= NULL
;
251 _n_openssl_mutexes
= 0;
253 tor_mutex_free(ms
[i
]);
261 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
263 _crypto_new_pk_env_rsa(RSA
*rsa
)
265 crypto_pk_env_t
*env
;
267 env
= tor_malloc(sizeof(crypto_pk_env_t
));
273 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
275 _crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
280 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
281 * private is set, include the private-key portion of the key. */
283 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
286 EVP_PKEY
*pkey
= NULL
;
287 tor_assert(env
->key
);
289 if (!(key
= RSAPrivateKey_dup(env
->key
)))
292 if (!(key
= RSAPublicKey_dup(env
->key
)))
295 if (!(pkey
= EVP_PKEY_new()))
297 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
308 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
311 _crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
316 /** Allocate and return storage for a public key. The key itself will not yet
320 crypto_new_pk_env(void)
325 if (!rsa
) return NULL
;
326 return _crypto_new_pk_env_rsa(rsa
);
329 /** Release a reference to an asymmetric key; when all the references
330 * are released, free the key.
333 crypto_free_pk_env(crypto_pk_env_t
*env
)
346 /** Create a new symmetric cipher for a given key and encryption flag
347 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
350 crypto_cipher_env_t
*
351 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
354 crypto_cipher_env_t
*crypto
= NULL
;
356 if (! (crypto
= crypto_new_cipher_env())) {
357 warn(LD_CRYPTO
, "Unable to allocate crypto object");
361 if (crypto_cipher_set_key(crypto
, key
)) {
362 crypto_log_errors(LOG_WARN
, "setting symmetric key");
367 r
= crypto_cipher_encrypt_init_cipher(crypto
);
369 r
= crypto_cipher_decrypt_init_cipher(crypto
);
377 crypto_free_cipher_env(crypto
);
381 /** Allocate and return a new symmetric cipher.
383 crypto_cipher_env_t
*
384 crypto_new_cipher_env(void)
386 crypto_cipher_env_t
*env
;
388 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
389 env
->cipher
= aes_new_cipher();
393 /** Free a symmetric cipher.
396 crypto_free_cipher_env(crypto_cipher_env_t
*env
)
400 tor_assert(env
->cipher
);
401 aes_free_cipher(env
->cipher
);
405 /* public key crypto */
407 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
408 * success, -1 on failure.
411 crypto_pk_generate_key(crypto_pk_env_t
*env
)
417 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
419 crypto_log_errors(LOG_WARN
, "generating RSA key");
426 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
427 * Return 0 on success, -1 on failure.
430 crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
438 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
439 b
= BIO_new_mem_buf((char*)s
, -1);
444 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
449 crypto_log_errors(LOG_WARN
, "Error parsing private key");
455 /** Read a PEM-encoded private key from the file named by
456 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
459 crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
, const char *keyfile
)
464 /* Read the file into a string. */
465 contents
= read_file_to_str(keyfile
, 0);
467 warn(LD_CRYPTO
, "Error reading private key from \"%s\"", keyfile
);
471 /* Try to parse it. */
472 r
= crypto_pk_read_private_key_from_string(env
, contents
);
475 return -1; /* read_private_key_from_string already warned, so we don't.*/
477 /* Make sure it's valid. */
478 if (crypto_pk_check_key(env
) <= 0)
484 /** PEM-encode the public key portion of <b>env</b> and write it to a
485 * newly allocated string. On success, set *<b>dest</b> to the new
486 * string, *<b>len</b> to the string's length, and return 0. On
487 * failure, return -1.
490 crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
, size_t *len
)
496 tor_assert(env
->key
);
499 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
501 /* Now you can treat b as if it were a file. Just use the
502 * PEM_*_bio_* functions instead of the non-bio variants.
504 if (!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
505 crypto_log_errors(LOG_WARN
, "writing public key to string");
509 BIO_get_mem_ptr(b
, &buf
);
510 BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
513 tor_assert(buf
->length
>= 0);
514 *dest
= tor_malloc(buf
->length
+1);
515 memcpy(*dest
, buf
->data
, buf
->length
);
516 (*dest
)[buf
->length
] = 0; /* null terminate it */
523 /** Read a PEM-encoded public key from the first <b>len</b> characters of
524 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
528 crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
, size_t len
)
535 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
537 BIO_write(b
, src
, len
);
541 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
544 crypto_log_errors(LOG_WARN
, "reading public key from string");
551 /* Write the private key from 'env' into the file named by 'fname',
552 * PEM-encoded. Return 0 on success, -1 on failure.
555 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
564 tor_assert(PRIVATE_KEY_OK(env
));
566 if (!(bio
= BIO_new(BIO_s_mem())))
568 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
570 crypto_log_errors(LOG_WARN
, "writing private key");
574 len
= BIO_get_mem_data(bio
, &cp
);
575 tor_assert(len
>= 0);
576 s
= tor_malloc(len
+1);
579 r
= write_str_to_file(fname
, s
, 0);
585 /** Allocate a new string in *<b>out</b>, containing the public portion of the
586 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
587 * length of the encoded representation on success, and -1 on failure.
589 * <i>This function is for temporary use only. We need a simple
590 * one-line representation for keys to work around a bug in parsing
591 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
592 * in versions of Tor up to 0.0.9pre2.</i>
595 crypto_pk_DER64_encode_public_key(crypto_pk_env_t
*env
, char **out
)
598 char buf
[PK_BYTES
*2]; /* Too long, but hey, stacks are big. */
601 len
= crypto_pk_asn1_encode(env
, buf
, sizeof(buf
));
605 *out
= tor_malloc(len
* 2); /* too long, but safe. */
606 if (base64_encode(*out
, len
*2, buf
, len
) < 0) {
607 warn(LD_CRYPTO
, "Error base64-encoding DER-encoded key");
612 tor_strstrip(*out
, " \r\n\t");
616 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
617 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
619 * <i>This function is for temporary use only. We need a simple
620 * one-line representation for keys to work around a bug in parsing
621 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
622 * in versions of Tor up to 0.0.9pre2.</i>
625 crypto_pk_DER64_decode_public_key(const char *in
)
627 char partitioned
[PK_BYTES
*2 + 16];
628 char buf
[PK_BYTES
*2];
633 if (strlen(in
) > PK_BYTES
*2) {
636 /* base64_decode doesn't work unless we insert linebreaks every 64
637 * characters. how dumb. */
638 if (tor_strpartition(partitioned
, sizeof(partitioned
), in
, "\n", 64,
641 len
= base64_decode(buf
, sizeof(buf
), partitioned
, strlen(partitioned
));
643 warn(LD_CRYPTO
,"Error base-64 decoding key");
646 return crypto_pk_asn1_decode(buf
, len
);
649 /** Return true iff <b>env</b> has a valid key.
652 crypto_pk_check_key(crypto_pk_env_t
*env
)
657 r
= RSA_check_key(env
->key
);
659 crypto_log_errors(LOG_WARN
,"checking RSA key");
663 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
664 * if a==b, and 1 if a\>b.
667 crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
)
674 if (!a
->key
|| !b
->key
)
677 tor_assert(PUBLIC_KEY_OK(a
));
678 tor_assert(PUBLIC_KEY_OK(b
));
679 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
682 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
685 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
687 crypto_pk_keysize(crypto_pk_env_t
*env
)
690 tor_assert(env
->key
);
692 return (size_t) RSA_size(env
->key
);
695 /** Increase the reference count of <b>env</b>, and return it.
698 crypto_pk_dup_key(crypto_pk_env_t
*env
)
701 tor_assert(env
->key
);
707 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
708 * in <b>env</b>, using the padding method <b>padding</b>. On success,
709 * write the result to <b>to</b>, and return the number of bytes
710 * written. On failure, return -1.
713 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, char *to
,
714 const char *from
, size_t fromlen
, int padding
)
721 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
722 env
->key
, crypto_get_rsa_padding(padding
));
724 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
730 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
731 * in <b>env</b>, using the padding method <b>padding</b>. On success,
732 * write the result to <b>to</b>, and return the number of bytes
733 * written. On failure, return -1.
736 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, char *to
,
737 const char *from
, size_t fromlen
,
738 int padding
, int warnOnFailure
)
744 tor_assert(env
->key
);
746 /* Not a private key */
749 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
,
750 env
->key
, crypto_get_rsa_padding(padding
));
753 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
754 "performing RSA decryption");
760 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
761 * public key in <b>env</b>, using PKCS1 padding. On success, write the
762 * signed data to <b>to</b>, and return the number of bytes written.
763 * On failure, return -1.
766 crypto_pk_public_checksig(crypto_pk_env_t
*env
, char *to
,
767 const char *from
, size_t fromlen
)
773 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
, env
->key
, RSA_PKCS1_PADDING
);
776 crypto_log_errors(LOG_WARN
, "checking RSA signature");
782 /** Check a siglen-byte long signature at <b>sig</b> against
783 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
784 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
785 * SHA1(data). Else return -1.
788 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const char *data
,
789 int datalen
, const char *sig
, int siglen
)
791 char digest
[DIGEST_LEN
];
792 char buf
[PK_BYTES
+1];
799 if (crypto_digest(digest
,data
,datalen
)<0) {
800 warn(LD_CRYPTO
, "couldn't compute digest");
803 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
804 if (r
!= DIGEST_LEN
) {
805 warn(LD_CRYPTO
, "Invalid signature");
808 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
809 warn(LD_CRYPTO
, "Signature mismatched with digest.");
816 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
817 * <b>env</b>, using PKCS1 padding. On success, write the signature to
818 * <b>to</b>, and return the number of bytes written. On failure, return
822 crypto_pk_private_sign(crypto_pk_env_t
*env
, char *to
,
823 const char *from
, size_t fromlen
)
830 /* Not a private key */
833 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, (unsigned char*)to
, env
->key
, RSA_PKCS1_PADDING
);
835 crypto_log_errors(LOG_WARN
, "generating RSA signature");
841 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
842 * <b>from</b>; sign the data with the private key in <b>env</b>, and
843 * store it in <b>to</b>. Return the number of bytes written on
844 * success, and -1 on failure.
847 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, char *to
,
848 const char *from
, size_t fromlen
)
850 char digest
[DIGEST_LEN
];
851 if (crypto_digest(digest
,from
,fromlen
)<0)
853 return crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
856 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
857 * bytes of data from <b>from</b>, with padding type 'padding',
858 * storing the results on <b>to</b>.
860 * If no padding is used, the public key must be at least as large as
863 * Returns the number of bytes written on success, -1 on failure.
865 * The encrypted data consists of:
866 * - The source data, padded and encrypted with the public key, if the
867 * padded source data is no longer than the public key, and <b>force</b>
869 * - The beginning of the source data prefixed with a 16-byte symmetric key,
870 * padded and encrypted with the public key; followed by the rest of
871 * the source data encrypted in AES-CTR mode with the symmetric key.
874 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
878 int padding
, int force
)
880 int overhead
, outlen
, r
, symlen
;
882 crypto_cipher_env_t
*cipher
= NULL
;
883 char buf
[PK_BYTES
+1];
889 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
890 pkeylen
= crypto_pk_keysize(env
);
892 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
895 if (!force
&& fromlen
+overhead
<= pkeylen
) {
896 /* It all fits in a single encrypt. */
897 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
899 cipher
= crypto_new_cipher_env();
900 if (!cipher
) return -1;
901 if (crypto_cipher_generate_key(cipher
)<0)
903 /* You can't just run around RSA-encrypting any bitstream: if it's
904 * greater than the RSA key, then OpenSSL will happily encrypt, and
905 * later decrypt to the wrong value. So we set the first bit of
906 * 'cipher->key' to 0 if we aren't padding. This means that our
907 * symmetric key is really only 127 bits.
909 if (padding
== PK_NO_PADDING
)
910 cipher
->key
[0] &= 0x7f;
911 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
913 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
914 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
916 /* Length of symmetrically encrypted data. */
917 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
919 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
920 if (outlen
!=(int)pkeylen
) {
923 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
924 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
927 memset(buf
, 0, sizeof(buf
));
928 crypto_free_cipher_env(cipher
);
929 return outlen
+ symlen
;
931 memset(buf
, 0, sizeof(buf
));
932 if (cipher
) crypto_free_cipher_env(cipher
);
936 /** Invert crypto_pk_public_hybrid_encrypt. */
938 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
942 int padding
, int warnOnFailure
)
944 int overhead
, outlen
, r
;
946 crypto_cipher_env_t
*cipher
= NULL
;
947 char buf
[PK_BYTES
+1];
949 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
950 pkeylen
= crypto_pk_keysize(env
);
952 if (fromlen
<= pkeylen
) {
953 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,warnOnFailure
);
955 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,warnOnFailure
);
957 log_fn(warnOnFailure
?LOG_WARN
:LOG_DEBUG
, LD_CRYPTO
,
958 "Error decrypting public-key data");
961 if (outlen
< CIPHER_KEY_LEN
) {
962 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, LD_CRYPTO
,
963 "No room for a symmetric key");
966 cipher
= crypto_create_init_cipher(buf
, 0);
970 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
971 outlen
-= CIPHER_KEY_LEN
;
972 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
975 memset(buf
,0,sizeof(buf
));
976 crypto_free_cipher_env(cipher
);
977 return outlen
+ (fromlen
-pkeylen
);
979 memset(buf
,0,sizeof(buf
));
980 if (cipher
) crypto_free_cipher_env(cipher
);
984 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
985 * Return -1 on error, or the number of characters used on success.
988 crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
991 unsigned char *buf
, *cp
;
992 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
993 if (len
< 0 || len
> dest_len
)
995 cp
= buf
= tor_malloc(len
+1);
996 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
998 crypto_log_errors(LOG_WARN
,"encoding public key");
1002 /* We don't encode directly into 'dest', because that would be illegal
1003 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1005 memcpy(dest
,buf
,len
);
1010 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1011 * success and NULL on failure.
1014 crypto_pk_asn1_decode(const char *str
, size_t len
)
1018 /* This ifdef suppresses a type warning. Take out the first case once
1019 * everybody is using openssl 0.9.7 or later.
1021 #if OPENSSL_VERSION_NUMBER < 0x00907000l
1024 const unsigned char *cp
;
1026 cp
= buf
= tor_malloc(len
);
1027 memcpy(buf
,str
,len
);
1028 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
1031 crypto_log_errors(LOG_WARN
,"decoding public key");
1034 return _crypto_new_pk_env_rsa(rsa
);
1037 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1038 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1039 * Return 0 on success, -1 on failure.
1042 crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
1044 unsigned char *buf
, *bufp
;
1047 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
1050 buf
= bufp
= tor_malloc(len
+1);
1051 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
1053 crypto_log_errors(LOG_WARN
,"encoding public key");
1057 if (crypto_digest(digest_out
, (char*)buf
, len
) < 0) {
1065 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1066 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1067 * space). Return 0 on success, -1 on failure.
1069 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1070 * of the public key, converted to hexadecimal, in upper case, with a
1071 * space after every four digits.
1073 * If <b>add_space</b> is false, omit the spaces.
1076 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
1078 char digest
[DIGEST_LEN
];
1079 char hexdigest
[HEX_DIGEST_LEN
+1];
1080 if (crypto_pk_get_digest(pk
, digest
)) {
1083 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
1085 if (tor_strpartition(fp_out
, FINGERPRINT_LEN
+1, hexdigest
, " ", 4,
1089 strcpy(fp_out
, hexdigest
);
1094 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1097 crypto_pk_check_fingerprint_syntax(const char *s
)
1100 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
1102 if (!TOR_ISSPACE(s
[i
])) return 0;
1104 if (!TOR_ISXDIGIT(s
[i
])) return 0;
1107 if (s
[FINGERPRINT_LEN
]) return 0;
1111 /* symmetric crypto */
1113 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1114 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1117 crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
1121 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1124 /** Set the symmetric key for the cipher in <b>env</b> to the first
1125 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1126 * Return 0 on success, -1 on failure.
1129 crypto_cipher_set_key(crypto_cipher_env_t
*env
, const char *key
)
1137 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1142 /** Return a pointer to the key set for the cipher in <b>env</b>.
1145 crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1150 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1151 * success, -1 on failure.
1154 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1158 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1162 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1163 * success, -1 on failure.
1166 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1170 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1174 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1175 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1176 * On failure, return -1.
1179 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, char *to
,
1180 const char *from
, size_t fromlen
)
1183 tor_assert(env
->cipher
);
1185 tor_assert(fromlen
);
1188 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1192 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1193 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1194 * On failure, return -1.
1197 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, char *to
,
1198 const char *from
, size_t fromlen
)
1204 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1208 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1209 * Return 0 on success, -1 on failure.
1212 crypto_cipher_rewind(crypto_cipher_env_t
*env
, long delta
)
1214 return crypto_cipher_advance(env
, -delta
);
1217 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1218 * Return 0 on success, -1 on failure.
1221 crypto_cipher_advance(crypto_cipher_env_t
*env
, long delta
)
1223 aes_adjust_counter(env
->cipher
, delta
);
1229 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1230 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1231 * Return 0 on success, -1 on failure.
1234 crypto_digest(char *digest
, const char *m
, size_t len
)
1238 return (SHA1((const unsigned char*)m
,len
,(unsigned char*)digest
) == NULL
);
1241 /** Intermediate information about the digest of a stream of data. */
1242 struct crypto_digest_env_t
{
1246 /** Allocate and return a new digest object.
1248 crypto_digest_env_t
*
1249 crypto_new_digest_env(void)
1251 crypto_digest_env_t
*r
;
1252 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1257 /** Deallocate a digest object.
1260 crypto_free_digest_env(crypto_digest_env_t
*digest
)
1265 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1268 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1273 /* Using the SHA1_*() calls directly means we don't support doing
1274 * sha1 in hardware. But so far the delay of getting the question
1275 * to the hardware, and hearing the answer, is likely higher than
1276 * just doing it ourselves. Hashes are fast.
1278 SHA1_Update(&digest
->d
, (void*)data
, len
);
1281 /** Compute the hash of the data that has been passed to the digest
1282 * object; write the first out_len bytes of the result to <b>out</b>.
1283 * <b>out_len</b> must be \<= DIGEST_LEN.
1286 crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1287 char *out
, size_t out_len
)
1289 static unsigned char r
[DIGEST_LEN
];
1293 tor_assert(out_len
<= DIGEST_LEN
);
1294 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1295 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1296 SHA1_Final(r
, &tmpctx
);
1297 memcpy(out
, r
, out_len
);
1300 /** Allocate and return a new digest object with the same state as
1303 crypto_digest_env_t
*
1304 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1306 crypto_digest_env_t
*r
;
1308 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1309 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1313 /** Replace the state of the digest object <b>into</b> with the state
1314 * of the digest object <b>from</b>.
1317 crypto_digest_assign(crypto_digest_env_t
*into
,
1318 const crypto_digest_env_t
*from
)
1322 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1327 /** Shared P parameter for our DH key exchanged. */
1328 static BIGNUM
*dh_param_p
= NULL
;
1329 /** Shared G parameter for our DH key exchanges. */
1330 static BIGNUM
*dh_param_g
= NULL
;
1332 /** Initialize dh_param_p and dh_param_g if they are not already
1339 if (dh_param_p
&& dh_param_g
)
1347 /* This is from rfc2409, section 6.2. It's a safe prime, and
1348 supposedly it equals:
1349 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1352 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1353 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1354 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1355 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1356 "49286651ECE65381FFFFFFFFFFFFFFFF");
1359 r
= BN_set_word(g
, 2);
1365 #define DH_PRIVATE_KEY_BITS 320
1367 /** Allocate and return a new DH object for a key exchange.
1372 crypto_dh_env_t
*res
= NULL
;
1377 res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1379 if (!(res
->dh
= DH_new()))
1382 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1385 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1388 res
->dh
->length
= DH_PRIVATE_KEY_BITS
;
1392 crypto_log_errors(LOG_WARN
, "creating DH object");
1393 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1394 if (res
) tor_free(res
);
1398 /** Return the length of the DH key in <b>dh</b>, in bytes.
1401 crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1404 return DH_size(dh
->dh
);
1407 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1408 * success, -1 on failure.
1411 crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1414 if (!DH_generate_key(dh
->dh
)) {
1415 crypto_log_errors(LOG_WARN
, "generating DH key");
1418 if (tor_check_dh_key(dh
->dh
->pub_key
)<0) {
1419 warn(LD_CRYPTO
, "Weird! Our own DH key was invalid. I guess once-in-the-universe chances really do happen. Trying again.");
1420 /* Free and clear the keys, so openssl will actually try again. */
1421 BN_free(dh
->dh
->pub_key
);
1422 BN_free(dh
->dh
->priv_key
);
1423 dh
->dh
->pub_key
= dh
->dh
->priv_key
= NULL
;
1429 /** Generate g^x as necessary, and write the g^x for the key exchange
1430 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1431 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1434 crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1438 if (!dh
->dh
->pub_key
) {
1439 if (crypto_dh_generate_public(dh
)<0)
1443 tor_assert(dh
->dh
->pub_key
);
1444 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1445 tor_assert(bytes
>= 0);
1446 if (pubkey_len
< (size_t)bytes
) {
1447 warn(LD_CRYPTO
, "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)", (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, 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
)
1464 /* There are about 2^116 ways to have a 1024-bit key with <= 16 bits set,
1465 * and similarly for <= 16 bits unset. This is negligible compared to the
1466 * 2^1024 entry keyspace. */
1467 #define MIN_DIFFERING_BITS 16
1468 /* This covers another 2^25 keys, which is still negligible. */
1469 #define MIN_DIST_FROM_EDGE (1<<24)
1470 /* XXXX Note that this is basically voodoo. Really, we only care about 0,
1471 * 1, and p-1. The "number of bits set" business is inherited from some
1472 * dire warnings in the OpenSSH comments. Real Cryptographers assure us
1473 * that these dire warnings are misplaced.
1475 * Still, it can't hurt. -NM We will likely remove all the crud from this
1476 * function in a future version, though. -RD
1478 int i
, n_bits
, n_set
;
1486 warn(LD_CRYPTO
, "Rejecting DH key < 0");
1489 if (BN_cmp(bn
, dh_param_p
)>=0) {
1490 warn(LD_CRYPTO
, "Rejecting DH key >= p");
1493 n_bits
= BN_num_bits(bn
);
1495 for (i
=0; i
<= n_bits
; ++i
) {
1496 if (BN_is_bit_set(bn
, i
))
1499 if (n_set
< MIN_DIFFERING_BITS
|| n_set
>= n_bits
-MIN_DIFFERING_BITS
) {
1500 warn(LD_CRYPTO
, "Too few/many bits in DH key (%d)", n_set
);
1503 BN_set_word(x
, MIN_DIST_FROM_EDGE
);
1504 if (BN_cmp(bn
,x
)<=0) {
1505 warn(LD_CRYPTO
, "DH key is too close to 0");
1508 BN_copy(x
,dh_param_p
);
1509 BN_sub_word(x
, MIN_DIST_FROM_EDGE
);
1510 if (BN_cmp(bn
,x
)>=0) {
1511 warn(LD_CRYPTO
, "DH key is too close to p");
1519 warn(LD_CRYPTO
, "Rejecting invalid DH key [%s]", s
);
1525 #define MIN(a,b) ((a)<(b)?(a):(b))
1526 /** Given a DH key exchange object, and our peer's value of g^y (as a
1527 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1528 * <b>secret_bytes_out</b> bytes of shared key material and write them
1529 * to <b>secret_out</b>. Return the number of bytes generated on success,
1532 * (We generate key material by computing
1533 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1534 * where || is concatenation.)
1537 crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1538 const char *pubkey
, size_t pubkey_len
,
1539 char *secret_out
, size_t secret_bytes_out
)
1541 char hash
[DIGEST_LEN
];
1542 char *secret_tmp
= NULL
;
1543 BIGNUM
*pubkey_bn
= NULL
;
1544 size_t secret_len
=0;
1548 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1550 if (!(pubkey_bn
= BN_bin2bn((const unsigned char*)pubkey
, pubkey_len
, NULL
)))
1552 if (tor_check_dh_key(pubkey_bn
)<0) {
1553 /* Check for invalid public keys. */
1554 warn(LD_CRYPTO
,"Rejected invalid g^x");
1557 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
)+1);
1558 result
= DH_compute_key((unsigned char*)secret_tmp
, pubkey_bn
, dh
->dh
);
1560 warn(LD_CRYPTO
,"DH_compute_key() failed.");
1563 secret_len
= result
;
1564 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1565 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1566 * Leading zeros MUST be preserved, so that ZZ occupies as many
1567 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1569 * What are the security implications here?
1571 for (i
= 0; i
< secret_bytes_out
; i
+= DIGEST_LEN
) {
1572 secret_tmp
[secret_len
] = (unsigned char) i
/DIGEST_LEN
;
1573 if (crypto_digest(hash
, secret_tmp
, secret_len
+1))
1575 memcpy(secret_out
+i
, hash
, MIN(DIGEST_LEN
, secret_bytes_out
-i
));
1577 secret_len
= secret_bytes_out
;
1583 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1586 tor_free(secret_tmp
);
1593 /** Free a DH key exchange object.
1596 crypto_dh_free(crypto_dh_env_t
*dh
)
1604 /* random numbers */
1606 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1607 * work for us too. */
1608 #define ADD_ENTROPY 32
1610 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1612 #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1614 /** Seed OpenSSL's random number generator with bytes from the
1615 * operating system. Return 0 on success, -1 on failure.
1618 crypto_seed_rng(void)
1620 char buf
[ADD_ENTROPY
];
1621 int rand_poll_status
;
1623 /* local variables */
1625 static int provider_set
= 0;
1626 static HCRYPTPROV provider
;
1628 static const char *filenames
[] = {
1629 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1636 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1637 * entropy than we do. We'll try calling that, *and* calling our own entropy
1638 * functions. If one succeeds, we'll accept the RNG as seeded. */
1639 rand_poll_status
= RAND_poll();
1640 if (rand_poll_status
== 0)
1641 warn(LD_CRYPTO
, "RAND_poll() failed.");
1643 rand_poll_status
= 0;
1647 if (!provider_set
) {
1648 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
)) {
1649 if (GetLastError() != NTE_BAD_KEYSET
) {
1650 warn(LD_CRYPTO
, "Can't get CryptoAPI provider [1]");
1651 return rand_poll_status
? 0 : -1;
1656 if (!CryptGenRandom(provider
, sizeof(buf
), buf
)) {
1657 warn(LD_CRYPTO
, "Can't get entropy from CryptoAPI.");
1658 return rand_poll_status
? 0 : -1;
1660 RAND_seed(buf
, sizeof(buf
));
1663 for (i
= 0; filenames
[i
]; ++i
) {
1664 fd
= open(filenames
[i
], O_RDONLY
, 0);
1666 info(LD_CRYPTO
, "Seeding RNG from \"%s\"", filenames
[i
]);
1667 n
= read_all(fd
, buf
, sizeof(buf
), 0);
1669 if (n
!= sizeof(buf
)) {
1670 warn(LD_CRYPTO
, "Error reading from entropy source");
1673 RAND_seed(buf
, sizeof(buf
));
1677 warn(LD_CRYPTO
, "Cannot seed RNG -- no entropy source found.");
1678 return rand_poll_status
? 0 : -1;
1682 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1683 * success, -1 on failure.
1686 crypto_rand(char *to
, size_t n
)
1690 r
= RAND_bytes((unsigned char*)to
, n
);
1692 crypto_log_errors(LOG_WARN
, "generating random data");
1693 return (r
== 1) ? 0 : -1;
1696 /** Return a pseudorandom integer, chosen uniformly from the values
1697 * between 0 and max-1. */
1699 crypto_rand_int(unsigned int max
)
1702 unsigned int cutoff
;
1703 tor_assert(max
< UINT_MAX
);
1704 tor_assert(max
> 0); /* don't div by 0 */
1706 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1707 * distribution with clipping at the upper end of unsigned int's
1710 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1712 crypto_rand((char*)&val
, sizeof(val
));
1718 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1721 smartlist_choose(const smartlist_t
*sl
)
1724 len
= smartlist_len(sl
);
1726 return smartlist_get(sl
,crypto_rand_int(len
));
1727 return NULL
; /* no elements to choose from */
1730 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1731 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1732 * bytes. Return the number of bytes written on success; -1 if
1733 * destlen is too short, or other failure.
1736 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1741 /* 48 bytes of input -> 64 bytes of output plus newline.
1742 Plus one more byte, in case I'm wrong.
1744 if (destlen
< ((srclen
/48)+1)*66)
1746 if (destlen
> SIZE_T_CEILING
)
1749 EVP_EncodeInit(&ctx
);
1750 EVP_EncodeUpdate(&ctx
, (unsigned char*)dest
, &len
, (unsigned char*)src
, srclen
);
1751 EVP_EncodeFinal(&ctx
, (unsigned char*)(dest
+len
), &ret
);
1756 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1757 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1758 * bytes. Return the number of bytes written on success; -1 if
1759 * destlen is too short, or other failure.
1761 * NOTE: destlen should be a little longer than the amount of data it
1762 * will contain, since we check for sufficient space conservatively.
1763 * Here, "a little" is around 64-ish bytes.
1766 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1770 /* 64 bytes of input -> *up to* 48 bytes of output.
1771 Plus one more byte, in case I'm wrong.
1773 if (destlen
< ((srclen
/64)+1)*49)
1775 if (destlen
> SIZE_T_CEILING
)
1778 EVP_DecodeInit(&ctx
);
1779 EVP_DecodeUpdate(&ctx
, (unsigned char*)dest
, &len
, (unsigned char*)src
, srclen
);
1780 EVP_DecodeFinal(&ctx
, (unsigned char*)dest
, &ret
);
1786 digest_to_base64(char *d64
, const char *digest
)
1789 base64_encode(buf
, sizeof(buf
), digest
, DIGEST_LEN
);
1790 buf
[BASE64_DIGEST_LEN
] = '\0';
1791 memcpy(d64
, buf
, BASE64_DIGEST_LEN
+1);
1796 digest_from_base64(char *digest
, const char *d64
)
1798 char buf_in
[BASE64_DIGEST_LEN
+3];
1800 if (strlen(d64
) != BASE64_DIGEST_LEN
)
1802 memcpy(buf_in
, d64
, BASE64_DIGEST_LEN
);
1803 memcpy(buf_in
+BASE64_DIGEST_LEN
, "=\n\0", 3);
1804 if (base64_decode(buf
, sizeof(buf
), buf_in
, strlen(buf_in
)) != DIGEST_LEN
)
1806 memcpy(digest
, buf
, DIGEST_LEN
);
1810 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1811 * that srclen*8 is a multiple of 5.
1814 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1816 unsigned int nbits
, i
, bit
, v
, u
;
1819 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
1820 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
1821 tor_assert(destlen
< SIZE_T_CEILING
);
1823 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1824 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1825 v
= ((uint8_t)src
[bit
/8]) << 8;
1826 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1827 /* set u to the 5-bit value at the bit'th bit of src. */
1828 u
= (v
>> (11-(bit
%8))) & 0x1F;
1829 dest
[i
] = BASE32_CHARS
[u
];
1834 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1835 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1836 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1837 * are a salt; the 9th byte describes how much iteration to do.
1838 * Does not support <b>key_out_len</b> > DIGEST_LEN.
1841 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
1842 size_t secret_len
, const char *s2k_specifier
)
1844 crypto_digest_env_t
*d
;
1848 tor_assert(key_out_len
< SIZE_T_CEILING
);
1851 c
= s2k_specifier
[8];
1852 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
1855 tor_assert(key_out_len
<= DIGEST_LEN
);
1857 d
= crypto_new_digest_env();
1858 tmp
= tor_malloc(8+secret_len
);
1859 memcpy(tmp
,s2k_specifier
,8);
1860 memcpy(tmp
+8,secret
,secret_len
);
1863 if (count
>= secret_len
) {
1864 crypto_digest_add_bytes(d
, tmp
, secret_len
);
1865 count
-= secret_len
;
1867 crypto_digest_add_bytes(d
, tmp
, count
);
1871 crypto_digest_get_digest(d
, key_out
, key_out_len
);
1873 crypto_free_digest_env(d
);
1876 #ifdef TOR_IS_MULTITHREADED
1878 _openssl_locking_cb(int mode
, int n
, const char *file
, int line
)
1880 if (!_openssl_mutexes
)
1881 /* This is not a really good fix for the
1882 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1885 if (mode
& CRYPTO_LOCK
)
1886 tor_mutex_acquire(_openssl_mutexes
[n
]);
1888 tor_mutex_release(_openssl_mutexes
[n
]);
1892 setup_openssl_threading(void)
1895 int n
= CRYPTO_num_locks();
1896 _n_openssl_mutexes
= n
;
1897 _openssl_mutexes
= tor_malloc(n
*sizeof(tor_mutex_t
*));
1898 for (i
=0; i
< n
; ++i
)
1899 _openssl_mutexes
[i
] = tor_mutex_new();
1900 CRYPTO_set_locking_callback(_openssl_locking_cb
);
1901 CRYPTO_set_id_callback(tor_get_thread_id
);
1906 setup_openssl_threading(void)