Use RSA_generate_key_ex where available.
[tor/rransom.git] / src / common / crypto.c
blob2c892fbc1ea8661d2cd5e428e9a301d3cb9a6cac
1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char crypto_c_id[] =
8 "$Id$";
10 /**
11 * \file crypto.c
12 * \brief Wrapper functions to present a consistent interface to
13 * public-key and symmetric cryptography operations from OpenSSL.
14 **/
16 #include "orconfig.h"
18 #ifdef MS_WINDOWS
19 #define WIN32_WINNT 0x400
20 #define _WIN32_WINNT 0x400
21 #define WIN32_LEAN_AND_MEAN
22 #include <windows.h>
23 #include <wincrypt.h>
24 /* Windows defines this; so does openssl 0.9.8h and later. We don't actually
25 * use either definition. */
26 #undef OCSP_RESPONSE
27 #endif
29 #include <openssl/err.h>
30 #include <openssl/rsa.h>
31 #include <openssl/pem.h>
32 #include <openssl/evp.h>
33 #include <openssl/rand.h>
34 #include <openssl/opensslv.h>
35 #include <openssl/bn.h>
36 #include <openssl/dh.h>
37 #include <openssl/conf.h>
38 #include <openssl/hmac.h>
40 #ifdef HAVE_CTYPE_H
41 #include <ctype.h>
42 #endif
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #endif
49 #ifdef HAVE_SYS_FCNTL_H
50 #include <sys/fcntl.h>
51 #endif
53 #define CRYPTO_PRIVATE
54 #include "crypto.h"
55 #include "log.h"
56 #include "aes.h"
57 #include "util.h"
58 #include "container.h"
59 #include "compat.h"
61 #if OPENSSL_VERSION_NUMBER < 0x00907000l
62 #error "We require openssl >= 0.9.7"
63 #endif
65 #include <openssl/engine.h>
67 /** Macro: is k a valid RSA public or private key? */
68 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
69 /** Macro: is k a valid RSA private key? */
70 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
72 #ifdef TOR_IS_MULTITHREADED
73 /** A number of prealloced mutexes for use by openssl. */
74 static tor_mutex_t **_openssl_mutexes = NULL;
75 /** How many mutexes have we allocated for use by openssl? */
76 static int _n_openssl_mutexes = 0;
77 #endif
79 /** A public key, or a public/private keypair. */
80 struct crypto_pk_env_t
82 int refs; /* reference counting so we don't have to copy keys */
83 RSA *key;
86 /** Key and stream information for a stream cipher. */
87 struct crypto_cipher_env_t
89 char key[CIPHER_KEY_LEN];
90 aes_cnt_cipher_t *cipher;
93 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
94 * while we're waiting for the second.*/
95 struct crypto_dh_env_t {
96 DH *dh;
99 static int setup_openssl_threading(void);
100 static int tor_check_dh_key(BIGNUM *bn);
102 /** Return the number of bytes added by padding method <b>padding</b>.
104 static INLINE int
105 crypto_get_rsa_padding_overhead(int padding)
107 switch (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.
118 static INLINE int
119 crypto_get_rsa_padding(int padding)
121 switch (padding)
123 case PK_NO_PADDING: return RSA_NO_PADDING;
124 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
125 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
126 default: tor_assert(0); return -1;
130 /** Boolean: has OpenSSL's crypto been initialized? */
131 static int _crypto_global_initialized = 0;
133 /** Log all pending crypto errors at level <b>severity</b>. Use
134 * <b>doing</b> to describe our current activities.
136 static void
137 crypto_log_errors(int severity, const char *doing)
139 unsigned long err;
140 const char *msg, *lib, *func;
141 while ((err = ERR_get_error()) != 0) {
142 msg = (const char*)ERR_reason_error_string(err);
143 lib = (const char*)ERR_lib_error_string(err);
144 func = (const char*)ERR_func_error_string(err);
145 if (!msg) msg = "(null)";
146 if (!lib) lib = "(null)";
147 if (!func) func = "(null)";
148 if (doing) {
149 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
150 doing, msg, lib, func);
151 } else {
152 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
157 /** Log any OpenSSL engines we're using at NOTICE. */
158 static void
159 log_engine(const char *fn, ENGINE *e)
161 if (e) {
162 const char *name, *id;
163 name = ENGINE_get_name(e);
164 id = ENGINE_get_id(e);
165 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
166 name?name:"?", id?id:"?", fn);
167 } else {
168 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
172 /** Initialize the crypto library. Return 0 on success, -1 on failure.
175 crypto_global_init(int useAccel)
177 if (!_crypto_global_initialized) {
178 ERR_load_crypto_strings();
179 OpenSSL_add_all_algorithms();
180 _crypto_global_initialized = 1;
181 setup_openssl_threading();
182 /* XXX the below is a bug, since we can't know if we're supposed
183 * to be using hardware acceleration or not. we should arrange
184 * for this function to be called before init_keys. But make it
185 * not complain loudly, at least until we make acceleration work. */
186 if (useAccel < 0) {
187 log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
189 if (useAccel > 0) {
190 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
191 ENGINE_load_builtin_engines();
192 if (!ENGINE_register_all_complete())
193 return -1;
195 /* XXXX make sure this isn't leaking. */
196 log_engine("RSA", ENGINE_get_default_RSA());
197 log_engine("DH", ENGINE_get_default_DH());
198 log_engine("RAND", ENGINE_get_default_RAND());
199 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
200 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
201 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
204 return 0;
207 /** Free crypto resources held by this thread. */
208 void
209 crypto_thread_cleanup(void)
211 ERR_remove_state(0);
214 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
217 crypto_global_cleanup(void)
219 EVP_cleanup();
220 ERR_remove_state(0);
221 ERR_free_strings();
222 ENGINE_cleanup();
223 CONF_modules_unload(1);
224 CRYPTO_cleanup_all_ex_data();
225 #ifdef TOR_IS_MULTITHREADED
226 if (_n_openssl_mutexes) {
227 int n = _n_openssl_mutexes;
228 tor_mutex_t **ms = _openssl_mutexes;
229 int i;
230 _openssl_mutexes = NULL;
231 _n_openssl_mutexes = 0;
232 for (i=0;i<n;++i) {
233 tor_mutex_free(ms[i]);
235 tor_free(ms);
237 #endif
238 return 0;
241 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
242 crypto_pk_env_t *
243 _crypto_new_pk_env_rsa(RSA *rsa)
245 crypto_pk_env_t *env;
246 tor_assert(rsa);
247 env = tor_malloc(sizeof(crypto_pk_env_t));
248 env->refs = 1;
249 env->key = rsa;
250 return env;
253 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
254 * returns NULL if this isn't an RSA key. */
255 crypto_pk_env_t *
256 _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
258 RSA *rsa;
259 if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
260 return NULL;
261 return _crypto_new_pk_env_rsa(rsa);
264 /** Helper, used by tor-checkkey.c. Return the RSA from a crypto_pk_env_t. */
265 RSA *
266 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
268 return env->key;
271 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
272 * private is set, include the private-key portion of the key. */
273 EVP_PKEY *
274 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
276 RSA *key = NULL;
277 EVP_PKEY *pkey = NULL;
278 tor_assert(env->key);
279 if (private) {
280 if (!(key = RSAPrivateKey_dup(env->key)))
281 goto error;
282 } else {
283 if (!(key = RSAPublicKey_dup(env->key)))
284 goto error;
286 if (!(pkey = EVP_PKEY_new()))
287 goto error;
288 if (!(EVP_PKEY_assign_RSA(pkey, key)))
289 goto error;
290 return pkey;
291 error:
292 if (pkey)
293 EVP_PKEY_free(pkey);
294 if (key)
295 RSA_free(key);
296 return NULL;
299 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
301 DH *
302 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
304 return dh->dh;
307 /** Allocate and return storage for a public key. The key itself will not yet
308 * be set.
310 crypto_pk_env_t *
311 crypto_new_pk_env(void)
313 RSA *rsa;
315 rsa = RSA_new();
316 if (!rsa) return NULL;
317 return _crypto_new_pk_env_rsa(rsa);
320 /** Release a reference to an asymmetric key; when all the references
321 * are released, free the key.
323 void
324 crypto_free_pk_env(crypto_pk_env_t *env)
326 tor_assert(env);
328 if (--env->refs > 0)
329 return;
331 if (env->key)
332 RSA_free(env->key);
334 tor_free(env);
337 /** Create a new symmetric cipher for a given key and encryption flag
338 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
339 * on failure.
341 crypto_cipher_env_t *
342 crypto_create_init_cipher(const char *key, int encrypt_mode)
344 int r;
345 crypto_cipher_env_t *crypto = NULL;
347 if (! (crypto = crypto_new_cipher_env())) {
348 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
349 return NULL;
352 if (crypto_cipher_set_key(crypto, key)) {
353 crypto_log_errors(LOG_WARN, "setting symmetric key");
354 goto error;
357 if (encrypt_mode)
358 r = crypto_cipher_encrypt_init_cipher(crypto);
359 else
360 r = crypto_cipher_decrypt_init_cipher(crypto);
362 if (r)
363 goto error;
364 return crypto;
366 error:
367 if (crypto)
368 crypto_free_cipher_env(crypto);
369 return NULL;
372 /** Allocate and return a new symmetric cipher.
374 crypto_cipher_env_t *
375 crypto_new_cipher_env(void)
377 crypto_cipher_env_t *env;
379 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
380 env->cipher = aes_new_cipher();
381 return env;
384 /** Free a symmetric cipher.
386 void
387 crypto_free_cipher_env(crypto_cipher_env_t *env)
389 tor_assert(env);
391 tor_assert(env->cipher);
392 aes_free_cipher(env->cipher);
393 memset(env, 0, sizeof(crypto_cipher_env_t));
394 tor_free(env);
397 /* public key crypto */
399 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
400 * success, -1 on failure.
403 crypto_pk_generate_key(crypto_pk_env_t *env)
405 tor_assert(env);
407 if (env->key)
408 RSA_free(env->key);
409 #if OPENSSL_VERSION_NUMBER < 0x00908000l
410 /* In openssl 0.9.7, RSA_generate_key is all we have. */
411 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
412 #else
413 /* In openssl 0.9.8, RSA_generate_key is deprecated. */
415 BIGNUM *e = BN_new();
416 RSA *r = NULL;
417 if (!e)
418 goto done;
419 if (! BN_set_word(e, 65537))
420 goto done;
421 r = RSA_new();
422 if (!r)
423 goto done;
424 if (RSA_generate_key_ex(r, PK_BYTES*8, e, NULL) == -1)
425 goto done;
427 env->key = r;
428 r = NULL;
429 done:
430 if (e)
431 BN_free(e);
432 if (r)
433 RSA_free(r);
435 #endif
436 if (!env->key) {
437 crypto_log_errors(LOG_WARN, "generating RSA key");
438 return -1;
441 return 0;
444 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
445 * Return 0 on success, -1 on failure.
447 /* Used here, and used for testing. */
449 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
450 const char *s)
452 BIO *b;
454 tor_assert(env);
455 tor_assert(s);
457 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
458 b = BIO_new_mem_buf((char*)s, -1);
460 if (env->key)
461 RSA_free(env->key);
463 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
465 BIO_free(b);
467 if (!env->key) {
468 crypto_log_errors(LOG_WARN, "Error parsing private key");
469 return -1;
471 return 0;
474 /** Read a PEM-encoded private key from the file named by
475 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
478 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
479 const char *keyfile)
481 char *contents;
482 int r;
484 /* Read the file into a string. */
485 contents = read_file_to_str(keyfile, 0, NULL);
486 if (!contents) {
487 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
488 return -1;
491 /* Try to parse it. */
492 r = crypto_pk_read_private_key_from_string(env, contents);
493 tor_free(contents);
494 if (r)
495 return -1; /* read_private_key_from_string already warned, so we don't.*/
497 /* Make sure it's valid. */
498 if (crypto_pk_check_key(env) <= 0)
499 return -1;
501 return 0;
504 /** Helper function to implement crypto_pk_write_*_key_to_string. */
505 static int
506 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
507 size_t *len, int is_public)
509 BUF_MEM *buf;
510 BIO *b;
511 int r;
513 tor_assert(env);
514 tor_assert(env->key);
515 tor_assert(dest);
517 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
519 /* Now you can treat b as if it were a file. Just use the
520 * PEM_*_bio_* functions instead of the non-bio variants.
522 if (is_public)
523 r = PEM_write_bio_RSAPublicKey(b, env->key);
524 else
525 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
527 if (!r) {
528 crypto_log_errors(LOG_WARN, "writing RSA key to string");
529 BIO_free(b);
530 return -1;
533 BIO_get_mem_ptr(b, &buf);
534 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
535 BIO_free(b);
537 tor_assert(buf->length >= 0);
538 *dest = tor_malloc(buf->length+1);
539 memcpy(*dest, buf->data, buf->length);
540 (*dest)[buf->length] = 0; /* nul terminate it */
541 *len = buf->length;
542 BUF_MEM_free(buf);
544 return 0;
547 /** PEM-encode the public key portion of <b>env</b> and write it to a
548 * newly allocated string. On success, set *<b>dest</b> to the new
549 * string, *<b>len</b> to the string's length, and return 0. On
550 * failure, return -1.
553 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
554 size_t *len)
556 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
559 /** PEM-encode the private key portion of <b>env</b> and write it to a
560 * newly allocated string. On success, set *<b>dest</b> to the new
561 * string, *<b>len</b> to the string's length, and return 0. On
562 * failure, return -1.
565 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
566 size_t *len)
568 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
571 /** Read a PEM-encoded public key from the first <b>len</b> characters of
572 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
573 * failure.
576 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
577 size_t len)
579 BIO *b;
581 tor_assert(env);
582 tor_assert(src);
583 tor_assert(len<INT_MAX);
585 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
587 BIO_write(b, src, (int)len);
589 if (env->key)
590 RSA_free(env->key);
591 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
592 BIO_free(b);
593 if (!env->key) {
594 crypto_log_errors(LOG_WARN, "reading public key from string");
595 return -1;
598 return 0;
601 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
602 * PEM-encoded. Return 0 on success, -1 on failure.
605 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
606 const char *fname)
608 BIO *bio;
609 char *cp;
610 long len;
611 char *s;
612 int r;
614 tor_assert(PRIVATE_KEY_OK(env));
616 if (!(bio = BIO_new(BIO_s_mem())))
617 return -1;
618 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
619 == 0) {
620 crypto_log_errors(LOG_WARN, "writing private key");
621 BIO_free(bio);
622 return -1;
624 len = BIO_get_mem_data(bio, &cp);
625 tor_assert(len >= 0);
626 s = tor_malloc(len+1);
627 memcpy(s, cp, len);
628 s[len]='\0';
629 r = write_str_to_file(fname, s, 0);
630 BIO_free(bio);
631 tor_free(s);
632 return r;
635 /** Return true iff <b>env</b> has a valid key.
638 crypto_pk_check_key(crypto_pk_env_t *env)
640 int r;
641 tor_assert(env);
643 r = RSA_check_key(env->key);
644 if (r <= 0)
645 crypto_log_errors(LOG_WARN,"checking RSA key");
646 return r;
649 /** Return true iff <b>key</b> contains the private-key portion of the RSA
650 * key. */
652 crypto_pk_key_is_private(const crypto_pk_env_t *key)
654 tor_assert(key);
655 return PRIVATE_KEY_OK(key);
658 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
659 * if a==b, and 1 if a\>b.
662 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
664 int result;
666 if (!a || !b)
667 return -1;
669 if (!a->key || !b->key)
670 return -1;
672 tor_assert(PUBLIC_KEY_OK(a));
673 tor_assert(PUBLIC_KEY_OK(b));
674 result = BN_cmp((a->key)->n, (b->key)->n);
675 if (result)
676 return result;
677 return BN_cmp((a->key)->e, (b->key)->e);
680 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
681 size_t
682 crypto_pk_keysize(crypto_pk_env_t *env)
684 tor_assert(env);
685 tor_assert(env->key);
687 return (size_t) RSA_size(env->key);
690 /** Increase the reference count of <b>env</b>, and return it.
692 crypto_pk_env_t *
693 crypto_pk_dup_key(crypto_pk_env_t *env)
695 tor_assert(env);
696 tor_assert(env->key);
698 env->refs++;
699 return env;
702 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
703 crypto_pk_env_t *
704 crypto_pk_copy_full(crypto_pk_env_t *env)
706 RSA *new_key;
707 tor_assert(env);
708 tor_assert(env->key);
710 if (PRIVATE_KEY_OK(env)) {
711 new_key = RSAPrivateKey_dup(env->key);
712 } else {
713 new_key = RSAPublicKey_dup(env->key);
716 return _crypto_new_pk_env_rsa(new_key);
719 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
720 * in <b>env</b>, using the padding method <b>padding</b>. On success,
721 * write the result to <b>to</b>, and return the number of bytes
722 * written. On failure, return -1.
725 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
726 const char *from, size_t fromlen, int padding)
728 int r;
729 tor_assert(env);
730 tor_assert(from);
731 tor_assert(to);
732 tor_assert(fromlen<INT_MAX);
734 r = RSA_public_encrypt((int)fromlen,
735 (unsigned char*)from, (unsigned char*)to,
736 env->key, crypto_get_rsa_padding(padding));
737 if (r<0) {
738 crypto_log_errors(LOG_WARN, "performing RSA encryption");
739 return -1;
741 return r;
744 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
745 * in <b>env</b>, using the padding method <b>padding</b>. On success,
746 * write the result to <b>to</b>, and return the number of bytes
747 * written. On failure, return -1.
750 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
751 const char *from, size_t fromlen,
752 int padding, int warnOnFailure)
754 int r;
755 tor_assert(env);
756 tor_assert(from);
757 tor_assert(to);
758 tor_assert(env->key);
759 tor_assert(fromlen<INT_MAX);
760 if (!env->key->p)
761 /* Not a private key */
762 return -1;
764 r = RSA_private_decrypt((int)fromlen,
765 (unsigned char*)from, (unsigned char*)to,
766 env->key, crypto_get_rsa_padding(padding));
768 if (r<0) {
769 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
770 "performing RSA decryption");
771 return -1;
773 return r;
776 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
777 * public key in <b>env</b>, using PKCS1 padding. On success, write the
778 * signed data to <b>to</b>, and return the number of bytes written.
779 * On failure, return -1.
782 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
783 const char *from, size_t fromlen)
785 int r;
786 tor_assert(env);
787 tor_assert(from);
788 tor_assert(to);
789 tor_assert(fromlen < INT_MAX);
790 r = RSA_public_decrypt((int)fromlen,
791 (unsigned char*)from, (unsigned char*)to,
792 env->key, RSA_PKCS1_PADDING);
794 if (r<0) {
795 crypto_log_errors(LOG_WARN, "checking RSA signature");
796 return -1;
798 return r;
801 /** Check a siglen-byte long signature at <b>sig</b> against
802 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
803 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
804 * SHA1(data). Else return -1.
807 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
808 size_t datalen, const char *sig, size_t siglen)
810 char digest[DIGEST_LEN];
811 char *buf;
812 int r;
814 tor_assert(env);
815 tor_assert(data);
816 tor_assert(sig);
818 if (crypto_digest(digest,data,datalen)<0) {
819 log_warn(LD_BUG, "couldn't compute digest");
820 return -1;
822 buf = tor_malloc(crypto_pk_keysize(env)+1);
823 r = crypto_pk_public_checksig(env,buf,sig,siglen);
824 if (r != DIGEST_LEN) {
825 log_warn(LD_CRYPTO, "Invalid signature");
826 tor_free(buf);
827 return -1;
829 if (memcmp(buf, digest, DIGEST_LEN)) {
830 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
831 tor_free(buf);
832 return -1;
834 tor_free(buf);
836 return 0;
839 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
840 * <b>env</b>, using PKCS1 padding. On success, write the signature to
841 * <b>to</b>, and return the number of bytes written. On failure, return
842 * -1.
845 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
846 const char *from, size_t fromlen)
848 int r;
849 tor_assert(env);
850 tor_assert(from);
851 tor_assert(to);
852 tor_assert(fromlen < INT_MAX);
853 if (!env->key->p)
854 /* Not a private key */
855 return -1;
857 r = RSA_private_encrypt((int)fromlen,
858 (unsigned char*)from, (unsigned char*)to,
859 env->key, RSA_PKCS1_PADDING);
860 if (r<0) {
861 crypto_log_errors(LOG_WARN, "generating RSA signature");
862 return -1;
864 return r;
867 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
868 * <b>from</b>; sign the data with the private key in <b>env</b>, and
869 * store it in <b>to</b>. Return the number of bytes written on
870 * success, and -1 on failure.
873 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
874 const char *from, size_t fromlen)
876 int r;
877 char digest[DIGEST_LEN];
878 if (crypto_digest(digest,from,fromlen)<0)
879 return -1;
880 r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
881 memset(digest, 0, sizeof(digest));
882 return r;
885 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
886 * bytes of data from <b>from</b>, with padding type 'padding',
887 * storing the results on <b>to</b>.
889 * If no padding is used, the public key must be at least as large as
890 * <b>from</b>.
892 * Returns the number of bytes written on success, -1 on failure.
894 * The encrypted data consists of:
895 * - The source data, padded and encrypted with the public key, if the
896 * padded source data is no longer than the public key, and <b>force</b>
897 * is false, OR
898 * - The beginning of the source data prefixed with a 16-byte symmetric key,
899 * padded and encrypted with the public key; followed by the rest of
900 * the source data encrypted in AES-CTR mode with the symmetric key.
903 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
904 char *to,
905 const char *from,
906 size_t fromlen,
907 int padding, int force)
909 int overhead, outlen, r;
910 size_t pkeylen, symlen;
911 crypto_cipher_env_t *cipher = NULL;
912 char *buf = NULL;
914 tor_assert(env);
915 tor_assert(from);
916 tor_assert(to);
918 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
919 pkeylen = crypto_pk_keysize(env);
921 if (padding == PK_NO_PADDING && fromlen < pkeylen)
922 return -1;
924 if (!force && fromlen+overhead <= pkeylen) {
925 /* It all fits in a single encrypt. */
926 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
928 cipher = crypto_new_cipher_env();
929 if (!cipher) return -1;
930 if (crypto_cipher_generate_key(cipher)<0)
931 goto err;
932 /* You can't just run around RSA-encrypting any bitstream: if it's
933 * greater than the RSA key, then OpenSSL will happily encrypt, and
934 * later decrypt to the wrong value. So we set the first bit of
935 * 'cipher->key' to 0 if we aren't padding. This means that our
936 * symmetric key is really only 127 bits.
938 if (padding == PK_NO_PADDING)
939 cipher->key[0] &= 0x7f;
940 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
941 goto err;
942 buf = tor_malloc(pkeylen+1);
943 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
944 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
946 /* Length of symmetrically encrypted data. */
947 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
949 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
950 if (outlen!=(int)pkeylen) {
951 goto err;
953 r = crypto_cipher_encrypt(cipher, to+outlen,
954 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
956 if (r<0) goto err;
957 memset(buf, 0, pkeylen);
958 tor_free(buf);
959 crypto_free_cipher_env(cipher);
960 tor_assert(outlen+symlen < INT_MAX);
961 return (int)(outlen + symlen);
962 err:
963 if (buf) {
964 memset(buf, 0, pkeylen);
965 tor_free(buf);
967 if (cipher) crypto_free_cipher_env(cipher);
968 return -1;
971 /** Invert crypto_pk_public_hybrid_encrypt. */
973 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
974 char *to,
975 const char *from,
976 size_t fromlen,
977 int padding, int warnOnFailure)
979 int outlen, r;
980 size_t pkeylen;
981 crypto_cipher_env_t *cipher = NULL;
982 char *buf = NULL;
984 pkeylen = crypto_pk_keysize(env);
986 if (fromlen <= pkeylen) {
987 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
988 warnOnFailure);
990 buf = tor_malloc(pkeylen+1);
991 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
992 warnOnFailure);
993 if (outlen<0) {
994 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
995 "Error decrypting public-key data");
996 goto err;
998 if (outlen < CIPHER_KEY_LEN) {
999 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1000 "No room for a symmetric key");
1001 goto err;
1003 cipher = crypto_create_init_cipher(buf, 0);
1004 if (!cipher) {
1005 goto err;
1007 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1008 outlen -= CIPHER_KEY_LEN;
1009 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1010 if (r<0)
1011 goto err;
1012 memset(buf,0,pkeylen);
1013 tor_free(buf);
1014 crypto_free_cipher_env(cipher);
1015 tor_assert(outlen + fromlen < INT_MAX);
1016 return (int)(outlen + (fromlen-pkeylen));
1017 err:
1018 memset(buf,0,pkeylen);
1019 tor_free(buf);
1020 if (cipher) crypto_free_cipher_env(cipher);
1021 return -1;
1024 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1025 * Return -1 on error, or the number of characters used on success.
1028 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1030 int len;
1031 unsigned char *buf, *cp;
1032 len = i2d_RSAPublicKey(pk->key, NULL);
1033 if (len < 0 || (size_t)len > dest_len)
1034 return -1;
1035 cp = buf = tor_malloc(len+1);
1036 len = i2d_RSAPublicKey(pk->key, &cp);
1037 if (len < 0) {
1038 crypto_log_errors(LOG_WARN,"encoding public key");
1039 tor_free(buf);
1040 return -1;
1042 /* We don't encode directly into 'dest', because that would be illegal
1043 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1045 memcpy(dest,buf,len);
1046 tor_free(buf);
1047 return len;
1050 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1051 * success and NULL on failure.
1053 crypto_pk_env_t *
1054 crypto_pk_asn1_decode(const char *str, size_t len)
1056 RSA *rsa;
1057 unsigned char *buf;
1058 /* This ifdef suppresses a type warning. Take out the first case once
1059 * everybody is using openssl 0.9.7 or later.
1061 const unsigned char *cp;
1062 cp = buf = tor_malloc(len);
1063 memcpy(buf,str,len);
1064 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1065 tor_free(buf);
1066 if (!rsa) {
1067 crypto_log_errors(LOG_WARN,"decoding public key");
1068 return NULL;
1070 return _crypto_new_pk_env_rsa(rsa);
1073 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1074 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1075 * Return 0 on success, -1 on failure.
1078 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1080 unsigned char *buf, *bufp;
1081 int len;
1083 len = i2d_RSAPublicKey(pk->key, NULL);
1084 if (len < 0)
1085 return -1;
1086 buf = bufp = tor_malloc(len+1);
1087 len = i2d_RSAPublicKey(pk->key, &bufp);
1088 if (len < 0) {
1089 crypto_log_errors(LOG_WARN,"encoding public key");
1090 tor_free(buf);
1091 return -1;
1093 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1094 tor_free(buf);
1095 return -1;
1097 tor_free(buf);
1098 return 0;
1101 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1102 * every four spaces. */
1103 /* static */ void
1104 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1106 int n = 0;
1107 char *end = out+outlen;
1108 while (*in && out<end) {
1109 *out++ = *in++;
1110 if (++n == 4 && *in && out<end) {
1111 n = 0;
1112 *out++ = ' ';
1115 tor_assert(out<end);
1116 *out = '\0';
1119 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1120 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1121 * space). Return 0 on success, -1 on failure.
1123 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1124 * of the public key, converted to hexadecimal, in upper case, with a
1125 * space after every four digits.
1127 * If <b>add_space</b> is false, omit the spaces.
1130 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1132 char digest[DIGEST_LEN];
1133 char hexdigest[HEX_DIGEST_LEN+1];
1134 if (crypto_pk_get_digest(pk, digest)) {
1135 return -1;
1137 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1138 if (add_space) {
1139 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1140 } else {
1141 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1143 return 0;
1146 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1149 crypto_pk_check_fingerprint_syntax(const char *s)
1151 int i;
1152 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1153 if ((i%5) == 4) {
1154 if (!TOR_ISSPACE(s[i])) return 0;
1155 } else {
1156 if (!TOR_ISXDIGIT(s[i])) return 0;
1159 if (s[FINGERPRINT_LEN]) return 0;
1160 return 1;
1163 /* symmetric crypto */
1165 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1166 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1169 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1171 tor_assert(env);
1173 return crypto_rand(env->key, CIPHER_KEY_LEN);
1176 /** Set the symmetric key for the cipher in <b>env</b> to the first
1177 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1178 * Return 0 on success, -1 on failure.
1181 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1183 tor_assert(env);
1184 tor_assert(key);
1186 if (!env->key)
1187 return -1;
1189 memcpy(env->key, key, CIPHER_KEY_LEN);
1190 return 0;
1193 /** Generate an initialization vector for our AES-CTR cipher; store it
1194 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1195 void
1196 crypto_cipher_generate_iv(char *iv_out)
1198 crypto_rand(iv_out, CIPHER_IV_LEN);
1201 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1202 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1203 * <b>iv</b>. */
1205 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1207 tor_assert(env);
1208 tor_assert(iv);
1209 aes_set_iv(env->cipher, iv);
1210 return 0;
1213 /** Return a pointer to the key set for the cipher in <b>env</b>.
1215 const char *
1216 crypto_cipher_get_key(crypto_cipher_env_t *env)
1218 return env->key;
1221 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1222 * success, -1 on failure.
1225 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1227 tor_assert(env);
1229 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1230 return 0;
1233 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1234 * success, -1 on failure.
1237 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1239 tor_assert(env);
1241 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1242 return 0;
1245 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1246 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1247 * On failure, return -1.
1250 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1251 const char *from, size_t fromlen)
1253 tor_assert(env);
1254 tor_assert(env->cipher);
1255 tor_assert(from);
1256 tor_assert(fromlen);
1257 tor_assert(to);
1259 aes_crypt(env->cipher, from, fromlen, to);
1260 return 0;
1263 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1264 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1265 * On failure, return -1.
1268 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1269 const char *from, size_t fromlen)
1271 tor_assert(env);
1272 tor_assert(from);
1273 tor_assert(to);
1275 aes_crypt(env->cipher, from, fromlen, to);
1276 return 0;
1279 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1280 * on success, return 0. On failure, return -1.
1283 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1285 aes_crypt_inplace(env->cipher, buf, len);
1286 return 0;
1289 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1290 * <b>cipher</b> to the buffer in <b>to</b> of length
1291 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1292 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1293 * number of bytes written, on failure, return -1.
1295 * This function adjusts the current position of the counter in <b>cipher</b>
1296 * to immediately after the encrypted data.
1299 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1300 char *to, size_t tolen,
1301 const char *from, size_t fromlen)
1303 tor_assert(cipher);
1304 tor_assert(from);
1305 tor_assert(to);
1306 tor_assert(fromlen < INT_MAX);
1308 if (fromlen < 1)
1309 return -1;
1310 if (tolen < fromlen + CIPHER_IV_LEN)
1311 return -1;
1313 crypto_cipher_generate_iv(to);
1314 if (crypto_cipher_set_iv(cipher, to)<0)
1315 return -1;
1316 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1317 return (int)(fromlen + CIPHER_IV_LEN);
1320 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1321 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1322 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1323 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1324 * number of bytes written, on failure, return -1.
1326 * This function adjusts the current position of the counter in <b>cipher</b>
1327 * to immediately after the decrypted data.
1330 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1331 char *to, size_t tolen,
1332 const char *from, size_t fromlen)
1334 tor_assert(cipher);
1335 tor_assert(from);
1336 tor_assert(to);
1337 tor_assert(fromlen < INT_MAX);
1339 if (fromlen <= CIPHER_IV_LEN)
1340 return -1;
1341 if (tolen < fromlen - CIPHER_IV_LEN)
1342 return -1;
1344 if (crypto_cipher_set_iv(cipher, from)<0)
1345 return -1;
1346 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1347 return (int)(fromlen - CIPHER_IV_LEN);
1350 /* SHA-1 */
1352 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1353 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1354 * Return 0 on success, -1 on failure.
1357 crypto_digest(char *digest, const char *m, size_t len)
1359 tor_assert(m);
1360 tor_assert(digest);
1361 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1364 /** Intermediate information about the digest of a stream of data. */
1365 struct crypto_digest_env_t {
1366 SHA_CTX d;
1369 /** Allocate and return a new digest object.
1371 crypto_digest_env_t *
1372 crypto_new_digest_env(void)
1374 crypto_digest_env_t *r;
1375 r = tor_malloc(sizeof(crypto_digest_env_t));
1376 SHA1_Init(&r->d);
1377 return r;
1380 /** Deallocate a digest object.
1382 void
1383 crypto_free_digest_env(crypto_digest_env_t *digest)
1385 memset(digest, 0, sizeof(crypto_digest_env_t));
1386 tor_free(digest);
1389 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1391 void
1392 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1393 size_t len)
1395 tor_assert(digest);
1396 tor_assert(data);
1397 /* Using the SHA1_*() calls directly means we don't support doing
1398 * sha1 in hardware. But so far the delay of getting the question
1399 * to the hardware, and hearing the answer, is likely higher than
1400 * just doing it ourselves. Hashes are fast.
1402 SHA1_Update(&digest->d, (void*)data, len);
1405 /** Compute the hash of the data that has been passed to the digest
1406 * object; write the first out_len bytes of the result to <b>out</b>.
1407 * <b>out_len</b> must be \<= DIGEST_LEN.
1409 void
1410 crypto_digest_get_digest(crypto_digest_env_t *digest,
1411 char *out, size_t out_len)
1413 unsigned char r[DIGEST_LEN];
1414 SHA_CTX tmpctx;
1415 tor_assert(digest);
1416 tor_assert(out);
1417 tor_assert(out_len <= DIGEST_LEN);
1418 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1419 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1420 SHA1_Final(r, &tmpctx);
1421 memcpy(out, r, out_len);
1422 memset(r, 0, sizeof(r));
1425 /** Allocate and return a new digest object with the same state as
1426 * <b>digest</b>
1428 crypto_digest_env_t *
1429 crypto_digest_dup(const crypto_digest_env_t *digest)
1431 crypto_digest_env_t *r;
1432 tor_assert(digest);
1433 r = tor_malloc(sizeof(crypto_digest_env_t));
1434 memcpy(r,digest,sizeof(crypto_digest_env_t));
1435 return r;
1438 /** Replace the state of the digest object <b>into</b> with the state
1439 * of the digest object <b>from</b>.
1441 void
1442 crypto_digest_assign(crypto_digest_env_t *into,
1443 const crypto_digest_env_t *from)
1445 tor_assert(into);
1446 tor_assert(from);
1447 memcpy(into,from,sizeof(crypto_digest_env_t));
1450 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1451 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1452 * in <b>hmac_out</b>.
1454 void
1455 crypto_hmac_sha1(char *hmac_out,
1456 const char *key, size_t key_len,
1457 const char *msg, size_t msg_len)
1459 tor_assert(key_len < INT_MAX);
1460 tor_assert(msg_len < INT_MAX);
1461 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1462 (unsigned char*)hmac_out, NULL);
1465 /* DH */
1467 /** Shared P parameter for our DH key exchanged. */
1468 static BIGNUM *dh_param_p = NULL;
1469 /** Shared G parameter for our DH key exchanges. */
1470 static BIGNUM *dh_param_g = NULL;
1472 /** Initialize dh_param_p and dh_param_g if they are not already
1473 * set. */
1474 static void
1475 init_dh_param(void)
1477 BIGNUM *p, *g;
1478 int r;
1479 if (dh_param_p && dh_param_g)
1480 return;
1482 p = BN_new();
1483 g = BN_new();
1484 tor_assert(p);
1485 tor_assert(g);
1487 /* This is from rfc2409, section 6.2. It's a safe prime, and
1488 supposedly it equals:
1489 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1491 r = BN_hex2bn(&p,
1492 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1493 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1494 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1495 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1496 "49286651ECE65381FFFFFFFFFFFFFFFF");
1497 tor_assert(r);
1499 r = BN_set_word(g, 2);
1500 tor_assert(r);
1501 dh_param_p = p;
1502 dh_param_g = g;
1505 #define DH_PRIVATE_KEY_BITS 320
1507 /** Allocate and return a new DH object for a key exchange.
1509 crypto_dh_env_t *
1510 crypto_dh_new(void)
1512 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1514 if (!dh_param_p)
1515 init_dh_param();
1517 if (!(res->dh = DH_new()))
1518 goto err;
1520 if (!(res->dh->p = BN_dup(dh_param_p)))
1521 goto err;
1523 if (!(res->dh->g = BN_dup(dh_param_g)))
1524 goto err;
1526 res->dh->length = DH_PRIVATE_KEY_BITS;
1528 return res;
1529 err:
1530 crypto_log_errors(LOG_WARN, "creating DH object");
1531 if (res->dh) DH_free(res->dh); /* frees p and g too */
1532 tor_free(res);
1533 return NULL;
1536 /** Return the length of the DH key in <b>dh</b>, in bytes.
1539 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1541 tor_assert(dh);
1542 return DH_size(dh->dh);
1545 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1546 * success, -1 on failure.
1549 crypto_dh_generate_public(crypto_dh_env_t *dh)
1551 again:
1552 if (!DH_generate_key(dh->dh)) {
1553 crypto_log_errors(LOG_WARN, "generating DH key");
1554 return -1;
1556 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1557 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1558 "the-universe chances really do happen. Trying again.");
1559 /* Free and clear the keys, so openssl will actually try again. */
1560 BN_free(dh->dh->pub_key);
1561 BN_free(dh->dh->priv_key);
1562 dh->dh->pub_key = dh->dh->priv_key = NULL;
1563 goto again;
1565 return 0;
1568 /** Generate g^x as necessary, and write the g^x for the key exchange
1569 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1570 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1573 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1575 int bytes;
1576 tor_assert(dh);
1577 if (!dh->dh->pub_key) {
1578 if (crypto_dh_generate_public(dh)<0)
1579 return -1;
1582 tor_assert(dh->dh->pub_key);
1583 bytes = BN_num_bytes(dh->dh->pub_key);
1584 tor_assert(bytes >= 0);
1585 if (pubkey_len < (size_t)bytes) {
1586 log_warn(LD_CRYPTO,
1587 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1588 (int) pubkey_len, bytes);
1589 return -1;
1592 memset(pubkey, 0, pubkey_len);
1593 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1595 return 0;
1598 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1599 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1600 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1602 static int
1603 tor_check_dh_key(BIGNUM *bn)
1605 BIGNUM *x;
1606 char *s;
1607 tor_assert(bn);
1608 x = BN_new();
1609 tor_assert(x);
1610 if (!dh_param_p)
1611 init_dh_param();
1612 BN_set_word(x, 1);
1613 if (BN_cmp(bn,x)<=0) {
1614 log_warn(LD_CRYPTO, "DH key must be at least 2.");
1615 goto err;
1617 BN_copy(x,dh_param_p);
1618 BN_sub_word(x, 1);
1619 if (BN_cmp(bn,x)>=0) {
1620 log_warn(LD_CRYPTO, "DH key must be at most p-2.");
1621 goto err;
1623 BN_free(x);
1624 return 0;
1625 err:
1626 BN_free(x);
1627 s = BN_bn2hex(bn);
1628 log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1629 OPENSSL_free(s);
1630 return -1;
1633 #undef MIN
1634 #define MIN(a,b) ((a)<(b)?(a):(b))
1635 /** Given a DH key exchange object, and our peer's value of g^y (as a
1636 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1637 * <b>secret_bytes_out</b> bytes of shared key material and write them
1638 * to <b>secret_out</b>. Return the number of bytes generated on success,
1639 * or -1 on failure.
1641 * (We generate key material by computing
1642 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1643 * where || is concatenation.)
1645 ssize_t
1646 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1647 const char *pubkey, size_t pubkey_len,
1648 char *secret_out, size_t secret_bytes_out)
1650 char *secret_tmp = NULL;
1651 BIGNUM *pubkey_bn = NULL;
1652 size_t secret_len=0;
1653 int result=0;
1654 tor_assert(dh);
1655 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1656 tor_assert(pubkey_len < INT_MAX);
1658 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1659 (int)pubkey_len, NULL)))
1660 goto error;
1661 if (tor_check_dh_key(pubkey_bn)<0) {
1662 /* Check for invalid public keys. */
1663 log_warn(LD_CRYPTO,"Rejected invalid g^x");
1664 goto error;
1666 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1667 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1668 if (result < 0) {
1669 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1670 goto error;
1672 secret_len = result;
1673 if (crypto_expand_key_material(secret_tmp, secret_len,
1674 secret_out, secret_bytes_out)<0)
1675 goto error;
1676 secret_len = secret_bytes_out;
1678 goto done;
1679 error:
1680 result = -1;
1681 done:
1682 crypto_log_errors(LOG_WARN, "completing DH handshake");
1683 if (pubkey_bn)
1684 BN_free(pubkey_bn);
1685 tor_free(secret_tmp);
1686 if (result < 0)
1687 return result;
1688 else
1689 return secret_len;
1692 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1693 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1694 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1695 * H(K | [00]) | H(K | [01]) | ....
1697 * Return 0 on success, -1 on failure.
1700 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1701 char *key_out, size_t key_out_len)
1703 int i;
1704 char *cp, *tmp = tor_malloc(key_in_len+1);
1705 char digest[DIGEST_LEN];
1707 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1708 tor_assert(key_out_len <= DIGEST_LEN*256);
1710 memcpy(tmp, key_in, key_in_len);
1711 for (cp = key_out, i=0; cp < key_out+key_out_len;
1712 ++i, cp += DIGEST_LEN) {
1713 tmp[key_in_len] = i;
1714 if (crypto_digest(digest, tmp, key_in_len+1))
1715 goto err;
1716 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1718 memset(tmp, 0, key_in_len+1);
1719 tor_free(tmp);
1720 memset(digest, 0, sizeof(digest));
1721 return 0;
1723 err:
1724 memset(tmp, 0, key_in_len+1);
1725 tor_free(tmp);
1726 memset(digest, 0, sizeof(digest));
1727 return -1;
1730 /** Free a DH key exchange object.
1732 void
1733 crypto_dh_free(crypto_dh_env_t *dh)
1735 tor_assert(dh);
1736 tor_assert(dh->dh);
1737 DH_free(dh->dh);
1738 tor_free(dh);
1741 /* random numbers */
1743 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1744 * work for us too. */
1745 #define ADD_ENTROPY 32
1747 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1748 "release".) */
1749 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1751 /* Versions of openssl prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1752 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1753 * that fd without checking whether it fit in the fd_set. Thus, if the
1754 * system has not just been started up, it is unsafe to call */
1755 #define RAND_POLL_IS_SAFE \
1756 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1757 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1758 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1760 /** Seed OpenSSL's random number generator with bytes from the operating
1761 * system. <b>startup</b> should be true iff we have just started Tor and
1762 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1765 crypto_seed_rng(int startup)
1767 char buf[ADD_ENTROPY];
1768 int rand_poll_status = 0;
1770 /* local variables */
1771 #ifdef MS_WINDOWS
1772 static int provider_set = 0;
1773 static HCRYPTPROV provider;
1774 #else
1775 static const char *filenames[] = {
1776 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1778 int fd, i;
1779 size_t n;
1780 #endif
1782 #if HAVE_RAND_POLL
1783 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1784 * entropy than we do. We'll try calling that, *and* calling our own entropy
1785 * functions. If one succeeds, we'll accept the RNG as seeded. */
1786 if (startup || RAND_POLL_IS_SAFE) {
1787 rand_poll_status = RAND_poll();
1788 if (rand_poll_status == 0)
1789 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1791 #endif
1793 #ifdef MS_WINDOWS
1794 if (!provider_set) {
1795 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1796 CRYPT_VERIFYCONTEXT)) {
1797 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1798 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1799 return rand_poll_status ? 0 : -1;
1802 provider_set = 1;
1804 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1805 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1806 return rand_poll_status ? 0 : -1;
1808 RAND_seed(buf, sizeof(buf));
1809 memset(buf, 0, sizeof(buf));
1810 return 0;
1811 #else
1812 for (i = 0; filenames[i]; ++i) {
1813 fd = open(filenames[i], O_RDONLY, 0);
1814 if (fd<0) continue;
1815 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1816 n = read_all(fd, buf, sizeof(buf), 0);
1817 close(fd);
1818 if (n != sizeof(buf)) {
1819 log_warn(LD_CRYPTO,
1820 "Error reading from entropy source (read only %lu bytes).",
1821 (unsigned long)n);
1822 return -1;
1824 RAND_seed(buf, (int)sizeof(buf));
1825 memset(buf, 0, sizeof(buf));
1826 return 0;
1829 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1830 return rand_poll_status ? 0 : -1;
1831 #endif
1834 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1835 * success, -1 on failure.
1838 crypto_rand(char *to, size_t n)
1840 int r;
1841 tor_assert(n < INT_MAX);
1842 tor_assert(to);
1843 r = RAND_bytes((unsigned char*)to, (int)n);
1844 if (r == 0)
1845 crypto_log_errors(LOG_WARN, "generating random data");
1846 return (r == 1) ? 0 : -1;
1849 /** Return a pseudorandom integer, chosen uniformly from the values
1850 * between 0 and <b>max</b>-1. */
1852 crypto_rand_int(unsigned int max)
1854 unsigned int val;
1855 unsigned int cutoff;
1856 tor_assert(max < UINT_MAX);
1857 tor_assert(max > 0); /* don't div by 0 */
1859 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1860 * distribution with clipping at the upper end of unsigned int's
1861 * range.
1863 cutoff = UINT_MAX - (UINT_MAX%max);
1864 while (1) {
1865 crypto_rand((char*)&val, sizeof(val));
1866 if (val < cutoff)
1867 return val % max;
1871 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1872 * between 0 and <b>max</b>-1. */
1873 uint64_t
1874 crypto_rand_uint64(uint64_t max)
1876 uint64_t val;
1877 uint64_t cutoff;
1878 tor_assert(max < UINT64_MAX);
1879 tor_assert(max > 0); /* don't div by 0 */
1881 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1882 * distribution with clipping at the upper end of unsigned int's
1883 * range.
1885 cutoff = UINT64_MAX - (UINT64_MAX%max);
1886 while (1) {
1887 crypto_rand((char*)&val, sizeof(val));
1888 if (val < cutoff)
1889 return val % max;
1893 /** Generate and return a new random hostname starting with <b>prefix</b>,
1894 * ending with <b>suffix</b>, and containing no less than
1895 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1896 * characters between. */
1897 char *
1898 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
1899 const char *suffix)
1901 char *result, *rand_bytes;
1902 int randlen, rand_bytes_len;
1903 size_t resultlen, prefixlen;
1905 tor_assert(max_rand_len >= min_rand_len);
1906 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
1907 prefixlen = strlen(prefix);
1908 resultlen = prefixlen + strlen(suffix) + randlen + 16;
1910 rand_bytes_len = ((randlen*5)+7)/8;
1911 if (rand_bytes_len % 5)
1912 rand_bytes_len += 5 - (rand_bytes_len%5);
1913 rand_bytes = tor_malloc(rand_bytes_len);
1914 crypto_rand(rand_bytes, rand_bytes_len);
1916 result = tor_malloc(resultlen);
1917 memcpy(result, prefix, prefixlen);
1918 base32_encode(result+prefixlen, resultlen-prefixlen,
1919 rand_bytes, rand_bytes_len);
1920 tor_free(rand_bytes);
1921 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
1923 return result;
1926 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1927 * is empty. */
1928 void *
1929 smartlist_choose(const smartlist_t *sl)
1931 int len = smartlist_len(sl);
1932 if (len)
1933 return smartlist_get(sl,crypto_rand_int(len));
1934 return NULL; /* no elements to choose from */
1937 /** Scramble the elements of <b>sl</b> into a random order. */
1938 void
1939 smartlist_shuffle(smartlist_t *sl)
1941 int i;
1942 /* From the end of the list to the front, choose at random from the
1943 positions we haven't looked at yet, and swap that position into the
1944 current position. Remember to give "no swap" the same probability as
1945 any other swap. */
1946 for (i = smartlist_len(sl)-1; i > 0; --i) {
1947 int j = crypto_rand_int(i+1);
1948 smartlist_swap(sl, i, j);
1952 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1953 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1954 * bytes. Return the number of bytes written on success; -1 if
1955 * destlen is too short, or other failure.
1958 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1960 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1961 * it ever shows up in the profile. */
1962 EVP_ENCODE_CTX ctx;
1963 int len, ret;
1964 tor_assert(srclen < INT_MAX);
1966 /* 48 bytes of input -> 64 bytes of output plus newline.
1967 Plus one more byte, in case I'm wrong.
1969 if (destlen < ((srclen/48)+1)*66)
1970 return -1;
1971 if (destlen > SIZE_T_CEILING)
1972 return -1;
1974 EVP_EncodeInit(&ctx);
1975 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
1976 (unsigned char*)src, (int)srclen);
1977 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1978 ret += len;
1979 return ret;
1982 #define X 255
1983 #define SP 64
1984 #define PAD 65
1985 /** Internal table mapping byte values to what they represent in base64.
1986 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
1987 * skipped. Xs are invalid and must not appear in base64. PAD indicates
1988 * end-of-string. */
1989 static const uint8_t base64_decode_table[256] = {
1990 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
1991 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
1992 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
1993 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
1994 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1995 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
1996 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1997 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
1998 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
1999 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2000 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2001 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2002 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2003 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2004 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2005 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2008 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2009 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2010 * bytes. Return the number of bytes written on success; -1 if
2011 * destlen is too short, or other failure.
2013 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2014 * spaces or padding.
2016 * NOTE 2: This implementation does not check for the correct number of
2017 * padding "=" characters at the end of the string, and does not check
2018 * for internal padding characters.
2021 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2023 #ifdef USE_OPENSSL_BASE64
2024 EVP_ENCODE_CTX ctx;
2025 int len, ret;
2026 /* 64 bytes of input -> *up to* 48 bytes of output.
2027 Plus one more byte, in case I'm wrong.
2029 if (destlen < ((srclen/64)+1)*49)
2030 return -1;
2031 if (destlen > SIZE_T_CEILING)
2032 return -1;
2034 EVP_DecodeInit(&ctx);
2035 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2036 (unsigned char*)src, srclen);
2037 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2038 ret += len;
2039 return ret;
2040 #else
2041 const char *eos = src+srclen;
2042 uint32_t n=0;
2043 int n_idx=0;
2044 char *dest_orig = dest;
2046 /* Max number of bits == srclen*6.
2047 * Number of bytes required to hold all bits == (srclen*6)/8.
2048 * Yes, we want to round down: anything that hangs over the end of a
2049 * byte is padding. */
2050 if (destlen < (srclen*3)/4)
2051 return -1;
2052 if (destlen > SIZE_T_CEILING)
2053 return -1;
2055 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2056 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2057 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2059 for ( ; src < eos; ++src) {
2060 unsigned char c = (unsigned char) *src;
2061 uint8_t v = base64_decode_table[c];
2062 switch (v) {
2063 case X:
2064 /* This character isn't allowed in base64. */
2065 return -1;
2066 case SP:
2067 /* This character is whitespace, and has no effect. */
2068 continue;
2069 case PAD:
2070 /* We've hit an = character: the data is over. */
2071 goto end_of_loop;
2072 default:
2073 /* We have an actual 6-bit value. Append it to the bits in n. */
2074 n = (n<<6) | v;
2075 if ((++n_idx) == 4) {
2076 /* We've accumulated 24 bits in n. Flush them. */
2077 *dest++ = (n>>16);
2078 *dest++ = (n>>8) & 0xff;
2079 *dest++ = (n) & 0xff;
2080 n_idx = 0;
2081 n = 0;
2085 end_of_loop:
2086 /* If we have leftover bits, we need to cope. */
2087 switch (n_idx) {
2088 case 0:
2089 default:
2090 /* No leftover bits. We win. */
2091 break;
2092 case 1:
2093 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2094 return -1;
2095 case 2:
2096 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2097 *dest++ = n >> 4;
2098 break;
2099 case 3:
2100 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2101 *dest++ = n >> 10;
2102 *dest++ = n >> 2;
2105 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2106 tor_assert((dest-dest_orig) <= INT_MAX);
2108 return (int)(dest-dest_orig);
2109 #endif
2111 #undef X
2112 #undef SP
2113 #undef PAD
2115 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2116 * and newline characters, and store the nul-terminated result in the first
2117 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2119 digest_to_base64(char *d64, const char *digest)
2121 char buf[256];
2122 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2123 buf[BASE64_DIGEST_LEN] = '\0';
2124 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2125 return 0;
2128 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2129 * trailing newline or = characters), decode it and store the result in the
2130 * first DIGEST_LEN bytes at <b>digest</b>. */
2132 digest_from_base64(char *digest, const char *d64)
2134 #ifdef USE_OPENSSL_BASE64
2135 char buf_in[BASE64_DIGEST_LEN+3];
2136 char buf[256];
2137 if (strlen(d64) != BASE64_DIGEST_LEN)
2138 return -1;
2139 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2140 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2141 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2142 return -1;
2143 memcpy(digest, buf, DIGEST_LEN);
2144 return 0;
2145 #else
2146 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2147 return 0;
2148 else
2149 return -1;
2150 #endif
2153 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2154 * that srclen*8 is a multiple of 5.
2156 void
2157 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2159 unsigned int i, bit, v, u;
2160 size_t nbits = srclen * 8;
2162 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2163 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2164 tor_assert(destlen < SIZE_T_CEILING);
2166 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2167 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2168 v = ((uint8_t)src[bit/8]) << 8;
2169 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2170 /* set u to the 5-bit value at the bit'th bit of src. */
2171 u = (v >> (11-(bit%8))) & 0x1F;
2172 dest[i] = BASE32_CHARS[u];
2174 dest[i] = '\0';
2177 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2178 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2181 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2183 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2184 * it ever shows up in the profile. */
2185 unsigned int i, j, bit;
2186 size_t nbits;
2187 char *tmp;
2188 nbits = srclen * 5;
2190 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2191 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2192 tor_assert(destlen < SIZE_T_CEILING);
2194 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2195 tmp = tor_malloc_zero(srclen);
2196 for (j = 0; j < srclen; ++j) {
2197 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2198 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2199 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2200 else {
2201 log_warn(LD_BUG, "illegal character in base32 encoded string");
2202 tor_free(tmp);
2203 return -1;
2207 /* Assemble result byte-wise by applying five possible cases. */
2208 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2209 switch (bit % 40) {
2210 case 0:
2211 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2212 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2213 break;
2214 case 8:
2215 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2216 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2217 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2218 break;
2219 case 16:
2220 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2221 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2222 break;
2223 case 24:
2224 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2225 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2226 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2227 break;
2228 case 32:
2229 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2230 ((uint8_t)tmp[(bit/5)+1]);
2231 break;
2235 memset(tmp, 0, srclen);
2236 tor_free(tmp);
2237 tmp = NULL;
2238 return 0;
2241 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2242 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2243 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2244 * are a salt; the 9th byte describes how much iteration to do.
2245 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2247 void
2248 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2249 size_t secret_len, const char *s2k_specifier)
2251 crypto_digest_env_t *d;
2252 uint8_t c;
2253 size_t count, tmplen;
2254 char *tmp;
2255 tor_assert(key_out_len < SIZE_T_CEILING);
2257 #define EXPBIAS 6
2258 c = s2k_specifier[8];
2259 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2260 #undef EXPBIAS
2262 tor_assert(key_out_len <= DIGEST_LEN);
2264 d = crypto_new_digest_env();
2265 tmplen = 8+secret_len;
2266 tmp = tor_malloc(tmplen);
2267 memcpy(tmp,s2k_specifier,8);
2268 memcpy(tmp+8,secret,secret_len);
2269 secret_len += 8;
2270 while (count) {
2271 if (count >= secret_len) {
2272 crypto_digest_add_bytes(d, tmp, secret_len);
2273 count -= secret_len;
2274 } else {
2275 crypto_digest_add_bytes(d, tmp, count);
2276 count = 0;
2279 crypto_digest_get_digest(d, key_out, key_out_len);
2280 memset(tmp, 0, tmplen);
2281 tor_free(tmp);
2282 crypto_free_digest_env(d);
2285 #ifdef TOR_IS_MULTITHREADED
2286 /** Helper: openssl uses this callback to manipulate mutexes. */
2287 static void
2288 _openssl_locking_cb(int mode, int n, const char *file, int line)
2290 (void)file;
2291 (void)line;
2292 if (!_openssl_mutexes)
2293 /* This is not a really good fix for the
2294 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2295 * it can't hurt. */
2296 return;
2297 if (mode & CRYPTO_LOCK)
2298 tor_mutex_acquire(_openssl_mutexes[n]);
2299 else
2300 tor_mutex_release(_openssl_mutexes[n]);
2303 /** OpenSSL helper type: wraps a Tor mutex so that openssl can */
2304 struct CRYPTO_dynlock_value {
2305 tor_mutex_t *lock;
2308 /** Openssl callback function to allocate a lock: see CRYPTO_set_dynlock_*
2309 * documentation in OpenSSL's docs for more info. */
2310 static struct CRYPTO_dynlock_value *
2311 _openssl_dynlock_create_cb(const char *file, int line)
2313 struct CRYPTO_dynlock_value *v;
2314 (void)file;
2315 (void)line;
2316 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2317 v->lock = tor_mutex_new();
2318 return v;
2321 /** Openssl callback function to acquire or release a lock: see
2322 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2323 static void
2324 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2325 const char *file, int line)
2327 (void)file;
2328 (void)line;
2329 if (mode & CRYPTO_LOCK)
2330 tor_mutex_acquire(v->lock);
2331 else
2332 tor_mutex_release(v->lock);
2335 /** Openssl callback function to free a lock: see CRYPTO_set_dynlock_*
2336 * documentation in OpenSSL's docs for more info. */
2337 static void
2338 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2339 const char *file, int line)
2341 (void)file;
2342 (void)line;
2343 tor_mutex_free(v->lock);
2344 tor_free(v);
2347 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2348 * multithreaded. */
2349 static int
2350 setup_openssl_threading(void)
2352 int i;
2353 int n = CRYPTO_num_locks();
2354 _n_openssl_mutexes = n;
2355 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2356 for (i=0; i < n; ++i)
2357 _openssl_mutexes[i] = tor_mutex_new();
2358 CRYPTO_set_locking_callback(_openssl_locking_cb);
2359 CRYPTO_set_id_callback(tor_get_thread_id);
2360 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2361 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2362 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2363 return 0;
2365 #else
2366 static int
2367 setup_openssl_threading(void)
2369 return 0;
2371 #endif