man page entries for TunnelDirConns and PreferTunneledDirConns
[tor.git] / src / common / crypto.c
blob0cc393be3e8908618a76c340bfe15b7a79f05df9
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char crypto_c_id[] =
7 "$Id$";
9 /**
10 * \file crypto.c
11 * \brief Wrapper functions to present a consistent interface to
12 * public-key and symmetric cryptography operations from OpenSSL.
13 **/
15 #include "orconfig.h"
17 #ifdef MS_WINDOWS
18 #define WIN32_WINNT 0x400
19 #define _WIN32_WINNT 0x400
20 #define WIN32_LEAN_AND_MEAN
21 #include <windows.h>
22 #include <wincrypt.h>
23 #endif
25 #include <string.h>
27 #include <openssl/err.h>
28 #include <openssl/rsa.h>
29 #include <openssl/pem.h>
30 #include <openssl/evp.h>
31 #include <openssl/rand.h>
32 #include <openssl/opensslv.h>
33 #include <openssl/bn.h>
34 #include <openssl/dh.h>
35 #include <openssl/rsa.h>
36 #include <openssl/dh.h>
37 #include <openssl/conf.h>
39 #include <stdlib.h>
40 #include <assert.h>
41 #include <stdio.h>
42 #include <limits.h>
44 #ifdef HAVE_CTYPE_H
45 #include <ctype.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #ifdef HAVE_SYS_FCNTL_H
54 #include <sys/fcntl.h>
55 #endif
57 #include "crypto.h"
58 #include "log.h"
59 #include "aes.h"
60 #include "util.h"
61 #include "container.h"
62 #include "compat.h"
64 #if OPENSSL_VERSION_NUMBER < 0x00905000l
65 #error "We require openssl >= 0.9.5"
66 #endif
68 #if OPENSSL_VERSION_NUMBER < 0x00907000l
69 #define NO_ENGINES
70 #else
71 #include <openssl/engine.h>
72 #endif
74 /** Macro: is k a valid RSA public or private key? */
75 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
76 /** Macro: is k a valid RSA private key? */
77 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
79 #ifdef TOR_IS_MULTITHREADED
80 /** A number of prealloced mutexes for use by openssl. */
81 static tor_mutex_t **_openssl_mutexes = NULL;
82 /** How many mutexes have we allocated for use by openssl? */
83 static int _n_openssl_mutexes = 0;
84 #endif
86 /** A public key, or a public/private keypair. */
87 struct crypto_pk_env_t
89 int refs; /* reference counting so we don't have to copy keys */
90 RSA *key;
93 /** Key and stream information for a stream cipher. */
94 struct crypto_cipher_env_t
96 char key[CIPHER_KEY_LEN];
97 aes_cnt_cipher_t *cipher;
100 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
101 * while we're waiting for the second.*/
102 struct crypto_dh_env_t {
103 DH *dh;
106 /* Prototypes for functions only used by tortls.c */
107 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
108 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
109 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
110 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
112 static int setup_openssl_threading(void);
113 static int tor_check_dh_key(BIGNUM *bn);
115 /** Return the number of bytes added by padding method <b>padding</b>.
117 static INLINE int
118 crypto_get_rsa_padding_overhead(int padding)
120 switch (padding)
122 case RSA_NO_PADDING: return 0;
123 case RSA_PKCS1_OAEP_PADDING: return 42;
124 case RSA_PKCS1_PADDING: return 11;
125 default: tor_assert(0); return -1;
129 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
131 static INLINE int
132 crypto_get_rsa_padding(int padding)
134 switch (padding)
136 case PK_NO_PADDING: return RSA_NO_PADDING;
137 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
138 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
139 default: tor_assert(0); return -1;
143 /** Boolean: has OpenSSL's crypto been initialized? */
144 static int _crypto_global_initialized = 0;
146 /** Log all pending crypto errors at level <b>severity</b>. Use
147 * <b>doing</b> to describe our current activities.
149 static void
150 crypto_log_errors(int severity, const char *doing)
152 unsigned int err;
153 const char *msg, *lib, *func;
154 while ((err = ERR_get_error()) != 0) {
155 msg = (const char*)ERR_reason_error_string(err);
156 lib = (const char*)ERR_lib_error_string(err);
157 func = (const char*)ERR_func_error_string(err);
158 if (!msg) msg = "(null)";
159 if (!lib) lib = "(null)";
160 if (!func) func = "(null)";
161 if (doing) {
162 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
163 doing, msg, lib, func);
164 } else {
165 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
170 #ifndef NO_ENGINES
171 /** Log any OpenSSL engines we're using at NOTICE. */
172 static void
173 log_engine(const char *fn, ENGINE *e)
175 if (e) {
176 const char *name, *id;
177 name = ENGINE_get_name(e);
178 id = ENGINE_get_id(e);
179 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
180 name?name:"?", id?id:"?", fn);
181 } else {
182 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
185 #endif
187 /** Initialize the crypto library. Return 0 on success, -1 on failure.
190 crypto_global_init(int useAccel)
192 if (!_crypto_global_initialized) {
193 ERR_load_crypto_strings();
194 OpenSSL_add_all_algorithms();
195 _crypto_global_initialized = 1;
196 setup_openssl_threading();
197 /* XXX the below is a bug, since we can't know if we're supposed
198 * to be using hardware acceleration or not. we should arrange
199 * for this function to be called before init_keys. But make it
200 * not complain loudly, at least until we make acceleration work. */
201 if (useAccel < 0) {
202 log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
204 #ifndef NO_ENGINES
205 if (useAccel > 0) {
206 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
207 ENGINE_load_builtin_engines();
208 if (!ENGINE_register_all_complete())
209 return -1;
211 /* XXXX make sure this isn't leaking. */
212 log_engine("RSA", ENGINE_get_default_RSA());
213 log_engine("DH", ENGINE_get_default_DH());
214 log_engine("RAND", ENGINE_get_default_RAND());
215 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
216 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
217 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
219 #endif
221 return 0;
224 /** Free crypto resources held by this thread. */
225 void
226 crypto_thread_cleanup(void)
228 ERR_remove_state(0);
231 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
234 crypto_global_cleanup(void)
236 EVP_cleanup();
237 ERR_remove_state(0);
238 ERR_free_strings();
239 #ifndef NO_ENGINES
240 ENGINE_cleanup();
241 CONF_modules_unload(1);
242 CRYPTO_cleanup_all_ex_data();
243 #endif
244 #ifdef TOR_IS_MULTITHREADED
245 if (_n_openssl_mutexes) {
246 int n = _n_openssl_mutexes;
247 tor_mutex_t **ms = _openssl_mutexes;
248 int i;
249 _openssl_mutexes = NULL;
250 _n_openssl_mutexes = 0;
251 for (i=0;i<n;++i) {
252 tor_mutex_free(ms[i]);
254 tor_free(ms);
256 #endif
257 return 0;
260 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
261 crypto_pk_env_t *
262 _crypto_new_pk_env_rsa(RSA *rsa)
264 crypto_pk_env_t *env;
265 tor_assert(rsa);
266 env = tor_malloc(sizeof(crypto_pk_env_t));
267 env->refs = 1;
268 env->key = rsa;
269 return env;
272 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
273 RSA *
274 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
276 return env->key;
279 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
280 * private is set, include the private-key portion of the key. */
281 EVP_PKEY *
282 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
284 RSA *key = NULL;
285 EVP_PKEY *pkey = NULL;
286 tor_assert(env->key);
287 if (private) {
288 if (!(key = RSAPrivateKey_dup(env->key)))
289 goto error;
290 } else {
291 if (!(key = RSAPublicKey_dup(env->key)))
292 goto error;
294 if (!(pkey = EVP_PKEY_new()))
295 goto error;
296 if (!(EVP_PKEY_assign_RSA(pkey, key)))
297 goto error;
298 return pkey;
299 error:
300 if (pkey)
301 EVP_PKEY_free(pkey);
302 if (key)
303 RSA_free(key);
304 return NULL;
307 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
309 DH *
310 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
312 return dh->dh;
315 /** Allocate and return storage for a public key. The key itself will not yet
316 * be set.
318 crypto_pk_env_t *
319 crypto_new_pk_env(void)
321 RSA *rsa;
323 rsa = RSA_new();
324 if (!rsa) return NULL;
325 return _crypto_new_pk_env_rsa(rsa);
328 /** Release a reference to an asymmetric key; when all the references
329 * are released, free the key.
331 void
332 crypto_free_pk_env(crypto_pk_env_t *env)
334 tor_assert(env);
336 if (--env->refs > 0)
337 return;
339 if (env->key)
340 RSA_free(env->key);
342 tor_free(env);
345 /** Create a new symmetric cipher for a given key and encryption flag
346 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
347 * on failure.
349 crypto_cipher_env_t *
350 crypto_create_init_cipher(const char *key, int encrypt_mode)
352 int r;
353 crypto_cipher_env_t *crypto = NULL;
355 if (! (crypto = crypto_new_cipher_env())) {
356 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
357 return NULL;
360 if (crypto_cipher_set_key(crypto, key)) {
361 crypto_log_errors(LOG_WARN, "setting symmetric key");
362 goto error;
365 if (encrypt_mode)
366 r = crypto_cipher_encrypt_init_cipher(crypto);
367 else
368 r = crypto_cipher_decrypt_init_cipher(crypto);
370 if (r)
371 goto error;
372 return crypto;
374 error:
375 if (crypto)
376 crypto_free_cipher_env(crypto);
377 return NULL;
380 /** Allocate and return a new symmetric cipher.
382 crypto_cipher_env_t *
383 crypto_new_cipher_env(void)
385 crypto_cipher_env_t *env;
387 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
388 env->cipher = aes_new_cipher();
389 return env;
392 /** Free a symmetric cipher.
394 void
395 crypto_free_cipher_env(crypto_cipher_env_t *env)
397 tor_assert(env);
399 tor_assert(env->cipher);
400 aes_free_cipher(env->cipher);
401 tor_free(env);
404 /* public key crypto */
406 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
407 * success, -1 on failure.
410 crypto_pk_generate_key(crypto_pk_env_t *env)
412 tor_assert(env);
414 if (env->key)
415 RSA_free(env->key);
416 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
417 if (!env->key) {
418 crypto_log_errors(LOG_WARN, "generating RSA key");
419 return -1;
422 return 0;
425 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
426 * Return 0 on success, -1 on failure.
428 static int
429 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
430 const char *s)
432 BIO *b;
434 tor_assert(env);
435 tor_assert(s);
437 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
438 b = BIO_new_mem_buf((char*)s, -1);
440 if (env->key)
441 RSA_free(env->key);
443 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
445 BIO_free(b);
447 if (!env->key) {
448 crypto_log_errors(LOG_WARN, "Error parsing private key");
449 return -1;
451 return 0;
454 /** Read a PEM-encoded private key from the file named by
455 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
458 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
459 const char *keyfile)
461 char *contents;
462 int r;
464 /* Read the file into a string. */
465 contents = read_file_to_str(keyfile, 0, NULL);
466 if (!contents) {
467 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
468 return -1;
471 /* Try to parse it. */
472 r = crypto_pk_read_private_key_from_string(env, contents);
473 tor_free(contents);
474 if (r)
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)
479 return -1;
481 return 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,
491 size_t *len)
493 BUF_MEM *buf;
494 BIO *b;
496 tor_assert(env);
497 tor_assert(env->key);
498 tor_assert(dest);
500 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
502 /* Now you can treat b as if it were a file. Just use the
503 * PEM_*_bio_* functions instead of the non-bio variants.
505 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
506 crypto_log_errors(LOG_WARN, "writing public key to string");
507 return -1;
510 BIO_get_mem_ptr(b, &buf);
511 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
512 BIO_free(b);
514 tor_assert(buf->length >= 0);
515 *dest = tor_malloc(buf->length+1);
516 memcpy(*dest, buf->data, buf->length);
517 (*dest)[buf->length] = 0; /* nul terminate it */
518 *len = buf->length;
519 BUF_MEM_free(buf);
521 return 0;
524 /** Read a PEM-encoded public key from the first <b>len</b> characters of
525 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
526 * failure.
529 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
530 size_t len)
532 BIO *b;
534 tor_assert(env);
535 tor_assert(src);
537 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
539 BIO_write(b, src, len);
541 if (env->key)
542 RSA_free(env->key);
543 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
544 BIO_free(b);
545 if (!env->key) {
546 crypto_log_errors(LOG_WARN, "reading public key from string");
547 return -1;
550 return 0;
553 /* Write the private key from 'env' into the file named by 'fname',
554 * PEM-encoded. Return 0 on success, -1 on failure.
557 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
558 const char *fname)
560 BIO *bio;
561 char *cp;
562 long len;
563 char *s;
564 int r;
566 tor_assert(PRIVATE_KEY_OK(env));
568 if (!(bio = BIO_new(BIO_s_mem())))
569 return -1;
570 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
571 == 0) {
572 crypto_log_errors(LOG_WARN, "writing private key");
573 BIO_free(bio);
574 return -1;
576 len = BIO_get_mem_data(bio, &cp);
577 tor_assert(len >= 0);
578 s = tor_malloc(len+1);
579 memcpy(s, cp, len);
580 s[len]='\0';
581 r = write_str_to_file(fname, s, 0);
582 BIO_free(bio);
583 tor_free(s);
584 return r;
587 /** Return true iff <b>env</b> has a valid key.
590 crypto_pk_check_key(crypto_pk_env_t *env)
592 int r;
593 tor_assert(env);
595 r = RSA_check_key(env->key);
596 if (r <= 0)
597 crypto_log_errors(LOG_WARN,"checking RSA key");
598 return r;
601 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
602 * if a==b, and 1 if a\>b.
605 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
607 int result;
609 if (!a || !b)
610 return -1;
612 if (!a->key || !b->key)
613 return -1;
615 tor_assert(PUBLIC_KEY_OK(a));
616 tor_assert(PUBLIC_KEY_OK(b));
617 result = BN_cmp((a->key)->n, (b->key)->n);
618 if (result)
619 return result;
620 return BN_cmp((a->key)->e, (b->key)->e);
623 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
624 size_t
625 crypto_pk_keysize(crypto_pk_env_t *env)
627 tor_assert(env);
628 tor_assert(env->key);
630 return (size_t) RSA_size(env->key);
633 /** Increase the reference count of <b>env</b>, and return it.
635 crypto_pk_env_t *
636 crypto_pk_dup_key(crypto_pk_env_t *env)
638 tor_assert(env);
639 tor_assert(env->key);
641 env->refs++;
642 return env;
645 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
646 * in <b>env</b>, using the padding method <b>padding</b>. On success,
647 * write the result to <b>to</b>, and return the number of bytes
648 * written. On failure, return -1.
651 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
652 const char *from, size_t fromlen, int padding)
654 int r;
655 tor_assert(env);
656 tor_assert(from);
657 tor_assert(to);
659 r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
660 env->key, crypto_get_rsa_padding(padding));
661 if (r<0) {
662 crypto_log_errors(LOG_WARN, "performing RSA encryption");
663 return -1;
665 return r;
668 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
669 * in <b>env</b>, using the padding method <b>padding</b>. On success,
670 * write the result to <b>to</b>, and return the number of bytes
671 * written. On failure, return -1.
674 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
675 const char *from, size_t fromlen,
676 int padding, int warnOnFailure)
678 int r;
679 tor_assert(env);
680 tor_assert(from);
681 tor_assert(to);
682 tor_assert(env->key);
683 if (!env->key->p)
684 /* Not a private key */
685 return -1;
687 r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
688 env->key, crypto_get_rsa_padding(padding));
690 if (r<0) {
691 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
692 "performing RSA decryption");
693 return -1;
695 return r;
698 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
699 * public key in <b>env</b>, using PKCS1 padding. On success, write the
700 * signed data to <b>to</b>, and return the number of bytes written.
701 * On failure, return -1.
704 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
705 const char *from, size_t fromlen)
707 int r;
708 tor_assert(env);
709 tor_assert(from);
710 tor_assert(to);
711 r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
712 env->key, RSA_PKCS1_PADDING);
714 if (r<0) {
715 crypto_log_errors(LOG_WARN, "checking RSA signature");
716 return -1;
718 return r;
721 /** Check a siglen-byte long signature at <b>sig</b> against
722 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
723 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
724 * SHA1(data). Else return -1.
727 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
728 int datalen, const char *sig, int siglen)
730 char digest[DIGEST_LEN];
731 char buf[PK_BYTES+1];
732 int r;
734 tor_assert(env);
735 tor_assert(data);
736 tor_assert(sig);
738 if (crypto_digest(digest,data,datalen)<0) {
739 log_warn(LD_BUG, "couldn't compute digest");
740 return -1;
742 r = crypto_pk_public_checksig(env,buf,sig,siglen);
743 if (r != DIGEST_LEN) {
744 log_warn(LD_CRYPTO, "Invalid signature");
745 return -1;
747 if (memcmp(buf, digest, DIGEST_LEN)) {
748 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
749 return -1;
752 return 0;
755 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
756 * <b>env</b>, using PKCS1 padding. On success, write the signature to
757 * <b>to</b>, and return the number of bytes written. On failure, return
758 * -1.
761 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
762 const char *from, size_t fromlen)
764 int r;
765 tor_assert(env);
766 tor_assert(from);
767 tor_assert(to);
768 if (!env->key->p)
769 /* Not a private key */
770 return -1;
772 r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
773 env->key, RSA_PKCS1_PADDING);
774 if (r<0) {
775 crypto_log_errors(LOG_WARN, "generating RSA signature");
776 return -1;
778 return r;
781 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
782 * <b>from</b>; sign the data with the private key in <b>env</b>, and
783 * store it in <b>to</b>. Return the number of bytes written on
784 * success, and -1 on failure.
787 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
788 const char *from, size_t fromlen)
790 char digest[DIGEST_LEN];
791 if (crypto_digest(digest,from,fromlen)<0)
792 return -1;
793 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
796 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
797 * bytes of data from <b>from</b>, with padding type 'padding',
798 * storing the results on <b>to</b>.
800 * If no padding is used, the public key must be at least as large as
801 * <b>from</b>.
803 * Returns the number of bytes written on success, -1 on failure.
805 * The encrypted data consists of:
806 * - The source data, padded and encrypted with the public key, if the
807 * padded source data is no longer than the public key, and <b>force</b>
808 * is false, OR
809 * - The beginning of the source data prefixed with a 16-byte symmetric key,
810 * padded and encrypted with the public key; followed by the rest of
811 * the source data encrypted in AES-CTR mode with the symmetric key.
814 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
815 char *to,
816 const char *from,
817 size_t fromlen,
818 int padding, int force)
820 int overhead, outlen, r, symlen;
821 size_t pkeylen;
822 crypto_cipher_env_t *cipher = NULL;
823 char buf[PK_BYTES+1];
825 tor_assert(env);
826 tor_assert(from);
827 tor_assert(to);
829 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
830 pkeylen = crypto_pk_keysize(env);
832 if (padding == PK_NO_PADDING && fromlen < pkeylen)
833 return -1;
835 if (!force && fromlen+overhead <= pkeylen) {
836 /* It all fits in a single encrypt. */
837 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
839 cipher = crypto_new_cipher_env();
840 if (!cipher) return -1;
841 if (crypto_cipher_generate_key(cipher)<0)
842 goto err;
843 /* You can't just run around RSA-encrypting any bitstream: if it's
844 * greater than the RSA key, then OpenSSL will happily encrypt, and
845 * later decrypt to the wrong value. So we set the first bit of
846 * 'cipher->key' to 0 if we aren't padding. This means that our
847 * symmetric key is really only 127 bits.
849 if (padding == PK_NO_PADDING)
850 cipher->key[0] &= 0x7f;
851 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
852 goto err;
853 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
854 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
856 /* Length of symmetrically encrypted data. */
857 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
859 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
860 if (outlen!=(int)pkeylen) {
861 goto err;
863 r = crypto_cipher_encrypt(cipher, to+outlen,
864 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
866 if (r<0) goto err;
867 memset(buf, 0, sizeof(buf));
868 crypto_free_cipher_env(cipher);
869 return outlen + symlen;
870 err:
871 memset(buf, 0, sizeof(buf));
872 if (cipher) crypto_free_cipher_env(cipher);
873 return -1;
876 /** Invert crypto_pk_public_hybrid_encrypt. */
878 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
879 char *to,
880 const char *from,
881 size_t fromlen,
882 int padding, int warnOnFailure)
884 int outlen, r;
885 size_t pkeylen;
886 crypto_cipher_env_t *cipher = NULL;
887 char buf[PK_BYTES+1];
889 pkeylen = crypto_pk_keysize(env);
891 if (fromlen <= pkeylen) {
892 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
893 warnOnFailure);
895 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
896 warnOnFailure);
897 if (outlen<0) {
898 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
899 "Error decrypting public-key data");
900 return -1;
902 if (outlen < CIPHER_KEY_LEN) {
903 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
904 "No room for a symmetric key");
905 return -1;
907 cipher = crypto_create_init_cipher(buf, 0);
908 if (!cipher) {
909 return -1;
911 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
912 outlen -= CIPHER_KEY_LEN;
913 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
914 if (r<0)
915 goto err;
916 memset(buf,0,sizeof(buf));
917 crypto_free_cipher_env(cipher);
918 return outlen + (fromlen-pkeylen);
919 err:
920 memset(buf,0,sizeof(buf));
921 if (cipher) crypto_free_cipher_env(cipher);
922 return -1;
925 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
926 * Return -1 on error, or the number of characters used on success.
929 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
931 int len;
932 unsigned char *buf, *cp;
933 len = i2d_RSAPublicKey(pk->key, NULL);
934 if (len < 0 || len > dest_len)
935 return -1;
936 cp = buf = tor_malloc(len+1);
937 len = i2d_RSAPublicKey(pk->key, &cp);
938 if (len < 0) {
939 crypto_log_errors(LOG_WARN,"encoding public key");
940 tor_free(buf);
941 return -1;
943 /* We don't encode directly into 'dest', because that would be illegal
944 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
946 memcpy(dest,buf,len);
947 tor_free(buf);
948 return len;
951 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
952 * success and NULL on failure.
954 crypto_pk_env_t *
955 crypto_pk_asn1_decode(const char *str, size_t len)
957 RSA *rsa;
958 unsigned char *buf;
959 /* This ifdef suppresses a type warning. Take out the first case once
960 * everybody is using openssl 0.9.7 or later.
962 #if OPENSSL_VERSION_NUMBER < 0x00907000l
963 unsigned char *cp;
964 #else
965 const unsigned char *cp;
966 #endif
967 cp = buf = tor_malloc(len);
968 memcpy(buf,str,len);
969 rsa = d2i_RSAPublicKey(NULL, &cp, len);
970 tor_free(buf);
971 if (!rsa) {
972 crypto_log_errors(LOG_WARN,"decoding public key");
973 return NULL;
975 return _crypto_new_pk_env_rsa(rsa);
978 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
979 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
980 * Return 0 on success, -1 on failure.
983 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
985 unsigned char *buf, *bufp;
986 int len;
988 len = i2d_RSAPublicKey(pk->key, NULL);
989 if (len < 0)
990 return -1;
991 buf = bufp = tor_malloc(len+1);
992 len = i2d_RSAPublicKey(pk->key, &bufp);
993 if (len < 0) {
994 crypto_log_errors(LOG_WARN,"encoding public key");
995 tor_free(buf);
996 return -1;
998 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
999 tor_free(buf);
1000 return -1;
1002 tor_free(buf);
1003 return 0;
1006 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1007 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1008 * space). Return 0 on success, -1 on failure.
1010 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1011 * of the public key, converted to hexadecimal, in upper case, with a
1012 * space after every four digits.
1014 * If <b>add_space</b> is false, omit the spaces.
1017 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1019 char digest[DIGEST_LEN];
1020 char hexdigest[HEX_DIGEST_LEN+1];
1021 if (crypto_pk_get_digest(pk, digest)) {
1022 return -1;
1024 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1025 if (add_space) {
1026 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
1027 NEVER_TERMINATE)<0)
1028 return -1;
1029 } else {
1030 strcpy(fp_out, hexdigest);
1032 return 0;
1035 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1038 crypto_pk_check_fingerprint_syntax(const char *s)
1040 int i;
1041 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1042 if ((i%5) == 4) {
1043 if (!TOR_ISSPACE(s[i])) return 0;
1044 } else {
1045 if (!TOR_ISXDIGIT(s[i])) return 0;
1048 if (s[FINGERPRINT_LEN]) return 0;
1049 return 1;
1052 /* symmetric crypto */
1054 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1055 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1058 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1060 tor_assert(env);
1062 return crypto_rand(env->key, CIPHER_KEY_LEN);
1065 /** Set the symmetric key for the cipher in <b>env</b> to the first
1066 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1067 * Return 0 on success, -1 on failure.
1070 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1072 tor_assert(env);
1073 tor_assert(key);
1075 if (!env->key)
1076 return -1;
1078 memcpy(env->key, key, CIPHER_KEY_LEN);
1080 return 0;
1083 /** Return a pointer to the key set for the cipher in <b>env</b>.
1085 const char *
1086 crypto_cipher_get_key(crypto_cipher_env_t *env)
1088 return env->key;
1091 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1092 * success, -1 on failure.
1095 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1097 tor_assert(env);
1099 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1100 return 0;
1103 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1104 * success, -1 on failure.
1107 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1109 tor_assert(env);
1111 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1112 return 0;
1115 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1116 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1117 * On failure, return -1.
1120 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1121 const char *from, size_t fromlen)
1123 tor_assert(env);
1124 tor_assert(env->cipher);
1125 tor_assert(from);
1126 tor_assert(fromlen);
1127 tor_assert(to);
1129 aes_crypt(env->cipher, from, fromlen, to);
1130 return 0;
1133 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1134 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1135 * On failure, return -1.
1138 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1139 const char *from, size_t fromlen)
1141 tor_assert(env);
1142 tor_assert(from);
1143 tor_assert(to);
1145 aes_crypt(env->cipher, from, fromlen, to);
1146 return 0;
1149 /* SHA-1 */
1151 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1152 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1153 * Return 0 on success, -1 on failure.
1156 crypto_digest(char *digest, const char *m, size_t len)
1158 tor_assert(m);
1159 tor_assert(digest);
1160 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1163 /** Intermediate information about the digest of a stream of data. */
1164 struct crypto_digest_env_t {
1165 SHA_CTX d;
1168 /** Allocate and return a new digest object.
1170 crypto_digest_env_t *
1171 crypto_new_digest_env(void)
1173 crypto_digest_env_t *r;
1174 r = tor_malloc(sizeof(crypto_digest_env_t));
1175 SHA1_Init(&r->d);
1176 return r;
1179 /** Deallocate a digest object.
1181 void
1182 crypto_free_digest_env(crypto_digest_env_t *digest)
1184 tor_free(digest);
1187 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1189 void
1190 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1191 size_t len)
1193 tor_assert(digest);
1194 tor_assert(data);
1195 /* Using the SHA1_*() calls directly means we don't support doing
1196 * sha1 in hardware. But so far the delay of getting the question
1197 * to the hardware, and hearing the answer, is likely higher than
1198 * just doing it ourselves. Hashes are fast.
1200 SHA1_Update(&digest->d, (void*)data, len);
1203 /** Compute the hash of the data that has been passed to the digest
1204 * object; write the first out_len bytes of the result to <b>out</b>.
1205 * <b>out_len</b> must be \<= DIGEST_LEN.
1207 void
1208 crypto_digest_get_digest(crypto_digest_env_t *digest,
1209 char *out, size_t out_len)
1211 static unsigned char r[DIGEST_LEN];
1212 SHA_CTX tmpctx;
1213 tor_assert(digest);
1214 tor_assert(out);
1215 tor_assert(out_len <= DIGEST_LEN);
1216 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1217 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1218 SHA1_Final(r, &tmpctx);
1219 memcpy(out, r, out_len);
1222 /** Allocate and return a new digest object with the same state as
1223 * <b>digest</b>
1225 crypto_digest_env_t *
1226 crypto_digest_dup(const crypto_digest_env_t *digest)
1228 crypto_digest_env_t *r;
1229 tor_assert(digest);
1230 r = tor_malloc(sizeof(crypto_digest_env_t));
1231 memcpy(r,digest,sizeof(crypto_digest_env_t));
1232 return r;
1235 /** Replace the state of the digest object <b>into</b> with the state
1236 * of the digest object <b>from</b>.
1238 void
1239 crypto_digest_assign(crypto_digest_env_t *into,
1240 const crypto_digest_env_t *from)
1242 tor_assert(into);
1243 tor_assert(from);
1244 memcpy(into,from,sizeof(crypto_digest_env_t));
1247 /* DH */
1249 /** Shared P parameter for our DH key exchanged. */
1250 static BIGNUM *dh_param_p = NULL;
1251 /** Shared G parameter for our DH key exchanges. */
1252 static BIGNUM *dh_param_g = NULL;
1254 /** Initialize dh_param_p and dh_param_g if they are not already
1255 * set. */
1256 static void
1257 init_dh_param(void)
1259 BIGNUM *p, *g;
1260 int r;
1261 if (dh_param_p && dh_param_g)
1262 return;
1264 p = BN_new();
1265 g = BN_new();
1266 tor_assert(p);
1267 tor_assert(g);
1269 /* This is from rfc2409, section 6.2. It's a safe prime, and
1270 supposedly it equals:
1271 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1273 r = BN_hex2bn(&p,
1274 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1275 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1276 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1277 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1278 "49286651ECE65381FFFFFFFFFFFFFFFF");
1279 tor_assert(r);
1281 r = BN_set_word(g, 2);
1282 tor_assert(r);
1283 dh_param_p = p;
1284 dh_param_g = g;
1287 #define DH_PRIVATE_KEY_BITS 320
1289 /** Allocate and return a new DH object for a key exchange.
1291 crypto_dh_env_t *
1292 crypto_dh_new(void)
1294 crypto_dh_env_t *res = NULL;
1296 if (!dh_param_p)
1297 init_dh_param();
1299 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1301 if (!(res->dh = DH_new()))
1302 goto err;
1304 if (!(res->dh->p = BN_dup(dh_param_p)))
1305 goto err;
1307 if (!(res->dh->g = BN_dup(dh_param_g)))
1308 goto err;
1310 res->dh->length = DH_PRIVATE_KEY_BITS;
1312 return res;
1313 err:
1314 crypto_log_errors(LOG_WARN, "creating DH object");
1315 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1316 if (res) tor_free(res);
1317 return NULL;
1320 /** Return the length of the DH key in <b>dh</b>, in bytes.
1323 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1325 tor_assert(dh);
1326 return DH_size(dh->dh);
1329 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1330 * success, -1 on failure.
1333 crypto_dh_generate_public(crypto_dh_env_t *dh)
1335 again:
1336 if (!DH_generate_key(dh->dh)) {
1337 crypto_log_errors(LOG_WARN, "generating DH key");
1338 return -1;
1340 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1341 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1342 "the-universe chances really do happen. Trying again.");
1343 /* Free and clear the keys, so openssl will actually try again. */
1344 BN_free(dh->dh->pub_key);
1345 BN_free(dh->dh->priv_key);
1346 dh->dh->pub_key = dh->dh->priv_key = NULL;
1347 goto again;
1349 return 0;
1352 /** Generate g^x as necessary, and write the g^x for the key exchange
1353 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1354 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1357 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1359 int bytes;
1360 tor_assert(dh);
1361 if (!dh->dh->pub_key) {
1362 if (crypto_dh_generate_public(dh)<0)
1363 return -1;
1366 tor_assert(dh->dh->pub_key);
1367 bytes = BN_num_bytes(dh->dh->pub_key);
1368 tor_assert(bytes >= 0);
1369 if (pubkey_len < (size_t)bytes) {
1370 log_warn(LD_CRYPTO,
1371 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1372 (int) pubkey_len, bytes);
1373 return -1;
1376 memset(pubkey, 0, pubkey_len);
1377 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1379 return 0;
1382 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1383 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1384 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1386 static int
1387 tor_check_dh_key(BIGNUM *bn)
1389 BIGNUM *x;
1390 char *s;
1391 tor_assert(bn);
1392 x = BN_new();
1393 tor_assert(x);
1394 if (!dh_param_p)
1395 init_dh_param();
1396 BN_set_word(x, 1);
1397 if (BN_cmp(bn,x)<=0) {
1398 log_warn(LD_CRYPTO, "DH key must be at least 2.");
1399 goto err;
1401 BN_copy(x,dh_param_p);
1402 BN_sub_word(x, 1);
1403 if (BN_cmp(bn,x)>=0) {
1404 log_warn(LD_CRYPTO, "DH key must be at most p-2.");
1405 goto err;
1407 BN_free(x);
1408 return 0;
1409 err:
1410 BN_free(x);
1411 s = BN_bn2hex(bn);
1412 log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1413 OPENSSL_free(s);
1414 return -1;
1417 #undef MIN
1418 #define MIN(a,b) ((a)<(b)?(a):(b))
1419 /** Given a DH key exchange object, and our peer's value of g^y (as a
1420 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1421 * <b>secret_bytes_out</b> bytes of shared key material and write them
1422 * to <b>secret_out</b>. Return the number of bytes generated on success,
1423 * or -1 on failure.
1425 * (We generate key material by computing
1426 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1427 * where || is concatenation.)
1430 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1431 const char *pubkey, size_t pubkey_len,
1432 char *secret_out, size_t secret_bytes_out)
1434 char *secret_tmp = NULL;
1435 BIGNUM *pubkey_bn = NULL;
1436 size_t secret_len=0;
1437 int result=0;
1438 tor_assert(dh);
1439 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1441 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
1442 goto error;
1443 if (tor_check_dh_key(pubkey_bn)<0) {
1444 /* Check for invalid public keys. */
1445 log_warn(LD_CRYPTO,"Rejected invalid g^x");
1446 goto error;
1448 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1449 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1450 if (result < 0) {
1451 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1452 goto error;
1454 secret_len = result;
1455 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1456 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1457 * Leading zeros MUST be preserved, so that ZZ occupies as many
1458 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1459 * bytes long.
1460 * What are the security implications here?
1462 if (crypto_expand_key_material(secret_tmp, secret_len,
1463 secret_out, secret_bytes_out)<0)
1464 goto error;
1465 secret_len = secret_bytes_out;
1467 goto done;
1468 error:
1469 result = -1;
1470 done:
1471 crypto_log_errors(LOG_WARN, "completing DH handshake");
1472 if (pubkey_bn)
1473 BN_free(pubkey_bn);
1474 tor_free(secret_tmp);
1475 if (result < 0)
1476 return result;
1477 else
1478 return secret_len;
1481 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1482 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1483 * <b>key_out</b> by taking the first key_out_len bytes of
1484 * H(K | [00]) | H(K | [01]) | ....
1486 * Return 0 on success, -1 on failure.
1489 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1490 char *key_out, size_t key_out_len)
1492 int i;
1493 char *cp, *tmp = tor_malloc(key_in_len+1);
1494 char digest[DIGEST_LEN];
1496 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1497 tor_assert(key_out_len <= DIGEST_LEN*256);
1499 memcpy(tmp, key_in, key_in_len);
1500 for (cp = key_out, i=0; key_out_len; ++i, cp += DIGEST_LEN) {
1501 tmp[key_in_len] = i;
1502 if (crypto_digest(digest, tmp, key_in_len+1))
1503 goto err;
1504 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len));
1505 if (key_out_len < DIGEST_LEN)
1506 break;
1507 key_out_len -= DIGEST_LEN;
1509 memset(tmp, 0, key_in_len+1);
1510 tor_free(tmp);
1511 return 0;
1513 err:
1514 memset(tmp, 0, key_in_len+1);
1515 tor_free(tmp);
1516 return -1;
1519 /** Free a DH key exchange object.
1521 void
1522 crypto_dh_free(crypto_dh_env_t *dh)
1524 tor_assert(dh);
1525 tor_assert(dh->dh);
1526 DH_free(dh->dh);
1527 tor_free(dh);
1530 /* random numbers */
1532 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1533 * work for us too. */
1534 #define ADD_ENTROPY 32
1536 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1537 "release".) */
1538 //#define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1539 #define USE_RAND_POLL 0
1540 /* XXX Somehow setting USE_RAND_POLL on causes stack smashes. We're
1541 * not sure where. This was the big bug with Tor 0.1.1.9-alpha. */
1543 /** Seed OpenSSL's random number generator with bytes from the
1544 * operating system. Return 0 on success, -1 on failure.
1547 crypto_seed_rng(void)
1549 char buf[ADD_ENTROPY];
1550 int rand_poll_status;
1552 /* local variables */
1553 #ifdef MS_WINDOWS
1554 static int provider_set = 0;
1555 static HCRYPTPROV provider;
1556 #else
1557 static const char *filenames[] = {
1558 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1560 int fd;
1561 int i, n;
1562 #endif
1564 #if USE_RAND_POLL
1565 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1566 * entropy than we do. We'll try calling that, *and* calling our own entropy
1567 * functions. If one succeeds, we'll accept the RNG as seeded. */
1568 rand_poll_status = RAND_poll();
1569 if (rand_poll_status == 0)
1570 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1571 #else
1572 rand_poll_status = 0;
1573 #endif
1575 #ifdef MS_WINDOWS
1576 if (!provider_set) {
1577 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1578 CRYPT_VERIFYCONTEXT)) {
1579 if (GetLastError() != NTE_BAD_KEYSET) {
1580 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1581 return rand_poll_status ? 0 : -1;
1584 provider_set = 1;
1586 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1587 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1588 return rand_poll_status ? 0 : -1;
1590 RAND_seed(buf, sizeof(buf));
1591 return 0;
1592 #else
1593 for (i = 0; filenames[i]; ++i) {
1594 fd = open(filenames[i], O_RDONLY, 0);
1595 if (fd<0) continue;
1596 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1597 n = read_all(fd, buf, sizeof(buf), 0);
1598 close(fd);
1599 if (n != sizeof(buf)) {
1600 log_warn(LD_CRYPTO,
1601 "Error reading from entropy source (read only %d bytes).", n);
1602 return -1;
1604 RAND_seed(buf, sizeof(buf));
1605 return 0;
1608 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1609 return rand_poll_status ? 0 : -1;
1610 #endif
1613 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1614 * success, -1 on failure.
1617 crypto_rand(char *to, size_t n)
1619 int r;
1620 tor_assert(to);
1621 r = RAND_bytes((unsigned char*)to, n);
1622 if (r == 0)
1623 crypto_log_errors(LOG_WARN, "generating random data");
1624 return (r == 1) ? 0 : -1;
1627 /** Return a pseudorandom integer, chosen uniformly from the values
1628 * between 0 and max-1. */
1630 crypto_rand_int(unsigned int max)
1632 unsigned int val;
1633 unsigned int cutoff;
1634 tor_assert(max < UINT_MAX);
1635 tor_assert(max > 0); /* don't div by 0 */
1637 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1638 * distribution with clipping at the upper end of unsigned int's
1639 * range.
1641 cutoff = UINT_MAX - (UINT_MAX%max);
1642 while (1) {
1643 crypto_rand((char*)&val, sizeof(val));
1644 if (val < cutoff)
1645 return val % max;
1649 /** Return a pseudorandom integer, chosen uniformly from the values
1650 * between 0 and max-1. */
1651 uint64_t
1652 crypto_rand_uint64(uint64_t max)
1654 uint64_t val;
1655 uint64_t cutoff;
1656 tor_assert(max < UINT64_MAX);
1657 tor_assert(max > 0); /* don't div by 0 */
1659 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1660 * distribution with clipping at the upper end of unsigned int's
1661 * range.
1663 cutoff = UINT64_MAX - (UINT64_MAX%max);
1664 while (1) {
1665 crypto_rand((char*)&val, sizeof(val));
1666 if (val < cutoff)
1667 return val % max;
1671 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1673 void *
1674 smartlist_choose(const smartlist_t *sl)
1676 size_t len;
1677 len = smartlist_len(sl);
1678 if (len)
1679 return smartlist_get(sl,crypto_rand_int(len));
1680 return NULL; /* no elements to choose from */
1683 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1684 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1685 * bytes. Return the number of bytes written on success; -1 if
1686 * destlen is too short, or other failure.
1689 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1691 EVP_ENCODE_CTX ctx;
1692 int len, ret;
1694 /* 48 bytes of input -> 64 bytes of output plus newline.
1695 Plus one more byte, in case I'm wrong.
1697 if (destlen < ((srclen/48)+1)*66)
1698 return -1;
1699 if (destlen > SIZE_T_CEILING)
1700 return -1;
1702 EVP_EncodeInit(&ctx);
1703 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
1704 (unsigned char*)src, srclen);
1705 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1706 ret += len;
1707 return ret;
1710 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1711 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1712 * bytes. Return the number of bytes written on success; -1 if
1713 * destlen is too short, or other failure.
1715 * NOTE: destlen should be a little longer than the amount of data it
1716 * will contain, since we check for sufficient space conservatively.
1717 * Here, "a little" is around 64-ish bytes.
1720 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1722 EVP_ENCODE_CTX ctx;
1723 int len, ret;
1724 /* 64 bytes of input -> *up to* 48 bytes of output.
1725 Plus one more byte, in case I'm wrong.
1727 if (destlen < ((srclen/64)+1)*49)
1728 return -1;
1729 if (destlen > SIZE_T_CEILING)
1730 return -1;
1732 EVP_DecodeInit(&ctx);
1733 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
1734 (unsigned char*)src, srclen);
1735 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
1736 ret += len;
1737 return ret;
1740 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
1741 * and newline characters, and store the nul-terminated result in the first
1742 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
1744 digest_to_base64(char *d64, const char *digest)
1746 char buf[256];
1747 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
1748 buf[BASE64_DIGEST_LEN] = '\0';
1749 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
1750 return 0;
1753 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
1754 * trailing newline or = characters), decode it and store the result in the
1755 * first DIGEST_LEN bytes at <b>digest</b>. */
1757 digest_from_base64(char *digest, const char *d64)
1759 char buf_in[BASE64_DIGEST_LEN+3];
1760 char buf[256];
1761 if (strlen(d64) != BASE64_DIGEST_LEN)
1762 return -1;
1763 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
1764 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
1765 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
1766 return -1;
1767 memcpy(digest, buf, DIGEST_LEN);
1768 return 0;
1771 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1772 * that srclen*8 is a multiple of 5.
1774 void
1775 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1777 unsigned int nbits, i, bit, v, u;
1778 nbits = srclen * 8;
1780 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1781 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1782 tor_assert(destlen < SIZE_T_CEILING);
1784 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1785 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1786 v = ((uint8_t)src[bit/8]) << 8;
1787 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1788 /* set u to the 5-bit value at the bit'th bit of src. */
1789 u = (v >> (11-(bit%8))) & 0x1F;
1790 dest[i] = BASE32_CHARS[u];
1792 dest[i] = '\0';
1795 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1796 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1797 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1798 * are a salt; the 9th byte describes how much iteration to do.
1799 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1801 void
1802 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1803 size_t secret_len, const char *s2k_specifier)
1805 crypto_digest_env_t *d;
1806 uint8_t c;
1807 size_t count;
1808 char *tmp;
1809 tor_assert(key_out_len < SIZE_T_CEILING);
1811 #define EXPBIAS 6
1812 c = s2k_specifier[8];
1813 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1814 #undef EXPBIAS
1816 tor_assert(key_out_len <= DIGEST_LEN);
1818 d = crypto_new_digest_env();
1819 tmp = tor_malloc(8+secret_len);
1820 memcpy(tmp,s2k_specifier,8);
1821 memcpy(tmp+8,secret,secret_len);
1822 secret_len += 8;
1823 while (count) {
1824 if (count >= secret_len) {
1825 crypto_digest_add_bytes(d, tmp, secret_len);
1826 count -= secret_len;
1827 } else {
1828 crypto_digest_add_bytes(d, tmp, count);
1829 count = 0;
1832 crypto_digest_get_digest(d, key_out, key_out_len);
1833 tor_free(tmp);
1834 crypto_free_digest_env(d);
1837 #ifdef TOR_IS_MULTITHREADED
1838 /** Helper: openssl uses this callback to manipulate mutexes. */
1839 static void
1840 _openssl_locking_cb(int mode, int n, const char *file, int line)
1842 (void)file;
1843 (void)line;
1844 if (!_openssl_mutexes)
1845 /* This is not a really good fix for the
1846 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1847 * it can't hurt. */
1848 return;
1849 if (mode & CRYPTO_LOCK)
1850 tor_mutex_acquire(_openssl_mutexes[n]);
1851 else
1852 tor_mutex_release(_openssl_mutexes[n]);
1855 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
1856 * multithreaded. */
1857 static int
1858 setup_openssl_threading(void)
1860 int i;
1861 int n = CRYPTO_num_locks();
1862 _n_openssl_mutexes = n;
1863 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
1864 for (i=0; i < n; ++i)
1865 _openssl_mutexes[i] = tor_mutex_new();
1866 CRYPTO_set_locking_callback(_openssl_locking_cb);
1867 CRYPTO_set_id_callback(tor_get_thread_id);
1868 return 0;
1870 #else
1871 static int
1872 setup_openssl_threading(void)
1874 return 0;
1876 #endif