1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
4 const char crypto_c_id
[] = "$Id$";
9 * \brief Low-level cryptographic functions.
15 #define WIN32_WINNT 0x400
16 #define _WIN32_WINNT 0x400
17 #define WIN32_LEAN_AND_MEAN
24 #include <openssl/err.h>
25 #include <openssl/rsa.h>
26 #include <openssl/pem.h>
27 #include <openssl/evp.h>
28 #include <openssl/rand.h>
29 #include <openssl/opensslv.h>
30 #include <openssl/bn.h>
31 #include <openssl/dh.h>
32 #include <openssl/rsa.h>
33 #include <openssl/dh.h>
49 #ifdef HAVE_SYS_FCNTL_H
50 #include <sys/fcntl.h>
57 #include "container.h"
59 #if OPENSSL_VERSION_NUMBER < 0x00905000l
60 #error "We require openssl >= 0.9.5"
61 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
65 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
66 * (and don't indicate errors) in OpenSSL version 0.9.5.
68 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
71 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
73 #define RETURN_SSL_OUTCOME(exp) return !(exp)
76 /** Macro: is k a valid RSA public or private key? */
77 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
78 /** Macro: is k a valid RSA private key? */
79 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
81 struct crypto_pk_env_t
83 int refs
; /* reference counting so we don't have to copy keys */
87 struct crypto_cipher_env_t
89 unsigned char key
[CIPHER_KEY_LEN
];
90 aes_cnt_cipher_t
*cipher
;
93 struct crypto_dh_env_t
{
97 /* Prototypes for functions only used by tortls.c */
98 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
99 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
);
100 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
101 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
103 /** Return the number of bytes added by padding method <b>padding</b>.
106 crypto_get_rsa_padding_overhead(int padding
) {
109 case RSA_NO_PADDING
: return 0;
110 case RSA_PKCS1_OAEP_PADDING
: return 42;
111 case RSA_PKCS1_PADDING
: return 11;
112 default: tor_assert(0); return -1;
116 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
119 crypto_get_rsa_padding(int padding
) {
122 case PK_NO_PADDING
: return RSA_NO_PADDING
;
123 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
124 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
125 default: tor_assert(0); return -1;
129 /** Boolean: has OpenSSL's crypto been initialized? */
130 static int _crypto_global_initialized
= 0;
132 /** Log all pending crypto errors at level <b>severity</b>. Use
133 * <b>doing</b> to describe our current activities.
136 crypto_log_errors(int severity
, const char *doing
)
139 const char *msg
, *lib
, *func
;
140 while ((err
= ERR_get_error()) != 0) {
141 msg
= (const char*)ERR_reason_error_string(err
);
142 lib
= (const char*)ERR_lib_error_string(err
);
143 func
= (const char*)ERR_func_error_string(err
);
144 if (!msg
) msg
= "(null)";
146 log(severity
, "crypto error while %s: %s (in %s:%s)", doing
, msg
, lib
, func
);
148 log(severity
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
153 /** Initialize the crypto library. Return 0 on success, -1 on failure.
155 int crypto_global_init()
157 if (!_crypto_global_initialized
) {
158 ERR_load_crypto_strings();
159 _crypto_global_initialized
= 1;
164 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
166 int crypto_global_cleanup()
172 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
173 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
)
175 crypto_pk_env_t
*env
;
177 env
= tor_malloc(sizeof(crypto_pk_env_t
));
183 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
184 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
189 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
190 * private is set, include the private-key portion of the key. */
191 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
194 EVP_PKEY
*pkey
= NULL
;
195 tor_assert(env
->key
);
197 if (!(key
= RSAPrivateKey_dup(env
->key
)))
200 if (!(key
= RSAPublicKey_dup(env
->key
)))
203 if (!(pkey
= EVP_PKEY_new()))
205 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
216 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
218 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
223 /** Allocate and return storage for a public key. The key itself will not yet
226 crypto_pk_env_t
*crypto_new_pk_env(void)
231 if (!rsa
) return NULL
;
232 return _crypto_new_pk_env_rsa(rsa
);
235 /** Release a reference to an asymmetric key; when all the references
236 * are released, free the key.
238 void crypto_free_pk_env(crypto_pk_env_t
*env
)
251 /** Create a new symmetric cipher for a given key and encryption flag
252 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
255 crypto_cipher_env_t
*
256 crypto_create_init_cipher(const char *key
, int encrypt_mode
)
259 crypto_cipher_env_t
*crypto
= NULL
;
261 if (! (crypto
= crypto_new_cipher_env())) {
262 log_fn(LOG_WARN
, "Unable to allocate crypto object");
266 if (crypto_cipher_set_key(crypto
, key
)) {
267 crypto_log_errors(LOG_WARN
, "setting symmetric key");
272 r
= crypto_cipher_encrypt_init_cipher(crypto
);
274 r
= crypto_cipher_decrypt_init_cipher(crypto
);
282 crypto_free_cipher_env(crypto
);
286 /** Allocate and return a new symmetric cipher.
288 crypto_cipher_env_t
*crypto_new_cipher_env()
290 crypto_cipher_env_t
*env
;
292 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
293 env
->cipher
= aes_new_cipher();
297 /** Free a symmetric cipher.
299 void crypto_free_cipher_env(crypto_cipher_env_t
*env
)
303 tor_assert(env
->cipher
);
304 aes_free_cipher(env
->cipher
);
308 /* public key crypto */
310 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
311 * success, -1 on failure.
313 int crypto_pk_generate_key(crypto_pk_env_t
*env
)
319 env
->key
= RSA_generate_key(PK_BYTES
*8,65537, NULL
, NULL
);
321 crypto_log_errors(LOG_WARN
, "generating RSA key");
328 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
329 * Return 0 on success, -1 on failure.
331 static int crypto_pk_read_private_key_from_string(crypto_pk_env_t
*env
,
339 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
340 b
= BIO_new_mem_buf((char*)s
, -1);
345 env
->key
= PEM_read_bio_RSAPrivateKey(b
,NULL
,NULL
,NULL
);
350 crypto_log_errors(LOG_WARN
, "Error parsing private key");
356 /** Read a PEM-encoded private key from the file named by
357 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
359 int crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
, const char *keyfile
)
364 /* Read the file into a string. */
365 contents
= read_file_to_str(keyfile
, 0);
367 log_fn(LOG_WARN
, "Error reading private key from %s", keyfile
);
371 /* Try to parse it. */
372 r
= crypto_pk_read_private_key_from_string(env
, contents
);
375 return -1; /* read_private_key_from_string already warned, so we don't.*/
377 /* Make sure it's valid. */
378 if (crypto_pk_check_key(env
) <= 0)
384 /** PEM-encode the public key portion of <b>env</b> and write it to a
385 * newly allocated string. On success, set *<b>dest</b> to the new
386 * string, *<b>len</b> to the string's length, and return 0. On
387 * failure, return -1.
389 int crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
, size_t *len
) {
394 tor_assert(env
->key
);
397 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
399 /* Now you can treat b as if it were a file. Just use the
400 * PEM_*_bio_* functions instead of the non-bio variants.
402 if (!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
403 crypto_log_errors(LOG_WARN
, "writing public key to string");
407 BIO_get_mem_ptr(b
, &buf
);
408 BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
411 tor_assert(buf
->length
>= 0);
412 *dest
= tor_malloc(buf
->length
+1);
413 memcpy(*dest
, buf
->data
, buf
->length
);
414 (*dest
)[buf
->length
] = 0; /* null terminate it */
421 /** Read a PEM-encoded public key from the first <b>len</b> characters of
422 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
425 int crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
, size_t len
) {
431 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
433 BIO_write(b
, src
, len
);
437 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
440 crypto_log_errors(LOG_WARN
, "reading public key from string");
447 /* Write the private key from 'env' into the file named by 'fname',
448 * PEM-encoded. Return 0 on success, -1 on failure.
451 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
460 tor_assert(PRIVATE_KEY_OK(env
));
462 if (!(bio
= BIO_new(BIO_s_mem())))
464 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
466 crypto_log_errors(LOG_WARN
, "writing private key");
470 len
= BIO_get_mem_data(bio
, &cp
);
471 tor_assert(len
>= 0);
472 s
= tor_malloc(len
+1);
475 r
= write_str_to_file(fname
, s
, 0);
481 /** Allocate a new string in *<b>out</b>, containing the public portion of the
482 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
483 * length of the encoded representation on success, and -1 on failure.
485 * <i>This function is for temporary use only. We need a simple
486 * one-line representation for keys to work around a bug in parsing
487 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
488 * in versions of Tor up to 0.0.9pre2.</i>
490 int crypto_pk_DER64_encode_public_key(crypto_pk_env_t
*env
, char **out
)
493 char buf
[PK_BYTES
*2]; /* Too long, but hey, stacks are big. */
496 len
= crypto_pk_asn1_encode(env
, buf
, sizeof(buf
));
500 *out
= tor_malloc(len
* 2); /* too long, but safe. */
501 if (base64_encode(*out
, len
*2, buf
, len
) < 0) {
502 log_fn(LOG_WARN
, "Error base64-encoding DER-encoded key");
507 tor_strstrip(*out
, " \r\n\t");
511 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
512 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
514 * <i>This function is for temporary use only. We need a simple
515 * one-line representation for keys to work around a bug in parsing
516 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
517 * in versions of Tor up to 0.0.9pre2.</i>
519 crypto_pk_env_t
*crypto_pk_DER64_decode_public_key(const char *in
)
521 char partitioned
[PK_BYTES
*2 + 16];
522 char buf
[PK_BYTES
*2];
527 if (strlen(in
) > PK_BYTES
*2) {
530 /* base64_decode doesn't work unless we insert linebreaks every 64
531 * characters. how dumb. */
532 if (tor_strpartition(partitioned
, sizeof(partitioned
), in
, "\n", 64,
535 len
= base64_decode(buf
, sizeof(buf
), partitioned
, strlen(partitioned
));
537 log_fn(LOG_WARN
,"Error base-64 decoding key");
540 return crypto_pk_asn1_decode(buf
, len
);
543 /** Return true iff <b>env</b> has a valid key.
545 int crypto_pk_check_key(crypto_pk_env_t
*env
)
550 r
= RSA_check_key(env
->key
);
552 crypto_log_errors(LOG_WARN
,"checking RSA key");
556 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
557 * if a==b, and 1 if a\>b.
559 int crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
) {
565 if (!a
->key
|| !b
->key
)
568 tor_assert(PUBLIC_KEY_OK(a
));
569 tor_assert(PUBLIC_KEY_OK(b
));
570 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
573 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
576 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
577 int crypto_pk_keysize(crypto_pk_env_t
*env
)
580 tor_assert(env
->key
);
582 return RSA_size(env
->key
);
585 /** Increase the reference count of <b>env</b>, and return it.
587 crypto_pk_env_t
*crypto_pk_dup_key(crypto_pk_env_t
*env
) {
589 tor_assert(env
->key
);
595 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
596 * in <b>env</b>, using the padding method <b>padding</b>. On success,
597 * write the result to <b>to</b>, and return the number of bytes
598 * written. On failure, return -1.
601 crypto_pk_public_encrypt(crypto_pk_env_t
*env
, unsigned char *to
,
602 const unsigned char *from
, int fromlen
, int padding
)
609 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, to
, env
->key
,
610 crypto_get_rsa_padding(padding
));
612 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
618 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
619 * in <b>env</b>, using the padding method <b>padding</b>. On success,
620 * write the result to <b>to</b>, and return the number of bytes
621 * written. On failure, return -1.
624 crypto_pk_private_decrypt(crypto_pk_env_t
*env
, unsigned char *to
,
625 const unsigned char *from
, int fromlen
,
626 int padding
, int warnOnFailure
)
632 tor_assert(env
->key
);
634 /* Not a private key */
637 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, to
, env
->key
,
638 crypto_get_rsa_padding(padding
));
640 crypto_log_errors(warnOnFailure
?LOG_WARN
:LOG_INFO
,
641 "performing RSA decryption");
647 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
648 * public key in <b>env</b>, using PKCS1 padding. On success, write the
649 * signed data to <b>to</b>, and return the number of bytes written.
650 * On failure, return -1.
653 crypto_pk_public_checksig(crypto_pk_env_t
*env
, unsigned char *to
,
654 const unsigned char *from
, int fromlen
)
660 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, to
, env
->key
, RSA_PKCS1_PADDING
);
663 crypto_log_errors(LOG_WARN
, "checking RSA signature");
669 /** Check a siglen-byte long signature at <b>sig</b> against
670 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
671 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
672 * SHA1(data). Else return -1.
675 crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const unsigned char *data
,
676 int datalen
, const unsigned char *sig
, int siglen
)
678 char digest
[DIGEST_LEN
];
679 char buf
[PK_BYTES
+1];
686 if (crypto_digest(digest
,data
,datalen
)<0) {
687 log_fn(LOG_WARN
, "couldn't compute digest");
690 r
= crypto_pk_public_checksig(env
,buf
,sig
,siglen
);
691 if (r
!= DIGEST_LEN
) {
692 log_fn(LOG_WARN
, "Invalid signature");
695 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
696 log_fn(LOG_WARN
, "Signature mismatched with digest.");
703 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
704 * <b>env</b>, using PKCS1 padding. On success, write the signature to
705 * <b>to</b>, and return the number of bytes written. On failure, return
709 crypto_pk_private_sign(crypto_pk_env_t
*env
, unsigned char *to
,
710 const unsigned char *from
, int fromlen
)
717 /* Not a private key */
720 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, to
, env
->key
, RSA_PKCS1_PADDING
);
722 crypto_log_errors(LOG_WARN
, "generating RSA signature");
728 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
729 * <b>from</b>; sign the data with the private key in <b>env</b>, and
730 * store it in <b>to</b>. Return the number of bytes written on
731 * success, and -1 on failure.
734 crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, unsigned char *to
,
735 const unsigned char *from
, int fromlen
)
737 char digest
[DIGEST_LEN
];
738 if (crypto_digest(digest
,from
,fromlen
)<0)
740 return crypto_pk_private_sign(env
,to
,digest
,DIGEST_LEN
);
743 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
744 * bytes of data from <b>from</b>, with padding type 'padding',
745 * storing the results on <b>to</b>.
747 * If no padding is used, the public key must be at least as large as
750 * Returns the number of bytes written on success, -1 on failure.
752 * The encrypted data consists of:
753 * - The source data, padded and encrypted with the public key, if the
754 * padded source data is no longer than the public key, and <b>force</b>
756 * - The beginning of the source data prefixed with a 16-byte symmetric key,
757 * padded and encrypted with the public key; followed by the rest of
758 * the source data encrypted in AES-CTR mode with the symmetric key.
760 int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
762 const unsigned char *from
,
764 int padding
, int force
)
766 int overhead
, pkeylen
, outlen
, r
, symlen
;
767 crypto_cipher_env_t
*cipher
= NULL
;
768 char buf
[PK_BYTES
+1];
774 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
775 pkeylen
= crypto_pk_keysize(env
);
777 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
780 if (!force
&& fromlen
+overhead
<= pkeylen
) {
781 /* It all fits in a single encrypt. */
782 return crypto_pk_public_encrypt(env
,to
,from
,fromlen
,padding
);
784 cipher
= crypto_new_cipher_env();
785 if (!cipher
) return -1;
786 if (crypto_cipher_generate_key(cipher
)<0)
788 /* You can't just run around RSA-encrypting any bitstream: if it's
789 * greater than the RSA key, then OpenSSL will happily encrypt, and
790 * later decrypt to the wrong value. So we set the first bit of
791 * 'cipher->key' to 0 if we aren't padding. This means that our
792 * symmetric key is really only 127 bits.
794 if (padding
== PK_NO_PADDING
)
795 cipher
->key
[0] &= 0x7f;
796 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
798 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
799 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
801 /* Length of symmetrically encrypted data. */
802 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
804 outlen
= crypto_pk_public_encrypt(env
,to
,buf
,pkeylen
-overhead
,padding
);
805 if (outlen
!=pkeylen
) {
808 r
= crypto_cipher_encrypt(cipher
, to
+outlen
,
809 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
);
812 memset(buf
, 0, sizeof(buf
));
813 crypto_free_cipher_env(cipher
);
814 return outlen
+ symlen
;
816 memset(buf
, 0, sizeof(buf
));
817 if (cipher
) crypto_free_cipher_env(cipher
);
821 /** Invert crypto_pk_public_hybrid_encrypt. */
822 int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
824 const unsigned char *from
,
826 int padding
, int warnOnFailure
)
828 int overhead
, pkeylen
, outlen
, r
;
829 crypto_cipher_env_t
*cipher
= NULL
;
830 char buf
[PK_BYTES
+1];
832 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
833 pkeylen
= crypto_pk_keysize(env
);
835 if (fromlen
<= pkeylen
) {
836 return crypto_pk_private_decrypt(env
,to
,from
,fromlen
,padding
,warnOnFailure
);
838 outlen
= crypto_pk_private_decrypt(env
,buf
,from
,pkeylen
,padding
,warnOnFailure
);
840 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, "Error decrypting public-key data");
843 if (outlen
< CIPHER_KEY_LEN
) {
844 log_fn(warnOnFailure
?LOG_WARN
:LOG_INFO
, "No room for a symmetric key");
847 cipher
= crypto_create_init_cipher(buf
, 0);
851 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
852 outlen
-= CIPHER_KEY_LEN
;
853 r
= crypto_cipher_decrypt(cipher
, to
+outlen
, from
+pkeylen
, fromlen
-pkeylen
);
856 memset(buf
,0,sizeof(buf
));
857 crypto_free_cipher_env(cipher
);
858 return outlen
+ (fromlen
-pkeylen
);
860 memset(buf
,0,sizeof(buf
));
861 if (cipher
) crypto_free_cipher_env(cipher
);
865 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
866 * Return -1 on error, or the number of characters used on success.
868 int crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
871 unsigned char *buf
, *cp
;
872 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
873 if (len
< 0 || len
> dest_len
)
875 cp
= buf
= tor_malloc(len
+1);
876 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
878 crypto_log_errors(LOG_WARN
,"encoding public key");
882 /* We don't encode directly into 'dest', because that would be illegal
883 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
885 memcpy(dest
,buf
,len
);
890 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
891 * success and NULL on failure.
893 crypto_pk_env_t
*crypto_pk_asn1_decode(const char *str
, int len
)
897 /* This ifdef suppresses a type warning. Take out the first case once
898 * everybody is using openssl 0.9.7 or later.
900 #if OPENSSL_VERSION_NUMBER < 0x00907000l
903 const unsigned char *cp
;
905 cp
= buf
= tor_malloc(len
);
907 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
910 crypto_log_errors(LOG_WARN
,"decoding public key");
913 return _crypto_new_pk_env_rsa(rsa
);
916 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
917 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
918 * Return 0 on success, -1 on failure.
920 int crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
922 unsigned char *buf
, *bufp
;
925 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
928 buf
= bufp
= tor_malloc(len
+1);
929 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
931 crypto_log_errors(LOG_WARN
,"encoding public key");
935 if (crypto_digest(digest_out
, buf
, len
) < 0) {
943 /** Given a private or public key <b>pk</b>, put a fingerprint of the
944 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
945 * space). Return 0 on success, -1 on failure.
947 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
948 * of the public key, converted to hexadecimal, in upper case, with a
949 * space after every four digits.
951 * If <b>add_space</b> is false, omit the spaces.
954 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
, int add_space
)
956 unsigned char digest
[DIGEST_LEN
];
957 unsigned char hexdigest
[HEX_DIGEST_LEN
+1];
958 if (crypto_pk_get_digest(pk
, digest
)) {
961 base16_encode(hexdigest
,sizeof(hexdigest
),digest
,DIGEST_LEN
);
963 if (tor_strpartition(fp_out
, FINGERPRINT_LEN
+1, hexdigest
, " ", 4,
967 strcpy(fp_out
, hexdigest
);
972 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
975 crypto_pk_check_fingerprint_syntax(const char *s
)
978 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
980 if (!TOR_ISSPACE(s
[i
])) return 0;
982 if (!TOR_ISXDIGIT(s
[i
])) return 0;
985 if (s
[FINGERPRINT_LEN
]) return 0;
989 /* symmetric crypto */
991 /** Generate a new random key for the symmetric cipher in <b>env</b>.
992 * Return 0 on success, -1 on failure. Does not initialize the cipher.
994 int crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
998 return crypto_rand(env
->key
, CIPHER_KEY_LEN
);
1001 /** Set the symmetric key for the cipher in <b>env</b> to the first
1002 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1003 * Return 0 on success, -1 on failure.
1005 int crypto_cipher_set_key(crypto_cipher_env_t
*env
, const unsigned char *key
)
1013 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
1018 /** Return a pointer to the key set for the cipher in <b>env</b>.
1020 const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t
*env
)
1025 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1026 * success, -1 on failure.
1028 int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
1032 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1036 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1037 * success, -1 on failure.
1039 int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
1043 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
1047 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1048 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1049 * On failure, return -1.
1052 crypto_cipher_encrypt(crypto_cipher_env_t
*env
, unsigned char *to
,
1053 const unsigned char *from
, unsigned int fromlen
)
1056 tor_assert(env
->cipher
);
1058 tor_assert(fromlen
);
1061 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1065 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1066 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1067 * On failure, return -1.
1070 crypto_cipher_decrypt(crypto_cipher_env_t
*env
, unsigned char *to
,
1071 const unsigned char *from
, unsigned int fromlen
)
1077 aes_crypt(env
->cipher
, from
, fromlen
, to
);
1081 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1082 * Return 0 on success, -1 on failure.
1085 crypto_cipher_rewind(crypto_cipher_env_t
*env
, long delta
)
1087 return crypto_cipher_advance(env
, -delta
);
1090 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1091 * Return 0 on success, -1 on failure.
1094 crypto_cipher_advance(crypto_cipher_env_t
*env
, long delta
)
1096 aes_adjust_counter(env
->cipher
, delta
);
1102 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1103 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1104 * Return 0 on success, -1 on failure.
1106 int crypto_digest(unsigned char *digest
, const unsigned char *m
, int len
)
1110 return (SHA1(m
,len
,digest
) == NULL
);
1113 struct crypto_digest_env_t
{
1117 /** Allocate and return a new digest object.
1119 crypto_digest_env_t
*
1120 crypto_new_digest_env(void)
1122 crypto_digest_env_t
*r
;
1123 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1128 /** Deallocate a digest object.
1131 crypto_free_digest_env(crypto_digest_env_t
*digest
) {
1135 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1138 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
1143 /* Using the SHA1_*() calls directly means we don't support doing
1144 * sha1 in hardware. But so far the delay of getting the question
1145 * to the hardware, and hearing the answer, is likely higher than
1146 * just doing it ourselves. Hashes are fast.
1148 SHA1_Update(&digest
->d
, (void*)data
, len
);
1151 /** Compute the hash of the data that has been passed to the digest
1152 * object; write the first out_len bytes of the result to <b>out</b>.
1153 * <b>out_len</b> must be \<= DIGEST_LEN.
1155 void crypto_digest_get_digest(crypto_digest_env_t
*digest
,
1156 char *out
, size_t out_len
)
1158 static char r
[DIGEST_LEN
];
1162 tor_assert(out_len
<= DIGEST_LEN
);
1163 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1164 memcpy(&tmpctx
, &digest
->d
, sizeof(SHA_CTX
));
1165 SHA1_Final(r
, &tmpctx
);
1166 memcpy(out
, r
, out_len
);
1169 /** Allocate and return a new digest object with the same state as
1172 crypto_digest_env_t
*
1173 crypto_digest_dup(const crypto_digest_env_t
*digest
)
1175 crypto_digest_env_t
*r
;
1177 r
= tor_malloc(sizeof(crypto_digest_env_t
));
1178 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
1182 /** Replace the state of the digest object <b>into</b> with the state
1183 * of the digest object <b>from</b>.
1186 crypto_digest_assign(crypto_digest_env_t
*into
,
1187 const crypto_digest_env_t
*from
)
1191 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
1196 /** Shared P parameter for our DH key exchanged. */
1197 static BIGNUM
*dh_param_p
= NULL
;
1198 /** Shared G parameter for our DH key exchanges. */
1199 static BIGNUM
*dh_param_g
= NULL
;
1201 /** Initialize dh_param_p and dh_param_g if they are not already
1203 static void init_dh_param(void) {
1206 if (dh_param_p
&& dh_param_g
)
1215 /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
1216 prime, and supposedly it equals:
1217 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
1220 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
1221 "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
1222 "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
1223 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
1224 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
1225 "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
1226 "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
1227 "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
1230 /* This is from rfc2409, section 6.2. It's a safe prime, and
1231 supposedly it equals:
1232 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1234 /* See also rfc 3536 */
1236 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1237 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1238 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1239 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1240 "49286651ECE65381FFFFFFFFFFFFFFFF");
1243 r
= BN_set_word(g
, 2);
1249 /** Allocate and return a new DH object for a key exchange.
1251 crypto_dh_env_t
*crypto_dh_new()
1253 crypto_dh_env_t
*res
= NULL
;
1258 res
= tor_malloc_zero(sizeof(crypto_dh_env_t
));
1260 if (!(res
->dh
= DH_new()))
1263 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1266 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1271 crypto_log_errors(LOG_WARN
, "creating DH object");
1272 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1277 /** Return the length of the DH key in <b>dh</b>, in bytes.
1279 int crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1282 return DH_size(dh
->dh
);
1285 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1286 * success, -1 on failure.
1288 int crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1290 if (!DH_generate_key(dh
->dh
)) {
1291 crypto_log_errors(LOG_WARN
, "generating DH key");
1297 /** Generate g^x as necessary, and write the g^x for the key exchange
1298 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1299 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1301 int crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, size_t pubkey_len
)
1305 if (!dh
->dh
->pub_key
) {
1306 if (crypto_dh_generate_public(dh
)<0)
1310 tor_assert(dh
->dh
->pub_key
);
1311 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1312 tor_assert(bytes
>= 0);
1313 if (pubkey_len
< (size_t)bytes
)
1316 memset(pubkey
, 0, pubkey_len
);
1317 BN_bn2bin(dh
->dh
->pub_key
, pubkey
+(pubkey_len
-bytes
));
1323 #define MIN(a,b) ((a)<(b)?(a):(b))
1324 /** Given a DH key exchange object, and our peer's value of g^y (as a
1325 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1326 * <b>secret_bytes_out</b> bytes of shared key material and write them
1327 * to <b>secret_out</b>. Return the number of bytes generated on success,
1330 * (We generate key material by computing
1331 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1332 * where || is concatenation.)
1334 int crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1335 const char *pubkey
, size_t pubkey_len
,
1336 char *secret_out
, size_t secret_bytes_out
)
1338 unsigned char hash
[DIGEST_LEN
];
1339 unsigned char *secret_tmp
= NULL
;
1340 BIGNUM
*pubkey_bn
= NULL
;
1341 size_t secret_len
=0;
1345 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1347 if (!(pubkey_bn
= BN_bin2bn(pubkey
, pubkey_len
, NULL
)))
1349 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
)+1);
1350 result
= DH_compute_key(secret_tmp
, pubkey_bn
, dh
->dh
);
1352 log_fn(LOG_WARN
,"DH_compute_key() failed.");
1355 secret_len
= result
;
1356 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1357 for (i
= 0; i
< secret_bytes_out
; i
+= DIGEST_LEN
) {
1358 secret_tmp
[secret_len
] = (unsigned char) i
/DIGEST_LEN
;
1359 if (crypto_digest(hash
, secret_tmp
, secret_len
+1))
1361 memcpy(secret_out
+i
, hash
, MIN(DIGEST_LEN
, secret_bytes_out
-i
));
1363 secret_len
= secret_bytes_out
;
1369 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1372 tor_free(secret_tmp
);
1379 /** Free a DH key exchange object.
1381 void crypto_dh_free(crypto_dh_env_t
*dh
)
1389 /* random numbers */
1391 /** Seed OpenSSL's random number generator with DIGEST_LEN bytes from the
1392 * operating system. Return 0 on success, -1 on failure.
1394 int crypto_seed_rng(void)
1397 static int provider_set
= 0;
1398 static HCRYPTPROV provider
;
1399 char buf
[DIGEST_LEN
+1];
1401 if (!provider_set
) {
1402 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
, 0)) {
1403 if (GetLastError() != NTE_BAD_KEYSET
) {
1404 log_fn(LOG_ERR
,"Can't get CryptoAPI provider [1]");
1407 /* Yes, we need to try it twice. */
1408 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1410 log_fn(LOG_ERR
,"Can't get CryptoAPI provider [2]");
1416 if (!CryptGenRandom(provider
, DIGEST_LEN
, buf
)) {
1417 log_fn(LOG_ERR
,"Can't get entropy from CryptoAPI.");
1420 RAND_seed(buf
, DIGEST_LEN
);
1421 /* And add the current screen state to the entropy pool for
1426 static const char *filenames
[] = {
1427 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1431 char buf
[DIGEST_LEN
+1];
1433 for (i
= 0; filenames
[i
]; ++i
) {
1434 fd
= open(filenames
[i
], O_RDONLY
, 0);
1436 log_fn(LOG_INFO
, "Seeding RNG from %s", filenames
[i
]);
1437 n
= read(fd
, buf
, DIGEST_LEN
);
1439 if (n
!= DIGEST_LEN
) {
1440 log_fn(LOG_WARN
, "Error reading from entropy source");
1443 RAND_seed(buf
, DIGEST_LEN
);
1447 log_fn(LOG_WARN
, "Cannot seed RNG -- no entropy source found.");
1452 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1453 * success, -1 on failure.
1455 int crypto_rand(unsigned char *to
, unsigned int n
)
1459 r
= RAND_bytes(to
, n
);
1461 crypto_log_errors(LOG_WARN
, "generating random data");
1462 return (r
== 1) ? 0 : -1;
1465 /** Write n bytes of pseudorandom data to <b>to</b>. Return 0 on
1466 * success, -1 on failure.
1468 void crypto_pseudo_rand(unsigned char *to
, unsigned int n
)
1471 if (RAND_pseudo_bytes(to
, n
) == -1) {
1472 log_fn(LOG_ERR
, "RAND_pseudo_bytes failed unexpectedly.");
1473 crypto_log_errors(LOG_WARN
, "generating random data");
1478 /** Return a pseudorandom integer, chosen uniformly from the values
1479 * between 0 and max-1. */
1480 int crypto_pseudo_rand_int(unsigned int max
) {
1482 unsigned int cutoff
;
1483 tor_assert(max
< UINT_MAX
);
1484 tor_assert(max
> 0); /* don't div by 0 */
1486 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1487 * distribution with clipping at the upper end of unsigned int's
1490 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1492 crypto_pseudo_rand((unsigned char*) &val
, sizeof(val
));
1498 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1500 void *smartlist_choose(const smartlist_t
*sl
) {
1502 len
= smartlist_len(sl
);
1504 return smartlist_get(sl
,crypto_pseudo_rand_int(len
));
1505 return NULL
; /* no elements to choose from */
1508 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1509 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1510 * bytes. Return the number of bytes written on success; -1 if
1511 * destlen is too short, or other failure.
1514 base64_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1519 /* 48 bytes of input -> 64 bytes of output plus newline.
1520 Plus one more byte, in case I'm wrong.
1522 if (destlen
< ((srclen
/48)+1)*66)
1524 if (destlen
> SIZE_T_CEILING
)
1527 EVP_EncodeInit(&ctx
);
1528 EVP_EncodeUpdate(&ctx
, dest
, &len
, (char*) src
, srclen
);
1529 EVP_EncodeFinal(&ctx
, dest
+len
, &ret
);
1534 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1535 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1536 * bytes. Return the number of bytes written on success; -1 if
1537 * destlen is too short, or other failure.
1539 * NOTE: destlen should be a little longer than the amount of data it
1540 * will contain, since we check for sufficient space conservatively.
1541 * Here, "a little" is around 64-ish bytes.
1544 base64_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1548 /* 64 bytes of input -> *up to* 48 bytes of output.
1549 Plus one more byte, in case I'm wrong.
1551 if (destlen
< ((srclen
/64)+1)*49)
1553 if (destlen
> SIZE_T_CEILING
)
1556 EVP_DecodeInit(&ctx
);
1557 EVP_DecodeUpdate(&ctx
, dest
, &len
, (char*) src
, srclen
);
1558 EVP_DecodeFinal(&ctx
, dest
, &ret
);
1563 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1564 * that srclen*8 is a multiple of 5.
1567 base32_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1569 unsigned int nbits
, i
, bit
, v
, u
;
1572 tor_assert((nbits
%5) == 0); /* We need an even multiple of 5 bits. */
1573 tor_assert((nbits
/5)+1 <= destlen
); /* We need enough space. */
1574 tor_assert(destlen
< SIZE_T_CEILING
);
1576 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1577 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1578 v
= ((uint8_t)src
[bit
/8]) << 8;
1579 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1580 /* set u to the 5-bit value at the bit'th bit of src. */
1581 u
= (v
>> (11-(bit
%8))) & 0x1F;
1582 dest
[i
] = BASE32_CHARS
[u
];
1587 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1588 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1589 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1590 * are a salt; the 9th byte describes how much iteration to do.
1591 * Does not support <b>key_out_len</b> > DIGEST_LEN.
1594 secret_to_key(char *key_out
, size_t key_out_len
, const char *secret
,
1595 size_t secret_len
, const char *s2k_specifier
)
1597 crypto_digest_env_t
*d
;
1601 tor_assert(key_out_len
< SIZE_T_CEILING
);
1604 c
= s2k_specifier
[8];
1605 count
= ((uint32_t)16 + (c
& 15)) << ((c
>> 4) + EXPBIAS
);
1608 tor_assert(key_out_len
<= DIGEST_LEN
);
1610 d
= crypto_new_digest_env();
1611 tmp
= tor_malloc(8+secret_len
);
1612 memcpy(tmp
,s2k_specifier
,8);
1613 memcpy(tmp
+8,secret
,secret_len
);
1616 if (count
>= secret_len
) {
1617 crypto_digest_add_bytes(d
, tmp
, secret_len
);
1618 count
-= secret_len
;
1620 crypto_digest_add_bytes(d
, tmp
, count
);
1624 crypto_digest_get_digest(d
, key_out
, key_out_len
);
1626 crypto_free_digest_env(d
);