1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
8 #define WIN32_WINNT 0x400
9 #define _WIN32_WINNT 0x400
10 #define WIN32_LEAN_AND_MEAN
17 #include <openssl/err.h>
18 #include <openssl/rsa.h>
19 #include <openssl/pem.h>
20 #include <openssl/evp.h>
21 #include <openssl/rand.h>
22 #include <openssl/opensslv.h>
23 #include <openssl/bn.h>
24 #include <openssl/dh.h>
25 #include <openssl/rsa.h>
26 #include <openssl/dh.h>
42 #ifdef HAVE_SYS_FCNTL_H
43 #include <sys/fcntl.h>
51 #if OPENSSL_VERSION_NUMBER < 0x00905000l
52 #error "We require openssl >= 0.9.5"
53 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
58 * Certain functions that return a success code in OpenSSL 0.9.6 return void
59 * (and don't indicate errors) in OpenSSL version 0.9.5.
61 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
64 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
66 #define RETURN_SSL_OUTCOME(exp) return !(exp)
69 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
70 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
72 struct crypto_pk_env_t
74 int refs
; /* reference counting; so we don't have to copy keys */
78 struct crypto_cipher_env_t
80 unsigned char key
[CIPHER_KEY_LEN
];
81 unsigned char iv
[CIPHER_IV_LEN
+1];
82 /* +1 because some compilers don't like a length of 0 */
83 aes_cnt_cipher_t
*cipher
;
86 struct crypto_dh_env_t
{
91 crypto_get_rsa_padding_overhead(int padding
) {
94 case RSA_NO_PADDING
: return 0;
95 case RSA_PKCS1_OAEP_PADDING
: return 42;
96 case RSA_PKCS1_PADDING
: return 11;
97 default: tor_assert(0); return -1;
102 crypto_get_rsa_padding(int padding
) {
105 case PK_NO_PADDING
: return RSA_NO_PADDING
;
106 case PK_PKCS1_PADDING
: return RSA_PKCS1_PADDING
;
107 case PK_PKCS1_OAEP_PADDING
: return RSA_PKCS1_OAEP_PADDING
;
108 default: tor_assert(0); return -1;
112 static int _crypto_global_initialized
= 0;
117 crypto_log_errors(int severity
, const char *doing
)
120 const char *msg
, *lib
, *func
;
121 while ((err
= ERR_get_error()) != 0) {
122 msg
= (const char*)ERR_reason_error_string(err
);
123 lib
= (const char*)ERR_lib_error_string(err
);
124 func
= (const char*)ERR_func_error_string(err
);
125 if (!msg
) msg
= "(null)";
127 log(severity
, "crypto error while %s: %s (in %s:%s)", doing
, msg
, lib
,func
);
129 log(severity
, "crypto error: %s (in %s:%s)", msg
, lib
, func
);
133 int crypto_global_init()
135 if (!_crypto_global_initialized
) {
136 ERR_load_crypto_strings();
137 _crypto_global_initialized
= 1;
142 int crypto_global_cleanup()
148 /* used by tortls.c */
149 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
)
151 crypto_pk_env_t
*env
;
153 env
= tor_malloc(sizeof(crypto_pk_env_t
));
159 /* used by tortls.c */
160 RSA
*_crypto_pk_env_get_rsa(crypto_pk_env_t
*env
)
165 /* used by tortls.c */
166 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private)
169 EVP_PKEY
*pkey
= NULL
;
170 tor_assert(env
->key
);
172 if (!(key
= RSAPrivateKey_dup(env
->key
)))
175 if (!(key
= RSAPublicKey_dup(env
->key
)))
178 if (!(pkey
= EVP_PKEY_new()))
180 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
191 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
)
196 crypto_pk_env_t
*crypto_new_pk_env(void)
201 if (!rsa
) return NULL
;
202 return _crypto_new_pk_env_rsa(rsa
);
205 void crypto_free_pk_env(crypto_pk_env_t
*env
)
219 /* Create a new crypto_cipher_env_t for a given onion cipher type, key,
220 * iv, and encryption flag (1=encrypt, 0=decrypt). Return the crypto object
221 * on success; NULL on failure.
223 crypto_cipher_env_t
*
224 crypto_create_init_cipher(const char *key
, const char *iv
, int encrypt_mode
)
227 crypto_cipher_env_t
*crypto
= NULL
;
229 if (! (crypto
= crypto_new_cipher_env())) {
230 log_fn(LOG_WARN
, "Unable to allocate crypto object");
234 if (crypto_cipher_set_key(crypto
, key
)) {
235 crypto_log_errors(LOG_WARN
, "setting symmetric key");
239 if (crypto_cipher_set_iv(crypto
, iv
)) {
240 crypto_log_errors(LOG_WARN
, "setting IV");
245 r
= crypto_cipher_encrypt_init_cipher(crypto
);
247 r
= crypto_cipher_decrypt_init_cipher(crypto
);
255 crypto_free_cipher_env(crypto
);
259 crypto_cipher_env_t
*crypto_new_cipher_env()
261 crypto_cipher_env_t
*env
;
263 env
= tor_malloc_zero(sizeof(crypto_cipher_env_t
));
264 env
->cipher
= aes_new_cipher();
268 void crypto_free_cipher_env(crypto_cipher_env_t
*env
)
272 tor_assert(env
->cipher
);
273 aes_free_cipher(env
->cipher
);
277 /* public key crypto */
278 int crypto_pk_generate_key(crypto_pk_env_t
*env
)
284 env
->key
= RSA_generate_key(PK_BITS
,65537, NULL
, NULL
);
286 crypto_log_errors(LOG_WARN
, "generating RSA key");
293 static int crypto_pk_read_private_key_from_file(crypto_pk_env_t
*env
,
296 tor_assert(env
&& src
);
300 env
->key
= PEM_read_RSAPrivateKey(src
, NULL
, NULL
, NULL
);
302 crypto_log_errors(LOG_WARN
, "reading private key from file");
309 int crypto_pk_read_private_key_from_filename(crypto_pk_env_t
*env
, const char *keyfile
)
313 tor_assert(env
&& keyfile
);
315 if(strspn(keyfile
,CONFIG_LEGAL_FILENAME_CHARACTERS
) != strlen(keyfile
)) {
316 /* filename contains nonlegal characters */
320 /* open the keyfile */
321 f_pr
=fopen(keyfile
,"rb");
325 /* read the private key */
326 if(crypto_pk_read_private_key_from_file(env
, f_pr
) < 0) {
332 /* check the private key */
333 if (crypto_pk_check_key(env
) <= 0)
339 int crypto_pk_write_public_key_to_string(crypto_pk_env_t
*env
, char **dest
, int *len
) {
343 tor_assert(env
&& env
->key
&& dest
);
345 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
347 /* Now you can treat b as if it were a file. Just use the
348 * PEM_*_bio_* functions instead of the non-bio variants.
350 if(!PEM_write_bio_RSAPublicKey(b
, env
->key
)) {
351 crypto_log_errors(LOG_WARN
, "writing public key to string");
355 BIO_get_mem_ptr(b
, &buf
);
356 BIO_set_close(b
, BIO_NOCLOSE
); /* so BIO_free doesn't free buf */
359 *dest
= tor_malloc(buf
->length
+1);
360 memcpy(*dest
, buf
->data
, buf
->length
);
361 (*dest
)[buf
->length
] = 0; /* null terminate it */
368 int crypto_pk_read_public_key_from_string(crypto_pk_env_t
*env
, const char *src
, int len
) {
371 tor_assert(env
&& src
);
373 b
= BIO_new(BIO_s_mem()); /* Create a memory BIO */
375 BIO_write(b
, src
, len
);
379 env
->key
= PEM_read_bio_RSAPublicKey(b
, NULL
, NULL
, NULL
);
382 crypto_log_errors(LOG_WARN
, "reading public key from string");
390 crypto_pk_write_private_key_to_filename(crypto_pk_env_t
*env
,
399 tor_assert(PRIVATE_KEY_OK(env
));
401 if (!(bio
= BIO_new(BIO_s_mem())))
403 if (PEM_write_bio_RSAPrivateKey(bio
, env
->key
, NULL
,NULL
,0,NULL
,NULL
)
405 crypto_log_errors(LOG_WARN
, "writing private key");
409 len
= BIO_get_mem_data(bio
, &cp
);
410 s
= tor_malloc(len
+1);
413 r
= write_str_to_file(fname
, s
);
419 int crypto_pk_check_key(crypto_pk_env_t
*env
)
424 r
= RSA_check_key(env
->key
);
426 crypto_log_errors(LOG_WARN
,"checking RSA key");
430 int crypto_pk_cmp_keys(crypto_pk_env_t
*a
, crypto_pk_env_t
*b
) {
436 if (!a
->key
|| !b
->key
)
439 tor_assert(PUBLIC_KEY_OK(a
));
440 tor_assert(PUBLIC_KEY_OK(b
));
441 result
= BN_cmp((a
->key
)->n
, (b
->key
)->n
);
444 return BN_cmp((a
->key
)->e
, (b
->key
)->e
);
447 /* return the size of the public key modulus in 'env', in bytes. */
448 int crypto_pk_keysize(crypto_pk_env_t
*env
)
450 tor_assert(env
&& env
->key
);
452 return RSA_size(env
->key
);
455 crypto_pk_env_t
*crypto_pk_dup_key(crypto_pk_env_t
*env
) {
456 tor_assert(env
&& env
->key
);
462 int crypto_pk_public_encrypt(crypto_pk_env_t
*env
, const unsigned char *from
, int fromlen
, unsigned char *to
, int padding
)
465 tor_assert(env
&& from
&& to
);
467 r
= RSA_public_encrypt(fromlen
, (unsigned char*)from
, to
, env
->key
,
468 crypto_get_rsa_padding(padding
));
470 crypto_log_errors(LOG_WARN
, "performing RSA encryption");
474 int crypto_pk_private_decrypt(crypto_pk_env_t
*env
, const unsigned char *from
, int fromlen
, unsigned char *to
, int padding
)
477 tor_assert(env
&& from
&& to
&& env
->key
);
479 /* Not a private key */
482 r
= RSA_private_decrypt(fromlen
, (unsigned char*)from
, to
, env
->key
,
483 crypto_get_rsa_padding(padding
));
485 crypto_log_errors(LOG_WARN
, "performing RSA decryption");
489 int crypto_pk_public_checksig(crypto_pk_env_t
*env
, const unsigned char *from
, int fromlen
, unsigned char *to
)
492 tor_assert(env
&& from
&& to
);
493 r
= RSA_public_decrypt(fromlen
, (unsigned char*)from
, to
, env
->key
, RSA_PKCS1_PADDING
);
496 crypto_log_errors(LOG_WARN
, "checking RSA signature");
500 int crypto_pk_private_sign(crypto_pk_env_t
*env
, const unsigned char *from
, int fromlen
, unsigned char *to
)
503 tor_assert(env
&& from
&& to
);
505 /* Not a private key */
508 r
= RSA_private_encrypt(fromlen
, (unsigned char*)from
, to
, env
->key
, RSA_PKCS1_PADDING
);
510 crypto_log_errors(LOG_WARN
, "generating RSA signature");
514 /* Return 0 if sig is a correct signature for SHA1(data). Else return -1.
516 int crypto_pk_public_checksig_digest(crypto_pk_env_t
*env
, const unsigned char *data
, int datalen
, const unsigned char *sig
, int siglen
)
518 char digest
[DIGEST_LEN
];
519 char buf
[PK_BYTES
+1];
522 tor_assert(env
&& data
&& sig
);
524 if (crypto_digest(data
,datalen
,digest
)<0) {
525 log_fn(LOG_WARN
, "couldn't compute digest");
528 r
= crypto_pk_public_checksig(env
,sig
,siglen
,buf
);
529 if (r
!= DIGEST_LEN
) {
530 log_fn(LOG_WARN
, "Invalid signature");
533 if (memcmp(buf
, digest
, DIGEST_LEN
)) {
534 log_fn(LOG_WARN
, "Signature mismatched with digest.");
541 /* Fill 'to' with a signature of SHA1(from).
543 int crypto_pk_private_sign_digest(crypto_pk_env_t
*env
, const unsigned char *from
, int fromlen
, unsigned char *to
)
545 char digest
[DIGEST_LEN
];
546 if (crypto_digest(from
,fromlen
,digest
)<0)
548 return crypto_pk_private_sign(env
,digest
,DIGEST_LEN
,to
);
552 /* Perform a hybrid (public/secret) encryption on 'fromlen' bytes of data
553 * from 'from', with padding type 'padding', storing the results on 'to'.
555 * If no padding is used, the public key must be at least as large as
558 * Returns the number of bytes written on success, -1 on failure.
560 * The encrypted data consists of:
562 * The source data, padded and encrypted with the public key, if the
563 * padded source data is no longer than the public key, and "force"
566 * The beginning of the source data prefixed with a 16-byte symmetric key,
567 * padded and encrypted with the public key; followed by the rest of
568 * the source data encrypted in AES-CTR mode with the symmetric key.
571 int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t
*env
,
572 const unsigned char *from
,
573 int fromlen
, unsigned char *to
,
574 int padding
, int force
)
576 int overhead
, pkeylen
, outlen
, r
, symlen
;
577 crypto_cipher_env_t
*cipher
= NULL
;
578 char buf
[PK_BYTES
+1];
580 tor_assert(env
&& from
&& to
);
582 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
583 pkeylen
= crypto_pk_keysize(env
);
585 if (padding
== PK_NO_PADDING
&& fromlen
< pkeylen
)
588 if (!force
&& fromlen
+overhead
<= pkeylen
) {
589 /* It all fits in a single encrypt. */
590 return crypto_pk_public_encrypt(env
,from
,fromlen
,to
,padding
);
592 cipher
= crypto_new_cipher_env();
593 if (!cipher
) return -1;
594 if (crypto_cipher_generate_key(cipher
)<0)
596 /* You can't just run around RSA-encrypting any bitstream: if it's
597 * greater than the RSA key, then OpenSSL will happily encrypt, and
598 * later decrypt to the wrong value. So we set the first bit of
599 * 'cipher->key' to 0 if we aren't padding. This means that our
600 * symmetric key is really only 127 bits.
602 if (padding
== PK_NO_PADDING
)
603 cipher
->key
[0] &= 0x7f;
604 if (crypto_cipher_encrypt_init_cipher(cipher
)<0)
606 memcpy(buf
, cipher
->key
, CIPHER_KEY_LEN
);
607 memcpy(buf
+CIPHER_KEY_LEN
, from
, pkeylen
-overhead
-CIPHER_KEY_LEN
);
609 /* Length of symmetrically encrypted data. */
610 symlen
= fromlen
-(pkeylen
-overhead
-CIPHER_KEY_LEN
);
612 outlen
= crypto_pk_public_encrypt(env
,buf
,pkeylen
-overhead
,to
,padding
);
613 if (outlen
!=pkeylen
) {
616 r
= crypto_cipher_encrypt(cipher
,
617 from
+pkeylen
-overhead
-CIPHER_KEY_LEN
, symlen
,
621 memset(buf
, 0, sizeof(buf
));
622 crypto_free_cipher_env(cipher
);
623 return outlen
+ symlen
;
625 memset(buf
, 0, sizeof(buf
));
626 if (cipher
) crypto_free_cipher_env(cipher
);
630 /* Invert crypto_pk_public_hybrid_encrypt. */
631 int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t
*env
,
632 const unsigned char *from
,
633 int fromlen
, unsigned char *to
,
636 int overhead
, pkeylen
, outlen
, r
;
637 crypto_cipher_env_t
*cipher
= NULL
;
638 char buf
[PK_BYTES
+1];
640 overhead
= crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding
));
641 pkeylen
= crypto_pk_keysize(env
);
643 if (fromlen
<= pkeylen
) {
644 return crypto_pk_private_decrypt(env
,from
,fromlen
,to
,padding
);
646 outlen
= crypto_pk_private_decrypt(env
,from
,pkeylen
,buf
,padding
);
648 /* this is only log-levelinfo, because when we're decrypting
649 * onions, we try several keys to see which will work */
650 log_fn(LOG_INFO
, "Error decrypting public-key data");
653 if (outlen
< CIPHER_KEY_LEN
) {
654 log_fn(LOG_WARN
, "No room for a symmetric key");
657 cipher
= crypto_create_init_cipher(buf
, NULL
, 0);
661 memcpy(to
,buf
+CIPHER_KEY_LEN
,outlen
-CIPHER_KEY_LEN
);
662 outlen
-= CIPHER_KEY_LEN
;
663 r
= crypto_cipher_decrypt(cipher
, from
+pkeylen
, fromlen
-pkeylen
,
667 memset(buf
,0,sizeof(buf
));
668 crypto_free_cipher_env(cipher
);
669 return outlen
+ (fromlen
-pkeylen
);
671 memset(buf
,0,sizeof(buf
));
672 if (cipher
) crypto_free_cipher_env(cipher
);
676 /* Encode the public portion of 'pk' into 'dest'. Return -1 on error,
677 * or the number of characters used on success.
679 int crypto_pk_asn1_encode(crypto_pk_env_t
*pk
, char *dest
, int dest_len
)
682 unsigned char *buf
, *cp
;
683 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
684 if (len
< 0 || len
> dest_len
)
686 cp
= buf
= tor_malloc(len
+1);
687 len
= i2d_RSAPublicKey(pk
->key
, &cp
);
689 crypto_log_errors(LOG_WARN
,"encoding public key");
693 /* We don't encode directly into 'dest', because that would be illegal
694 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
696 memcpy(dest
,buf
,len
);
701 /* Decode an ASN1-encoded public key from str.
703 crypto_pk_env_t
*crypto_pk_asn1_decode(const char *str
, int len
)
707 /* This ifdef suppresses a type warning. Take out the first case once
708 * everybody is using openssl 0.9.7 or later.
710 #if OPENSSL_VERSION_NUMBER < 0x00907000l
713 const unsigned char *cp
;
715 cp
= buf
= tor_malloc(len
);
717 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
720 crypto_log_errors(LOG_WARN
,"decoding public key");
723 return _crypto_new_pk_env_rsa(rsa
);
726 /* Given a private or public key pk, put a SHA1 hash of the public key into
727 * digest_out (must have DIGEST_LEN bytes of space).
729 int crypto_pk_get_digest(crypto_pk_env_t
*pk
, char *digest_out
)
731 unsigned char *buf
, *bufp
;
734 len
= i2d_RSAPublicKey(pk
->key
, NULL
);
737 buf
= bufp
= tor_malloc(len
+1);
738 len
= i2d_RSAPublicKey(pk
->key
, &bufp
);
740 crypto_log_errors(LOG_WARN
,"encoding public key");
744 if (crypto_digest(buf
, len
, digest_out
) < 0) {
752 /* Given a private or public key pk, put a fingerprint of the
753 * public key into fp_out (must have at least FINGERPRINT_LEN+1 bytes of
757 crypto_pk_get_fingerprint(crypto_pk_env_t
*pk
, char *fp_out
)
760 unsigned char digest
[DIGEST_LEN
];
761 unsigned char buf
[FINGERPRINT_LEN
+1];
763 if (crypto_pk_get_digest(pk
, digest
)) {
767 for (i
= 0; i
< DIGEST_LEN
; ++i
) {
768 sprintf(bufp
,"%02X",digest
[i
]);
770 if (i
%2 && i
!= 19) {
775 tor_assert(strlen(buf
) == FINGERPRINT_LEN
);
776 tor_assert(crypto_pk_check_fingerprint_syntax(buf
));
782 crypto_pk_check_fingerprint_syntax(const char *s
)
785 for (i
= 0; i
< FINGERPRINT_LEN
; ++i
) {
787 if (!isspace((int)s
[i
])) return 0;
789 if (!isxdigit((int)s
[i
])) return 0;
792 if (s
[FINGERPRINT_LEN
]) return 0;
796 /* symmetric crypto */
797 int crypto_cipher_generate_key(crypto_cipher_env_t
*env
)
801 return crypto_rand(CIPHER_KEY_LEN
, env
->key
);
804 int crypto_cipher_set_iv(crypto_cipher_env_t
*env
, const unsigned char *iv
)
806 tor_assert(env
&& (CIPHER_IV_LEN
==0 || iv
));
814 memcpy(env
->iv
, iv
, CIPHER_IV_LEN
);
819 int crypto_cipher_set_key(crypto_cipher_env_t
*env
, const unsigned char *key
)
821 tor_assert(env
&& key
);
826 memcpy(env
->key
, key
, CIPHER_KEY_LEN
);
831 const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t
*env
)
836 int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t
*env
)
840 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
844 int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t
*env
)
848 aes_set_key(env
->cipher
, env
->key
, CIPHER_KEY_LEN
*8);
852 int crypto_cipher_encrypt(crypto_cipher_env_t
*env
, const unsigned char *from
, unsigned int fromlen
, unsigned char *to
)
854 tor_assert(env
&& env
->cipher
&& from
&& fromlen
&& to
);
856 aes_crypt(env
->cipher
, from
, fromlen
, to
);
860 int crypto_cipher_decrypt(crypto_cipher_env_t
*env
, const unsigned char *from
, unsigned int fromlen
, unsigned char *to
)
862 tor_assert(env
&& from
&& to
);
864 aes_crypt(env
->cipher
, from
, fromlen
, to
);
869 crypto_cipher_rewind(crypto_cipher_env_t
*env
, long delta
)
871 return crypto_cipher_advance(env
, -delta
);
875 crypto_cipher_advance(crypto_cipher_env_t
*env
, long delta
)
877 aes_adjust_counter(env
->cipher
, delta
);
882 int crypto_digest(const unsigned char *m
, int len
, unsigned char *digest
)
884 tor_assert(m
&& digest
);
885 return (SHA1(m
,len
,digest
) == NULL
);
888 struct crypto_digest_env_t
{
892 crypto_digest_env_t
*
893 crypto_new_digest_env(void)
895 crypto_digest_env_t
*r
;
896 r
= tor_malloc(sizeof(crypto_digest_env_t
));
902 crypto_free_digest_env(crypto_digest_env_t
*digest
) {
907 crypto_digest_add_bytes(crypto_digest_env_t
*digest
, const char *data
,
912 SHA1_Update(&digest
->d
, (void*)data
, len
);
915 void crypto_digest_get_digest(crypto_digest_env_t
*digest
,
916 char *out
, size_t out_len
)
918 static char r
[DIGEST_LEN
];
919 tor_assert(digest
&& out
);
920 tor_assert(out_len
<= DIGEST_LEN
);
921 SHA1_Final(r
, &digest
->d
);
922 memcpy(out
, r
, out_len
);
925 crypto_digest_env_t
*
926 crypto_digest_dup(const crypto_digest_env_t
*digest
)
928 crypto_digest_env_t
*r
;
930 r
= tor_malloc(sizeof(crypto_digest_env_t
));
931 memcpy(r
,digest
,sizeof(crypto_digest_env_t
));
936 crypto_digest_assign(crypto_digest_env_t
*into
,
937 const crypto_digest_env_t
*from
)
939 tor_assert(into
&& from
);
940 memcpy(into
,from
,sizeof(crypto_digest_env_t
));
944 static BIGNUM
*dh_param_p
= NULL
;
945 static BIGNUM
*dh_param_g
= NULL
;
947 static void init_dh_param() {
950 if (dh_param_p
&& dh_param_g
)
958 /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
959 prime, and supposedly it equals:
960 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
963 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
964 "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
965 "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
966 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
967 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
968 "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
969 "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
970 "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
973 /* This is from rfc2409, section 6.2. It's a safe prime, and
974 supposedly it equals:
975 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
977 /* See also rfc 3536 */
979 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
980 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
981 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
982 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
983 "49286651ECE65381FFFFFFFFFFFFFFFF");
986 r
= BN_set_word(g
, 2);
992 crypto_dh_env_t
*crypto_dh_new()
994 crypto_dh_env_t
*res
= NULL
;
999 res
= tor_malloc(sizeof(crypto_dh_env_t
));
1002 if (!(res
->dh
= DH_new()))
1005 if (!(res
->dh
->p
= BN_dup(dh_param_p
)))
1008 if (!(res
->dh
->g
= BN_dup(dh_param_g
)))
1013 crypto_log_errors(LOG_WARN
, "creating DH object");
1014 if (res
&& res
->dh
) DH_free(res
->dh
); /* frees p and g too */
1018 int crypto_dh_get_bytes(crypto_dh_env_t
*dh
)
1021 return DH_size(dh
->dh
);
1023 int crypto_dh_generate_public(crypto_dh_env_t
*dh
)
1025 if (!DH_generate_key(dh
->dh
)) {
1026 crypto_log_errors(LOG_WARN
, "generating DH key");
1031 int crypto_dh_get_public(crypto_dh_env_t
*dh
, char *pubkey
, int pubkey_len
)
1035 if (!dh
->dh
->pub_key
) {
1036 if (crypto_dh_generate_public(dh
)<0)
1040 tor_assert(dh
->dh
->pub_key
);
1041 bytes
= BN_num_bytes(dh
->dh
->pub_key
);
1042 if (pubkey_len
< bytes
)
1045 memset(pubkey
, 0, pubkey_len
);
1046 BN_bn2bin(dh
->dh
->pub_key
, pubkey
+(pubkey_len
-bytes
));
1052 #define MIN(a,b) ((a)<(b)?(a):(b))
1053 int crypto_dh_compute_secret(crypto_dh_env_t
*dh
,
1054 const char *pubkey
, int pubkey_len
,
1055 char *secret_out
, int secret_bytes_out
)
1057 unsigned char hash
[DIGEST_LEN
];
1058 unsigned char *secret_tmp
= NULL
;
1059 BIGNUM
*pubkey_bn
= NULL
;
1063 tor_assert(secret_bytes_out
/DIGEST_LEN
<= 255);
1065 if (!(pubkey_bn
= BN_bin2bn(pubkey
, pubkey_len
, NULL
)))
1067 secret_tmp
= tor_malloc(crypto_dh_get_bytes(dh
)+1);
1068 secret_len
= DH_compute_key(secret_tmp
, pubkey_bn
, dh
->dh
);
1069 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1070 for (i
= 0; i
< secret_bytes_out
; i
+= DIGEST_LEN
) {
1071 secret_tmp
[secret_len
] = (unsigned char) i
/DIGEST_LEN
;
1072 if (crypto_digest(secret_tmp
, secret_len
+1, hash
))
1074 memcpy(secret_out
+i
, hash
, MIN(DIGEST_LEN
, secret_bytes_out
-i
));
1076 secret_len
= secret_bytes_out
;
1082 crypto_log_errors(LOG_WARN
, "completing DH handshake");
1085 tor_free(secret_tmp
);
1088 void crypto_dh_free(crypto_dh_env_t
*dh
)
1090 tor_assert(dh
&& dh
->dh
);
1095 /* random numbers */
1097 int crypto_seed_rng()
1099 static int provider_set
= 0;
1100 static HCRYPTPROV provider
;
1101 char buf
[DIGEST_LEN
+1];
1103 if (!provider_set
) {
1104 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
, 0)) {
1105 if (GetLastError() != NTE_BAD_KEYSET
) {
1106 log_fn(LOG_ERR
,"Can't get CryptoAPI provider [1]");
1109 /* Yes, we need to try it twice. */
1110 if (!CryptAcquireContext(&provider
, NULL
, NULL
, PROV_RSA_FULL
,
1112 log_fn(LOG_ERR
,"Can't get CryptoAPI provider [2]");
1118 if (!CryptGenRandom(provider
, DIGEST_LEN
, buf
)) {
1119 log_fn(LOG_ERR
,"Can't get entropy from CryptoAPI.");
1122 RAND_seed(buf
, DIGEST_LEN
);
1123 /* And add the current screen state to the entopy pool for
1129 int crypto_seed_rng()
1131 static char *filenames
[] = {
1132 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1136 char buf
[DIGEST_LEN
+1];
1138 for (i
= 0; filenames
[i
]; ++i
) {
1139 fd
= open(filenames
[i
], O_RDONLY
, 0);
1141 log_fn(LOG_INFO
, "Seeding RNG from %s", filenames
[i
]);
1142 n
= read(fd
, buf
, DIGEST_LEN
);
1144 if (n
!= DIGEST_LEN
) {
1145 log_fn(LOG_WARN
, "Error reading from entropy source");
1148 RAND_seed(buf
, DIGEST_LEN
);
1152 log_fn(LOG_WARN
, "Cannot seed RNG -- no entropy source found.");
1157 int crypto_rand(unsigned int n
, unsigned char *to
)
1161 r
= RAND_bytes(to
, n
);
1163 crypto_log_errors(LOG_WARN
, "generating random data");
1167 void crypto_pseudo_rand(unsigned int n
, unsigned char *to
)
1170 if (RAND_pseudo_bytes(to
, n
) == -1) {
1171 log_fn(LOG_ERR
, "RAND_pseudo_bytes failed unexpectedly.");
1172 crypto_log_errors(LOG_WARN
, "generating random data");
1177 /* return a pseudo random number between 0 and max-1 */
1178 int crypto_pseudo_rand_int(unsigned int max
) {
1180 unsigned int cutoff
;
1181 tor_assert(max
< UINT_MAX
);
1182 tor_assert(max
> 0); /* don't div by 0 */
1184 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1185 * distribution with clipping at the upper end of unsigned int's
1188 cutoff
= UINT_MAX
- (UINT_MAX
%max
);
1190 crypto_pseudo_rand(sizeof(val
), (unsigned char*) &val
);
1197 base64_encode(char *dest
, int destlen
, const char *src
, int srclen
)
1202 /* 48 bytes of input -> 64 bytes of output plus newline.
1203 Plus one more byte, in case I'm wrong.
1205 if (destlen
< ((srclen
/48)+1)*66)
1208 EVP_EncodeInit(&ctx
);
1209 EVP_EncodeUpdate(&ctx
, dest
, &len
, (char*) src
, srclen
);
1210 EVP_EncodeFinal(&ctx
, dest
+len
, &ret
);
1215 base64_decode(char *dest
, int destlen
, const char *src
, int srclen
)
1219 /* 64 bytes of input -> *up to* 48 bytes of output.
1220 Plus one more byte, in caes I'm wrong.
1222 if (destlen
< ((srclen
/64)+1)*49)
1225 EVP_DecodeInit(&ctx
);
1226 EVP_DecodeUpdate(&ctx
, dest
, &len
, (char*) src
, srclen
);
1227 EVP_DecodeFinal(&ctx
, dest
, &ret
);
1232 /* Implement base32 encoding as in rfc3548. Limitation: Requires that
1233 * srclen is a multiple of 5.
1236 base32_encode(char *dest
, int destlen
, const char *src
, int srclen
)
1238 int nbits
, i
, bit
, v
, u
;
1242 /* We need an even multiple of 5 bits. */
1244 if ((nbits
/5)+1 > destlen
)
1245 /* Not enough space. */
1248 for (i
=0,bit
=0; bit
< nbits
; ++i
, bit
+=5) {
1249 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1250 v
= ((uint8_t)src
[bit
/8]) << 8;
1251 if (bit
+5<nbits
) v
+= (uint8_t)src
[(bit
/8)+1];
1252 /* set u to the 5-bit value at the bit'th bit of src. */
1253 u
= (v
>> (11-(bit
%8))) & 0x1F;
1254 dest
[i
] = BASE32_CHARS
[u
];
1263 indent-tabs-mode:nil