Fix bug 1173: remove an assert(unsigned >= 0).
[tor/rransom.git] / src / common / crypto.c
blob8676b6bc7b3c1166b6a452ebafb2eab80d6c4e4d
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file crypto.c
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
11 **/
13 #include "orconfig.h"
15 #ifdef MS_WINDOWS
16 #define WIN32_WINNT 0x400
17 #define _WIN32_WINNT 0x400
18 #define WIN32_LEAN_AND_MEAN
19 #include <windows.h>
20 #include <wincrypt.h>
21 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
22 * use either definition. */
23 #undef OCSP_RESPONSE
24 #endif
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/rand.h>
31 #include <openssl/opensslv.h>
32 #include <openssl/bn.h>
33 #include <openssl/dh.h>
34 #include <openssl/conf.h>
35 #include <openssl/hmac.h>
37 #ifdef HAVE_CTYPE_H
38 #include <ctype.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_SYS_FCNTL_H
47 #include <sys/fcntl.h>
48 #endif
50 #define CRYPTO_PRIVATE
51 #include "crypto.h"
52 #include "log.h"
53 #include "aes.h"
54 #include "util.h"
55 #include "container.h"
56 #include "compat.h"
58 #if OPENSSL_VERSION_NUMBER < 0x00907000l
59 #error "We require OpenSSL >= 0.9.7"
60 #endif
62 #include <openssl/engine.h>
64 /** Macro: is k a valid RSA public or private key? */
65 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
66 /** Macro: is k a valid RSA private key? */
67 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
69 #ifdef TOR_IS_MULTITHREADED
70 /** A number of preallocated mutexes for use by OpenSSL. */
71 static tor_mutex_t **_openssl_mutexes = NULL;
72 /** How many mutexes have we allocated for use by OpenSSL? */
73 static int _n_openssl_mutexes = 0;
74 #endif
76 /** A public key, or a public/private key-pair. */
77 struct crypto_pk_env_t
79 int refs; /* reference counting so we don't have to copy keys */
80 RSA *key;
83 /** Key and stream information for a stream cipher. */
84 struct crypto_cipher_env_t
86 char key[CIPHER_KEY_LEN];
87 aes_cnt_cipher_t *cipher;
90 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
91 * while we're waiting for the second.*/
92 struct crypto_dh_env_t {
93 DH *dh;
96 static int setup_openssl_threading(void);
97 static int tor_check_dh_key(BIGNUM *bn);
99 /** Return the number of bytes added by padding method <b>padding</b>.
101 static INLINE int
102 crypto_get_rsa_padding_overhead(int padding)
104 switch (padding)
106 case RSA_NO_PADDING: return 0;
107 case RSA_PKCS1_OAEP_PADDING: return 42;
108 case RSA_PKCS1_PADDING: return 11;
109 default: tor_assert(0); return -1;
113 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
115 static INLINE int
116 crypto_get_rsa_padding(int padding)
118 switch (padding)
120 case PK_NO_PADDING: return RSA_NO_PADDING;
121 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
122 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
123 default: tor_assert(0); return -1;
127 /** Boolean: has OpenSSL's crypto been initialized? */
128 static int _crypto_global_initialized = 0;
130 /** Log all pending crypto errors at level <b>severity</b>. Use
131 * <b>doing</b> to describe our current activities.
133 static void
134 crypto_log_errors(int severity, const char *doing)
136 unsigned long err;
137 const char *msg, *lib, *func;
138 while ((err = ERR_get_error()) != 0) {
139 msg = (const char*)ERR_reason_error_string(err);
140 lib = (const char*)ERR_lib_error_string(err);
141 func = (const char*)ERR_func_error_string(err);
142 if (!msg) msg = "(null)";
143 if (!lib) lib = "(null)";
144 if (!func) func = "(null)";
145 if (doing) {
146 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
147 doing, msg, lib, func);
148 } else {
149 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
154 /** Log any OpenSSL engines we're using at NOTICE. */
155 static void
156 log_engine(const char *fn, ENGINE *e)
158 if (e) {
159 const char *name, *id;
160 name = ENGINE_get_name(e);
161 id = ENGINE_get_id(e);
162 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
163 name?name:"?", id?id:"?", fn);
164 } else {
165 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
169 /** Initialize the crypto library. Return 0 on success, -1 on failure.
172 crypto_global_init(int useAccel)
174 if (!_crypto_global_initialized) {
175 ERR_load_crypto_strings();
176 OpenSSL_add_all_algorithms();
177 _crypto_global_initialized = 1;
178 setup_openssl_threading();
179 /* XXX the below is a bug, since we can't know if we're supposed
180 * to be using hardware acceleration or not. we should arrange
181 * for this function to be called before init_keys. But make it
182 * not complain loudly, at least until we make acceleration work. */
183 if (useAccel < 0) {
184 log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
186 if (useAccel > 0) {
187 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
188 ENGINE_load_builtin_engines();
189 if (!ENGINE_register_all_complete())
190 return -1;
192 /* XXXX make sure this isn't leaking. */
193 log_engine("RSA", ENGINE_get_default_RSA());
194 log_engine("DH", ENGINE_get_default_DH());
195 log_engine("RAND", ENGINE_get_default_RAND());
196 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
197 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
198 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
200 return crypto_seed_rng(1);
202 return 0;
205 /** Free crypto resources held by this thread. */
206 void
207 crypto_thread_cleanup(void)
209 ERR_remove_state(0);
212 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
215 crypto_global_cleanup(void)
217 EVP_cleanup();
218 ERR_remove_state(0);
219 ERR_free_strings();
220 ENGINE_cleanup();
221 CONF_modules_unload(1);
222 CRYPTO_cleanup_all_ex_data();
223 #ifdef TOR_IS_MULTITHREADED
224 if (_n_openssl_mutexes) {
225 int n = _n_openssl_mutexes;
226 tor_mutex_t **ms = _openssl_mutexes;
227 int i;
228 _openssl_mutexes = NULL;
229 _n_openssl_mutexes = 0;
230 for (i=0;i<n;++i) {
231 tor_mutex_free(ms[i]);
233 tor_free(ms);
235 #endif
236 return 0;
239 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
240 crypto_pk_env_t *
241 _crypto_new_pk_env_rsa(RSA *rsa)
243 crypto_pk_env_t *env;
244 tor_assert(rsa);
245 env = tor_malloc(sizeof(crypto_pk_env_t));
246 env->refs = 1;
247 env->key = rsa;
248 return env;
251 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
252 * returns NULL if this isn't an RSA key. */
253 crypto_pk_env_t *
254 _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
256 RSA *rsa;
257 if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
258 return NULL;
259 return _crypto_new_pk_env_rsa(rsa);
262 /** Helper, used by tor-checkkey.c. Return the RSA from a crypto_pk_env_t. */
263 RSA *
264 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
266 return env->key;
269 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
270 * private is set, include the private-key portion of the key. */
271 EVP_PKEY *
272 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
274 RSA *key = NULL;
275 EVP_PKEY *pkey = NULL;
276 tor_assert(env->key);
277 if (private) {
278 if (!(key = RSAPrivateKey_dup(env->key)))
279 goto error;
280 } else {
281 if (!(key = RSAPublicKey_dup(env->key)))
282 goto error;
284 if (!(pkey = EVP_PKEY_new()))
285 goto error;
286 if (!(EVP_PKEY_assign_RSA(pkey, key)))
287 goto error;
288 return pkey;
289 error:
290 if (pkey)
291 EVP_PKEY_free(pkey);
292 if (key)
293 RSA_free(key);
294 return NULL;
297 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
299 DH *
300 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
302 return dh->dh;
305 /** Allocate and return storage for a public key. The key itself will not yet
306 * be set.
308 crypto_pk_env_t *
309 crypto_new_pk_env(void)
311 RSA *rsa;
313 rsa = RSA_new();
314 if (!rsa) return NULL;
315 return _crypto_new_pk_env_rsa(rsa);
318 /** Release a reference to an asymmetric key; when all the references
319 * are released, free the key.
321 void
322 crypto_free_pk_env(crypto_pk_env_t *env)
324 tor_assert(env);
326 if (--env->refs > 0)
327 return;
329 if (env->key)
330 RSA_free(env->key);
332 tor_free(env);
335 /** Create a new symmetric cipher for a given key and encryption flag
336 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
337 * on failure.
339 crypto_cipher_env_t *
340 crypto_create_init_cipher(const char *key, int encrypt_mode)
342 int r;
343 crypto_cipher_env_t *crypto = NULL;
345 if (! (crypto = crypto_new_cipher_env())) {
346 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
347 return NULL;
350 if (crypto_cipher_set_key(crypto, key)) {
351 crypto_log_errors(LOG_WARN, "setting symmetric key");
352 goto error;
355 if (encrypt_mode)
356 r = crypto_cipher_encrypt_init_cipher(crypto);
357 else
358 r = crypto_cipher_decrypt_init_cipher(crypto);
360 if (r)
361 goto error;
362 return crypto;
364 error:
365 if (crypto)
366 crypto_free_cipher_env(crypto);
367 return NULL;
370 /** Allocate and return a new symmetric cipher.
372 crypto_cipher_env_t *
373 crypto_new_cipher_env(void)
375 crypto_cipher_env_t *env;
377 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
378 env->cipher = aes_new_cipher();
379 return env;
382 /** Free a symmetric cipher.
384 void
385 crypto_free_cipher_env(crypto_cipher_env_t *env)
387 tor_assert(env);
389 tor_assert(env->cipher);
390 aes_free_cipher(env->cipher);
391 memset(env, 0, sizeof(crypto_cipher_env_t));
392 tor_free(env);
395 /* public key crypto */
397 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
398 * success, -1 on failure.
401 crypto_pk_generate_key(crypto_pk_env_t *env)
403 tor_assert(env);
405 if (env->key)
406 RSA_free(env->key);
407 #if OPENSSL_VERSION_NUMBER < 0x00908000l
408 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
409 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
410 #else
411 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
413 BIGNUM *e = BN_new();
414 RSA *r = NULL;
415 if (!e)
416 goto done;
417 if (! BN_set_word(e, 65537))
418 goto done;
419 r = RSA_new();
420 if (!r)
421 goto done;
422 if (RSA_generate_key_ex(r, PK_BYTES*8, e, NULL) == -1)
423 goto done;
425 env->key = r;
426 r = NULL;
427 done:
428 if (e)
429 BN_free(e);
430 if (r)
431 RSA_free(r);
433 #endif
434 if (!env->key) {
435 crypto_log_errors(LOG_WARN, "generating RSA key");
436 return -1;
439 return 0;
442 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
443 * Return 0 on success, -1 on failure.
445 /* Used here, and used for testing. */
447 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
448 const char *s)
450 BIO *b;
452 tor_assert(env);
453 tor_assert(s);
455 /* Create a read-only memory BIO, backed by the NUL-terminated string 's' */
456 b = BIO_new_mem_buf((char*)s, -1);
458 if (env->key)
459 RSA_free(env->key);
461 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
463 BIO_free(b);
465 if (!env->key) {
466 crypto_log_errors(LOG_WARN, "Error parsing private key");
467 return -1;
469 return 0;
472 /** Read a PEM-encoded private key from the file named by
473 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
476 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
477 const char *keyfile)
479 char *contents;
480 int r;
482 /* Read the file into a string. */
483 contents = read_file_to_str(keyfile, 0, NULL);
484 if (!contents) {
485 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
486 return -1;
489 /* Try to parse it. */
490 r = crypto_pk_read_private_key_from_string(env, contents);
491 tor_free(contents);
492 if (r)
493 return -1; /* read_private_key_from_string already warned, so we don't.*/
495 /* Make sure it's valid. */
496 if (crypto_pk_check_key(env) <= 0)
497 return -1;
499 return 0;
502 /** Helper function to implement crypto_pk_write_*_key_to_string. */
503 static int
504 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
505 size_t *len, int is_public)
507 BUF_MEM *buf;
508 BIO *b;
509 int r;
511 tor_assert(env);
512 tor_assert(env->key);
513 tor_assert(dest);
515 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
517 /* Now you can treat b as if it were a file. Just use the
518 * PEM_*_bio_* functions instead of the non-bio variants.
520 if (is_public)
521 r = PEM_write_bio_RSAPublicKey(b, env->key);
522 else
523 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
525 if (!r) {
526 crypto_log_errors(LOG_WARN, "writing RSA key to string");
527 BIO_free(b);
528 return -1;
531 BIO_get_mem_ptr(b, &buf);
532 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
533 BIO_free(b);
535 *dest = tor_malloc(buf->length+1);
536 memcpy(*dest, buf->data, buf->length);
537 (*dest)[buf->length] = 0; /* nul terminate it */
538 *len = buf->length;
539 BUF_MEM_free(buf);
541 return 0;
544 /** PEM-encode the public key portion of <b>env</b> and write it to a
545 * newly allocated string. On success, set *<b>dest</b> to the new
546 * string, *<b>len</b> to the string's length, and return 0. On
547 * failure, return -1.
550 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
551 size_t *len)
553 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
556 /** PEM-encode the private key portion of <b>env</b> and write it to a
557 * newly allocated string. On success, set *<b>dest</b> to the new
558 * string, *<b>len</b> to the string's length, and return 0. On
559 * failure, return -1.
562 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
563 size_t *len)
565 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
568 /** Read a PEM-encoded public key from the first <b>len</b> characters of
569 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
570 * failure.
573 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
574 size_t len)
576 BIO *b;
578 tor_assert(env);
579 tor_assert(src);
580 tor_assert(len<INT_MAX);
582 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
584 BIO_write(b, src, (int)len);
586 if (env->key)
587 RSA_free(env->key);
588 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
589 BIO_free(b);
590 if (!env->key) {
591 crypto_log_errors(LOG_WARN, "reading public key from string");
592 return -1;
595 return 0;
598 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
599 * PEM-encoded. Return 0 on success, -1 on failure.
602 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
603 const char *fname)
605 BIO *bio;
606 char *cp;
607 long len;
608 char *s;
609 int r;
611 tor_assert(PRIVATE_KEY_OK(env));
613 if (!(bio = BIO_new(BIO_s_mem())))
614 return -1;
615 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
616 == 0) {
617 crypto_log_errors(LOG_WARN, "writing private key");
618 BIO_free(bio);
619 return -1;
621 len = BIO_get_mem_data(bio, &cp);
622 tor_assert(len >= 0);
623 s = tor_malloc(len+1);
624 memcpy(s, cp, len);
625 s[len]='\0';
626 r = write_str_to_file(fname, s, 0);
627 BIO_free(bio);
628 tor_free(s);
629 return r;
632 /** Return true iff <b>env</b> has a valid key.
635 crypto_pk_check_key(crypto_pk_env_t *env)
637 int r;
638 tor_assert(env);
640 r = RSA_check_key(env->key);
641 if (r <= 0)
642 crypto_log_errors(LOG_WARN,"checking RSA key");
643 return r;
646 /** Return true iff <b>key</b> contains the private-key portion of the RSA
647 * key. */
649 crypto_pk_key_is_private(const crypto_pk_env_t *key)
651 tor_assert(key);
652 return PRIVATE_KEY_OK(key);
655 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
656 * if a==b, and 1 if a\>b.
659 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
661 int result;
663 if (!a || !b)
664 return -1;
666 if (!a->key || !b->key)
667 return -1;
669 tor_assert(PUBLIC_KEY_OK(a));
670 tor_assert(PUBLIC_KEY_OK(b));
671 result = BN_cmp((a->key)->n, (b->key)->n);
672 if (result)
673 return result;
674 return BN_cmp((a->key)->e, (b->key)->e);
677 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
678 size_t
679 crypto_pk_keysize(crypto_pk_env_t *env)
681 tor_assert(env);
682 tor_assert(env->key);
684 return (size_t) RSA_size(env->key);
687 /** Increase the reference count of <b>env</b>, and return it.
689 crypto_pk_env_t *
690 crypto_pk_dup_key(crypto_pk_env_t *env)
692 tor_assert(env);
693 tor_assert(env->key);
695 env->refs++;
696 return env;
699 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
700 crypto_pk_env_t *
701 crypto_pk_copy_full(crypto_pk_env_t *env)
703 RSA *new_key;
704 tor_assert(env);
705 tor_assert(env->key);
707 if (PRIVATE_KEY_OK(env)) {
708 new_key = RSAPrivateKey_dup(env->key);
709 } else {
710 new_key = RSAPublicKey_dup(env->key);
713 return _crypto_new_pk_env_rsa(new_key);
716 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
717 * in <b>env</b>, using the padding method <b>padding</b>. On success,
718 * write the result to <b>to</b>, and return the number of bytes
719 * written. On failure, return -1.
722 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
723 const char *from, size_t fromlen, int padding)
725 int r;
726 tor_assert(env);
727 tor_assert(from);
728 tor_assert(to);
729 tor_assert(fromlen<INT_MAX);
731 r = RSA_public_encrypt((int)fromlen,
732 (unsigned char*)from, (unsigned char*)to,
733 env->key, crypto_get_rsa_padding(padding));
734 if (r<0) {
735 crypto_log_errors(LOG_WARN, "performing RSA encryption");
736 return -1;
738 return r;
741 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
742 * in <b>env</b>, using the padding method <b>padding</b>. On success,
743 * write the result to <b>to</b>, and return the number of bytes
744 * written. On failure, return -1.
747 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
748 const char *from, size_t fromlen,
749 int padding, int warnOnFailure)
751 int r;
752 tor_assert(env);
753 tor_assert(from);
754 tor_assert(to);
755 tor_assert(env->key);
756 tor_assert(fromlen<INT_MAX);
757 if (!env->key->p)
758 /* Not a private key */
759 return -1;
761 r = RSA_private_decrypt((int)fromlen,
762 (unsigned char*)from, (unsigned char*)to,
763 env->key, crypto_get_rsa_padding(padding));
765 if (r<0) {
766 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
767 "performing RSA decryption");
768 return -1;
770 return r;
773 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
774 * public key in <b>env</b>, using PKCS1 padding. On success, write the
775 * signed data to <b>to</b>, and return the number of bytes written.
776 * On failure, return -1.
779 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
780 const char *from, size_t fromlen)
782 int r;
783 tor_assert(env);
784 tor_assert(from);
785 tor_assert(to);
786 tor_assert(fromlen < INT_MAX);
787 r = RSA_public_decrypt((int)fromlen,
788 (unsigned char*)from, (unsigned char*)to,
789 env->key, RSA_PKCS1_PADDING);
791 if (r<0) {
792 crypto_log_errors(LOG_WARN, "checking RSA signature");
793 return -1;
795 return r;
798 /** Check a siglen-byte long signature at <b>sig</b> against
799 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
800 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
801 * SHA1(data). Else return -1.
804 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
805 size_t datalen, const char *sig, size_t siglen)
807 char digest[DIGEST_LEN];
808 char *buf;
809 int r;
811 tor_assert(env);
812 tor_assert(data);
813 tor_assert(sig);
815 if (crypto_digest(digest,data,datalen)<0) {
816 log_warn(LD_BUG, "couldn't compute digest");
817 return -1;
819 buf = tor_malloc(crypto_pk_keysize(env)+1);
820 r = crypto_pk_public_checksig(env,buf,sig,siglen);
821 if (r != DIGEST_LEN) {
822 log_warn(LD_CRYPTO, "Invalid signature");
823 tor_free(buf);
824 return -1;
826 if (memcmp(buf, digest, DIGEST_LEN)) {
827 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
828 tor_free(buf);
829 return -1;
831 tor_free(buf);
833 return 0;
836 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
837 * <b>env</b>, using PKCS1 padding. On success, write the signature to
838 * <b>to</b>, and return the number of bytes written. On failure, return
839 * -1.
842 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
843 const char *from, size_t fromlen)
845 int r;
846 tor_assert(env);
847 tor_assert(from);
848 tor_assert(to);
849 tor_assert(fromlen < INT_MAX);
850 if (!env->key->p)
851 /* Not a private key */
852 return -1;
854 r = RSA_private_encrypt((int)fromlen,
855 (unsigned char*)from, (unsigned char*)to,
856 env->key, RSA_PKCS1_PADDING);
857 if (r<0) {
858 crypto_log_errors(LOG_WARN, "generating RSA signature");
859 return -1;
861 return r;
864 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
865 * <b>from</b>; sign the data with the private key in <b>env</b>, and
866 * store it in <b>to</b>. Return the number of bytes written on
867 * success, and -1 on failure.
870 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
871 const char *from, size_t fromlen)
873 int r;
874 char digest[DIGEST_LEN];
875 if (crypto_digest(digest,from,fromlen)<0)
876 return -1;
877 r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
878 memset(digest, 0, sizeof(digest));
879 return r;
882 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
883 * bytes of data from <b>from</b>, with padding type 'padding',
884 * storing the results on <b>to</b>.
886 * If no padding is used, the public key must be at least as large as
887 * <b>from</b>.
889 * Returns the number of bytes written on success, -1 on failure.
891 * The encrypted data consists of:
892 * - The source data, padded and encrypted with the public key, if the
893 * padded source data is no longer than the public key, and <b>force</b>
894 * is false, OR
895 * - The beginning of the source data prefixed with a 16-byte symmetric key,
896 * padded and encrypted with the public key; followed by the rest of
897 * the source data encrypted in AES-CTR mode with the symmetric key.
900 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
901 char *to,
902 const char *from,
903 size_t fromlen,
904 int padding, int force)
906 int overhead, outlen, r;
907 size_t pkeylen, symlen;
908 crypto_cipher_env_t *cipher = NULL;
909 char *buf = NULL;
911 tor_assert(env);
912 tor_assert(from);
913 tor_assert(to);
915 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
916 pkeylen = crypto_pk_keysize(env);
918 if (padding == PK_NO_PADDING && fromlen < pkeylen)
919 return -1;
921 if (!force && fromlen+overhead <= pkeylen) {
922 /* It all fits in a single encrypt. */
923 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
925 cipher = crypto_new_cipher_env();
926 if (!cipher) return -1;
927 if (crypto_cipher_generate_key(cipher)<0)
928 goto err;
929 /* You can't just run around RSA-encrypting any bitstream: if it's
930 * greater than the RSA key, then OpenSSL will happily encrypt, and
931 * later decrypt to the wrong value. So we set the first bit of
932 * 'cipher->key' to 0 if we aren't padding. This means that our
933 * symmetric key is really only 127 bits.
935 if (padding == PK_NO_PADDING)
936 cipher->key[0] &= 0x7f;
937 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
938 goto err;
939 buf = tor_malloc(pkeylen+1);
940 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
941 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
943 /* Length of symmetrically encrypted data. */
944 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
946 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
947 if (outlen!=(int)pkeylen) {
948 goto err;
950 r = crypto_cipher_encrypt(cipher, to+outlen,
951 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
953 if (r<0) goto err;
954 memset(buf, 0, pkeylen);
955 tor_free(buf);
956 crypto_free_cipher_env(cipher);
957 tor_assert(outlen+symlen < INT_MAX);
958 return (int)(outlen + symlen);
959 err:
960 if (buf) {
961 memset(buf, 0, pkeylen);
962 tor_free(buf);
964 if (cipher) crypto_free_cipher_env(cipher);
965 return -1;
968 /** Invert crypto_pk_public_hybrid_encrypt. */
970 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
971 char *to,
972 const char *from,
973 size_t fromlen,
974 int padding, int warnOnFailure)
976 int outlen, r;
977 size_t pkeylen;
978 crypto_cipher_env_t *cipher = NULL;
979 char *buf = NULL;
981 pkeylen = crypto_pk_keysize(env);
983 if (fromlen <= pkeylen) {
984 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
985 warnOnFailure);
987 buf = tor_malloc(pkeylen+1);
988 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
989 warnOnFailure);
990 if (outlen<0) {
991 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
992 "Error decrypting public-key data");
993 goto err;
995 if (outlen < CIPHER_KEY_LEN) {
996 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
997 "No room for a symmetric key");
998 goto err;
1000 cipher = crypto_create_init_cipher(buf, 0);
1001 if (!cipher) {
1002 goto err;
1004 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1005 outlen -= CIPHER_KEY_LEN;
1006 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1007 if (r<0)
1008 goto err;
1009 memset(buf,0,pkeylen);
1010 tor_free(buf);
1011 crypto_free_cipher_env(cipher);
1012 tor_assert(outlen + fromlen < INT_MAX);
1013 return (int)(outlen + (fromlen-pkeylen));
1014 err:
1015 memset(buf,0,pkeylen);
1016 tor_free(buf);
1017 if (cipher) crypto_free_cipher_env(cipher);
1018 return -1;
1021 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1022 * Return -1 on error, or the number of characters used on success.
1025 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1027 int len;
1028 unsigned char *buf, *cp;
1029 len = i2d_RSAPublicKey(pk->key, NULL);
1030 if (len < 0 || (size_t)len > dest_len)
1031 return -1;
1032 cp = buf = tor_malloc(len+1);
1033 len = i2d_RSAPublicKey(pk->key, &cp);
1034 if (len < 0) {
1035 crypto_log_errors(LOG_WARN,"encoding public key");
1036 tor_free(buf);
1037 return -1;
1039 /* We don't encode directly into 'dest', because that would be illegal
1040 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1042 memcpy(dest,buf,len);
1043 tor_free(buf);
1044 return len;
1047 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1048 * success and NULL on failure.
1050 crypto_pk_env_t *
1051 crypto_pk_asn1_decode(const char *str, size_t len)
1053 RSA *rsa;
1054 unsigned char *buf;
1055 /* This ifdef suppresses a type warning. Take out the first case once
1056 * everybody is using OpenSSL 0.9.7 or later.
1058 const unsigned char *cp;
1059 cp = buf = tor_malloc(len);
1060 memcpy(buf,str,len);
1061 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1062 tor_free(buf);
1063 if (!rsa) {
1064 crypto_log_errors(LOG_WARN,"decoding public key");
1065 return NULL;
1067 return _crypto_new_pk_env_rsa(rsa);
1070 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1071 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1072 * Return 0 on success, -1 on failure.
1075 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1077 unsigned char *buf, *bufp;
1078 int len;
1080 len = i2d_RSAPublicKey(pk->key, NULL);
1081 if (len < 0)
1082 return -1;
1083 buf = bufp = tor_malloc(len+1);
1084 len = i2d_RSAPublicKey(pk->key, &bufp);
1085 if (len < 0) {
1086 crypto_log_errors(LOG_WARN,"encoding public key");
1087 tor_free(buf);
1088 return -1;
1090 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1091 tor_free(buf);
1092 return -1;
1094 tor_free(buf);
1095 return 0;
1098 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1099 * every four spaces. */
1100 /* static */ void
1101 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1103 int n = 0;
1104 char *end = out+outlen;
1105 while (*in && out<end) {
1106 *out++ = *in++;
1107 if (++n == 4 && *in && out<end) {
1108 n = 0;
1109 *out++ = ' ';
1112 tor_assert(out<end);
1113 *out = '\0';
1116 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1117 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1118 * space). Return 0 on success, -1 on failure.
1120 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1121 * of the public key, converted to hexadecimal, in upper case, with a
1122 * space after every four digits.
1124 * If <b>add_space</b> is false, omit the spaces.
1127 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1129 char digest[DIGEST_LEN];
1130 char hexdigest[HEX_DIGEST_LEN+1];
1131 if (crypto_pk_get_digest(pk, digest)) {
1132 return -1;
1134 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1135 if (add_space) {
1136 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1137 } else {
1138 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1140 return 0;
1143 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1146 crypto_pk_check_fingerprint_syntax(const char *s)
1148 int i;
1149 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1150 if ((i%5) == 4) {
1151 if (!TOR_ISSPACE(s[i])) return 0;
1152 } else {
1153 if (!TOR_ISXDIGIT(s[i])) return 0;
1156 if (s[FINGERPRINT_LEN]) return 0;
1157 return 1;
1160 /* symmetric crypto */
1162 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1163 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1166 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1168 tor_assert(env);
1170 return crypto_rand(env->key, CIPHER_KEY_LEN);
1173 /** Set the symmetric key for the cipher in <b>env</b> to the first
1174 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1175 * Return 0 on success, -1 on failure.
1178 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1180 tor_assert(env);
1181 tor_assert(key);
1183 if (!env->key)
1184 return -1;
1186 memcpy(env->key, key, CIPHER_KEY_LEN);
1187 return 0;
1190 /** Generate an initialization vector for our AES-CTR cipher; store it
1191 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1192 void
1193 crypto_cipher_generate_iv(char *iv_out)
1195 crypto_rand(iv_out, CIPHER_IV_LEN);
1198 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1199 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1200 * <b>iv</b>. */
1202 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1204 tor_assert(env);
1205 tor_assert(iv);
1206 aes_set_iv(env->cipher, iv);
1207 return 0;
1210 /** Return a pointer to the key set for the cipher in <b>env</b>.
1212 const char *
1213 crypto_cipher_get_key(crypto_cipher_env_t *env)
1215 return env->key;
1218 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1219 * success, -1 on failure.
1222 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1224 tor_assert(env);
1226 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1227 return 0;
1230 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1231 * success, -1 on failure.
1234 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1236 tor_assert(env);
1238 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1239 return 0;
1242 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1243 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1244 * On failure, return -1.
1247 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1248 const char *from, size_t fromlen)
1250 tor_assert(env);
1251 tor_assert(env->cipher);
1252 tor_assert(from);
1253 tor_assert(fromlen);
1254 tor_assert(to);
1256 aes_crypt(env->cipher, from, fromlen, to);
1257 return 0;
1260 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1261 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1262 * On failure, return -1.
1265 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1266 const char *from, size_t fromlen)
1268 tor_assert(env);
1269 tor_assert(from);
1270 tor_assert(to);
1272 aes_crypt(env->cipher, from, fromlen, to);
1273 return 0;
1276 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1277 * on success, return 0. On failure, return -1.
1280 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1282 aes_crypt_inplace(env->cipher, buf, len);
1283 return 0;
1286 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1287 * <b>cipher</b> to the buffer in <b>to</b> of length
1288 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1289 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1290 * number of bytes written, on failure, return -1.
1292 * This function adjusts the current position of the counter in <b>cipher</b>
1293 * to immediately after the encrypted data.
1296 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1297 char *to, size_t tolen,
1298 const char *from, size_t fromlen)
1300 tor_assert(cipher);
1301 tor_assert(from);
1302 tor_assert(to);
1303 tor_assert(fromlen < INT_MAX);
1305 if (fromlen < 1)
1306 return -1;
1307 if (tolen < fromlen + CIPHER_IV_LEN)
1308 return -1;
1310 crypto_cipher_generate_iv(to);
1311 if (crypto_cipher_set_iv(cipher, to)<0)
1312 return -1;
1313 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1314 return (int)(fromlen + CIPHER_IV_LEN);
1317 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1318 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1319 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1320 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1321 * number of bytes written, on failure, return -1.
1323 * This function adjusts the current position of the counter in <b>cipher</b>
1324 * to immediately after the decrypted data.
1327 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1328 char *to, size_t tolen,
1329 const char *from, size_t fromlen)
1331 tor_assert(cipher);
1332 tor_assert(from);
1333 tor_assert(to);
1334 tor_assert(fromlen < INT_MAX);
1336 if (fromlen <= CIPHER_IV_LEN)
1337 return -1;
1338 if (tolen < fromlen - CIPHER_IV_LEN)
1339 return -1;
1341 if (crypto_cipher_set_iv(cipher, from)<0)
1342 return -1;
1343 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1344 return (int)(fromlen - CIPHER_IV_LEN);
1347 /* SHA-1 */
1349 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1350 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1351 * Return 0 on success, -1 on failure.
1354 crypto_digest(char *digest, const char *m, size_t len)
1356 tor_assert(m);
1357 tor_assert(digest);
1358 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1361 /** Intermediate information about the digest of a stream of data. */
1362 struct crypto_digest_env_t {
1363 SHA_CTX d;
1366 /** Allocate and return a new digest object.
1368 crypto_digest_env_t *
1369 crypto_new_digest_env(void)
1371 crypto_digest_env_t *r;
1372 r = tor_malloc(sizeof(crypto_digest_env_t));
1373 SHA1_Init(&r->d);
1374 return r;
1377 /** Deallocate a digest object.
1379 void
1380 crypto_free_digest_env(crypto_digest_env_t *digest)
1382 memset(digest, 0, sizeof(crypto_digest_env_t));
1383 tor_free(digest);
1386 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1388 void
1389 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1390 size_t len)
1392 tor_assert(digest);
1393 tor_assert(data);
1394 /* Using the SHA1_*() calls directly means we don't support doing
1395 * SHA1 in hardware. But so far the delay of getting the question
1396 * to the hardware, and hearing the answer, is likely higher than
1397 * just doing it ourselves. Hashes are fast.
1399 SHA1_Update(&digest->d, (void*)data, len);
1402 /** Compute the hash of the data that has been passed to the digest
1403 * object; write the first out_len bytes of the result to <b>out</b>.
1404 * <b>out_len</b> must be \<= DIGEST_LEN.
1406 void
1407 crypto_digest_get_digest(crypto_digest_env_t *digest,
1408 char *out, size_t out_len)
1410 unsigned char r[DIGEST_LEN];
1411 SHA_CTX tmpctx;
1412 tor_assert(digest);
1413 tor_assert(out);
1414 tor_assert(out_len <= DIGEST_LEN);
1415 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1416 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1417 SHA1_Final(r, &tmpctx);
1418 memcpy(out, r, out_len);
1419 memset(r, 0, sizeof(r));
1422 /** Allocate and return a new digest object with the same state as
1423 * <b>digest</b>
1425 crypto_digest_env_t *
1426 crypto_digest_dup(const crypto_digest_env_t *digest)
1428 crypto_digest_env_t *r;
1429 tor_assert(digest);
1430 r = tor_malloc(sizeof(crypto_digest_env_t));
1431 memcpy(r,digest,sizeof(crypto_digest_env_t));
1432 return r;
1435 /** Replace the state of the digest object <b>into</b> with the state
1436 * of the digest object <b>from</b>.
1438 void
1439 crypto_digest_assign(crypto_digest_env_t *into,
1440 const crypto_digest_env_t *from)
1442 tor_assert(into);
1443 tor_assert(from);
1444 memcpy(into,from,sizeof(crypto_digest_env_t));
1447 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1448 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1449 * in <b>hmac_out</b>.
1451 void
1452 crypto_hmac_sha1(char *hmac_out,
1453 const char *key, size_t key_len,
1454 const char *msg, size_t msg_len)
1456 tor_assert(key_len < INT_MAX);
1457 tor_assert(msg_len < INT_MAX);
1458 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1459 (unsigned char*)hmac_out, NULL);
1462 /* DH */
1464 /** Shared P parameter for our DH key exchanged. */
1465 static BIGNUM *dh_param_p = NULL;
1466 /** Shared G parameter for our DH key exchanges. */
1467 static BIGNUM *dh_param_g = NULL;
1469 /** Initialize dh_param_p and dh_param_g if they are not already
1470 * set. */
1471 static void
1472 init_dh_param(void)
1474 BIGNUM *p, *g;
1475 int r;
1476 if (dh_param_p && dh_param_g)
1477 return;
1479 p = BN_new();
1480 g = BN_new();
1481 tor_assert(p);
1482 tor_assert(g);
1484 /* This is from rfc2409, section 6.2. It's a safe prime, and
1485 supposedly it equals:
1486 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1488 r = BN_hex2bn(&p,
1489 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1490 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1491 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1492 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1493 "49286651ECE65381FFFFFFFFFFFFFFFF");
1494 tor_assert(r);
1496 r = BN_set_word(g, 2);
1497 tor_assert(r);
1498 dh_param_p = p;
1499 dh_param_g = g;
1502 #define DH_PRIVATE_KEY_BITS 320
1504 /** Allocate and return a new DH object for a key exchange.
1506 crypto_dh_env_t *
1507 crypto_dh_new(void)
1509 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1511 if (!dh_param_p)
1512 init_dh_param();
1514 if (!(res->dh = DH_new()))
1515 goto err;
1517 if (!(res->dh->p = BN_dup(dh_param_p)))
1518 goto err;
1520 if (!(res->dh->g = BN_dup(dh_param_g)))
1521 goto err;
1523 res->dh->length = DH_PRIVATE_KEY_BITS;
1525 return res;
1526 err:
1527 crypto_log_errors(LOG_WARN, "creating DH object");
1528 if (res->dh) DH_free(res->dh); /* frees p and g too */
1529 tor_free(res);
1530 return NULL;
1533 /** Return the length of the DH key in <b>dh</b>, in bytes.
1536 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1538 tor_assert(dh);
1539 return DH_size(dh->dh);
1542 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1543 * success, -1 on failure.
1546 crypto_dh_generate_public(crypto_dh_env_t *dh)
1548 again:
1549 if (!DH_generate_key(dh->dh)) {
1550 crypto_log_errors(LOG_WARN, "generating DH key");
1551 return -1;
1553 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1554 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1555 "the-universe chances really do happen. Trying again.");
1556 /* Free and clear the keys, so OpenSSL will actually try again. */
1557 BN_free(dh->dh->pub_key);
1558 BN_free(dh->dh->priv_key);
1559 dh->dh->pub_key = dh->dh->priv_key = NULL;
1560 goto again;
1562 return 0;
1565 /** Generate g^x as necessary, and write the g^x for the key exchange
1566 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1567 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1570 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1572 int bytes;
1573 tor_assert(dh);
1574 if (!dh->dh->pub_key) {
1575 if (crypto_dh_generate_public(dh)<0)
1576 return -1;
1579 tor_assert(dh->dh->pub_key);
1580 bytes = BN_num_bytes(dh->dh->pub_key);
1581 tor_assert(bytes >= 0);
1582 if (pubkey_len < (size_t)bytes) {
1583 log_warn(LD_CRYPTO,
1584 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1585 (int) pubkey_len, bytes);
1586 return -1;
1589 memset(pubkey, 0, pubkey_len);
1590 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1592 return 0;
1595 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1596 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1597 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1599 static int
1600 tor_check_dh_key(BIGNUM *bn)
1602 BIGNUM *x;
1603 char *s;
1604 tor_assert(bn);
1605 x = BN_new();
1606 tor_assert(x);
1607 if (!dh_param_p)
1608 init_dh_param();
1609 BN_set_word(x, 1);
1610 if (BN_cmp(bn,x)<=0) {
1611 log_warn(LD_CRYPTO, "DH key must be at least 2.");
1612 goto err;
1614 BN_copy(x,dh_param_p);
1615 BN_sub_word(x, 1);
1616 if (BN_cmp(bn,x)>=0) {
1617 log_warn(LD_CRYPTO, "DH key must be at most p-2.");
1618 goto err;
1620 BN_free(x);
1621 return 0;
1622 err:
1623 BN_free(x);
1624 s = BN_bn2hex(bn);
1625 log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1626 OPENSSL_free(s);
1627 return -1;
1630 #undef MIN
1631 #define MIN(a,b) ((a)<(b)?(a):(b))
1632 /** Given a DH key exchange object, and our peer's value of g^y (as a
1633 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1634 * <b>secret_bytes_out</b> bytes of shared key material and write them
1635 * to <b>secret_out</b>. Return the number of bytes generated on success,
1636 * or -1 on failure.
1638 * (We generate key material by computing
1639 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1640 * where || is concatenation.)
1642 ssize_t
1643 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1644 const char *pubkey, size_t pubkey_len,
1645 char *secret_out, size_t secret_bytes_out)
1647 char *secret_tmp = NULL;
1648 BIGNUM *pubkey_bn = NULL;
1649 size_t secret_len=0;
1650 int result=0;
1651 tor_assert(dh);
1652 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1653 tor_assert(pubkey_len < INT_MAX);
1655 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1656 (int)pubkey_len, NULL)))
1657 goto error;
1658 if (tor_check_dh_key(pubkey_bn)<0) {
1659 /* Check for invalid public keys. */
1660 log_warn(LD_CRYPTO,"Rejected invalid g^x");
1661 goto error;
1663 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1664 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1665 if (result < 0) {
1666 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1667 goto error;
1669 secret_len = result;
1670 if (crypto_expand_key_material(secret_tmp, secret_len,
1671 secret_out, secret_bytes_out)<0)
1672 goto error;
1673 secret_len = secret_bytes_out;
1675 goto done;
1676 error:
1677 result = -1;
1678 done:
1679 crypto_log_errors(LOG_WARN, "completing DH handshake");
1680 if (pubkey_bn)
1681 BN_free(pubkey_bn);
1682 tor_free(secret_tmp);
1683 if (result < 0)
1684 return result;
1685 else
1686 return secret_len;
1689 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1690 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1691 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1692 * H(K | [00]) | H(K | [01]) | ....
1694 * Return 0 on success, -1 on failure.
1697 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1698 char *key_out, size_t key_out_len)
1700 int i;
1701 char *cp, *tmp = tor_malloc(key_in_len+1);
1702 char digest[DIGEST_LEN];
1704 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1705 tor_assert(key_out_len <= DIGEST_LEN*256);
1707 memcpy(tmp, key_in, key_in_len);
1708 for (cp = key_out, i=0; cp < key_out+key_out_len;
1709 ++i, cp += DIGEST_LEN) {
1710 tmp[key_in_len] = i;
1711 if (crypto_digest(digest, tmp, key_in_len+1))
1712 goto err;
1713 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1715 memset(tmp, 0, key_in_len+1);
1716 tor_free(tmp);
1717 memset(digest, 0, sizeof(digest));
1718 return 0;
1720 err:
1721 memset(tmp, 0, key_in_len+1);
1722 tor_free(tmp);
1723 memset(digest, 0, sizeof(digest));
1724 return -1;
1727 /** Free a DH key exchange object.
1729 void
1730 crypto_dh_free(crypto_dh_env_t *dh)
1732 tor_assert(dh);
1733 tor_assert(dh->dh);
1734 DH_free(dh->dh);
1735 tor_free(dh);
1738 /* random numbers */
1740 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1741 * work for us too. */
1742 #define ADD_ENTROPY 32
1744 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1745 "release".) */
1746 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1748 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1749 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1750 * that fd without checking whether it fit in the fd_set. Thus, if the
1751 * system has not just been started up, it is unsafe to call */
1752 #define RAND_POLL_IS_SAFE \
1753 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1754 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1755 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1757 /** Seed OpenSSL's random number generator with bytes from the operating
1758 * system. <b>startup</b> should be true iff we have just started Tor and
1759 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1762 crypto_seed_rng(int startup)
1764 char buf[ADD_ENTROPY];
1765 int rand_poll_status = 0;
1767 /* local variables */
1768 #ifdef MS_WINDOWS
1769 static int provider_set = 0;
1770 static HCRYPTPROV provider;
1771 #else
1772 static const char *filenames[] = {
1773 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1775 int fd, i;
1776 size_t n;
1777 #endif
1779 #if HAVE_RAND_POLL
1780 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1781 * entropy than we do. We'll try calling that, *and* calling our own entropy
1782 * functions. If one succeeds, we'll accept the RNG as seeded. */
1783 if (startup || RAND_POLL_IS_SAFE) {
1784 rand_poll_status = RAND_poll();
1785 if (rand_poll_status == 0)
1786 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1788 #endif
1790 #ifdef MS_WINDOWS
1791 if (!provider_set) {
1792 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1793 CRYPT_VERIFYCONTEXT)) {
1794 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1795 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1796 return rand_poll_status ? 0 : -1;
1799 provider_set = 1;
1801 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1802 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1803 return rand_poll_status ? 0 : -1;
1805 RAND_seed(buf, sizeof(buf));
1806 memset(buf, 0, sizeof(buf));
1807 return 0;
1808 #else
1809 for (i = 0; filenames[i]; ++i) {
1810 fd = open(filenames[i], O_RDONLY, 0);
1811 if (fd<0) continue;
1812 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1813 n = read_all(fd, buf, sizeof(buf), 0);
1814 close(fd);
1815 if (n != sizeof(buf)) {
1816 log_warn(LD_CRYPTO,
1817 "Error reading from entropy source (read only %lu bytes).",
1818 (unsigned long)n);
1819 return -1;
1821 RAND_seed(buf, (int)sizeof(buf));
1822 memset(buf, 0, sizeof(buf));
1823 return 0;
1826 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1827 return rand_poll_status ? 0 : -1;
1828 #endif
1831 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1832 * success, -1 on failure.
1835 crypto_rand(char *to, size_t n)
1837 int r;
1838 tor_assert(n < INT_MAX);
1839 tor_assert(to);
1840 r = RAND_bytes((unsigned char*)to, (int)n);
1841 if (r == 0)
1842 crypto_log_errors(LOG_WARN, "generating random data");
1843 return (r == 1) ? 0 : -1;
1846 /** Return a pseudorandom integer, chosen uniformly from the values
1847 * between 0 and <b>max</b>-1. */
1849 crypto_rand_int(unsigned int max)
1851 unsigned int val;
1852 unsigned int cutoff;
1853 tor_assert(max < UINT_MAX);
1854 tor_assert(max > 0); /* don't div by 0 */
1856 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1857 * distribution with clipping at the upper end of unsigned int's
1858 * range.
1860 cutoff = UINT_MAX - (UINT_MAX%max);
1861 while (1) {
1862 crypto_rand((char*)&val, sizeof(val));
1863 if (val < cutoff)
1864 return val % max;
1868 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1869 * between 0 and <b>max</b>-1. */
1870 uint64_t
1871 crypto_rand_uint64(uint64_t max)
1873 uint64_t val;
1874 uint64_t cutoff;
1875 tor_assert(max < UINT64_MAX);
1876 tor_assert(max > 0); /* don't div by 0 */
1878 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1879 * distribution with clipping at the upper end of unsigned int's
1880 * range.
1882 cutoff = UINT64_MAX - (UINT64_MAX%max);
1883 while (1) {
1884 crypto_rand((char*)&val, sizeof(val));
1885 if (val < cutoff)
1886 return val % max;
1890 /** Generate and return a new random hostname starting with <b>prefix</b>,
1891 * ending with <b>suffix</b>, and containing no less than
1892 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1893 * characters between. */
1894 char *
1895 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
1896 const char *suffix)
1898 char *result, *rand_bytes;
1899 int randlen, rand_bytes_len;
1900 size_t resultlen, prefixlen;
1902 tor_assert(max_rand_len >= min_rand_len);
1903 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
1904 prefixlen = strlen(prefix);
1905 resultlen = prefixlen + strlen(suffix) + randlen + 16;
1907 rand_bytes_len = ((randlen*5)+7)/8;
1908 if (rand_bytes_len % 5)
1909 rand_bytes_len += 5 - (rand_bytes_len%5);
1910 rand_bytes = tor_malloc(rand_bytes_len);
1911 crypto_rand(rand_bytes, rand_bytes_len);
1913 result = tor_malloc(resultlen);
1914 memcpy(result, prefix, prefixlen);
1915 base32_encode(result+prefixlen, resultlen-prefixlen,
1916 rand_bytes, rand_bytes_len);
1917 tor_free(rand_bytes);
1918 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
1920 return result;
1923 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1924 * is empty. */
1925 void *
1926 smartlist_choose(const smartlist_t *sl)
1928 int len = smartlist_len(sl);
1929 if (len)
1930 return smartlist_get(sl,crypto_rand_int(len));
1931 return NULL; /* no elements to choose from */
1934 /** Scramble the elements of <b>sl</b> into a random order. */
1935 void
1936 smartlist_shuffle(smartlist_t *sl)
1938 int i;
1939 /* From the end of the list to the front, choose at random from the
1940 positions we haven't looked at yet, and swap that position into the
1941 current position. Remember to give "no swap" the same probability as
1942 any other swap. */
1943 for (i = smartlist_len(sl)-1; i > 0; --i) {
1944 int j = crypto_rand_int(i+1);
1945 smartlist_swap(sl, i, j);
1949 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1950 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1951 * bytes. Return the number of bytes written on success; -1 if
1952 * destlen is too short, or other failure.
1955 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1957 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1958 * it ever shows up in the profile. */
1959 EVP_ENCODE_CTX ctx;
1960 int len, ret;
1961 tor_assert(srclen < INT_MAX);
1963 /* 48 bytes of input -> 64 bytes of output plus newline.
1964 Plus one more byte, in case I'm wrong.
1966 if (destlen < ((srclen/48)+1)*66)
1967 return -1;
1968 if (destlen > SIZE_T_CEILING)
1969 return -1;
1971 EVP_EncodeInit(&ctx);
1972 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
1973 (unsigned char*)src, (int)srclen);
1974 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1975 ret += len;
1976 return ret;
1979 #define X 255
1980 #define SP 64
1981 #define PAD 65
1982 /** Internal table mapping byte values to what they represent in base64.
1983 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
1984 * skipped. Xs are invalid and must not appear in base64. PAD indicates
1985 * end-of-string. */
1986 static const uint8_t base64_decode_table[256] = {
1987 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
1988 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
1989 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
1990 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
1991 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1992 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
1993 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1994 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
1995 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
1996 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
1997 X, X, X, X, X, X, X, X, X, X, X, 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,
2005 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2006 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2007 * bytes. Return the number of bytes written on success; -1 if
2008 * destlen is too short, or other failure.
2010 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2011 * spaces or padding.
2013 * NOTE 2: This implementation does not check for the correct number of
2014 * padding "=" characters at the end of the string, and does not check
2015 * for internal padding characters.
2018 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2020 #ifdef USE_OPENSSL_BASE64
2021 EVP_ENCODE_CTX ctx;
2022 int len, ret;
2023 /* 64 bytes of input -> *up to* 48 bytes of output.
2024 Plus one more byte, in case I'm wrong.
2026 if (destlen < ((srclen/64)+1)*49)
2027 return -1;
2028 if (destlen > SIZE_T_CEILING)
2029 return -1;
2031 EVP_DecodeInit(&ctx);
2032 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2033 (unsigned char*)src, srclen);
2034 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2035 ret += len;
2036 return ret;
2037 #else
2038 const char *eos = src+srclen;
2039 uint32_t n=0;
2040 int n_idx=0;
2041 char *dest_orig = dest;
2043 /* Max number of bits == srclen*6.
2044 * Number of bytes required to hold all bits == (srclen*6)/8.
2045 * Yes, we want to round down: anything that hangs over the end of a
2046 * byte is padding. */
2047 if (destlen < (srclen*3)/4)
2048 return -1;
2049 if (destlen > SIZE_T_CEILING)
2050 return -1;
2052 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2053 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2054 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2056 for ( ; src < eos; ++src) {
2057 unsigned char c = (unsigned char) *src;
2058 uint8_t v = base64_decode_table[c];
2059 switch (v) {
2060 case X:
2061 /* This character isn't allowed in base64. */
2062 return -1;
2063 case SP:
2064 /* This character is whitespace, and has no effect. */
2065 continue;
2066 case PAD:
2067 /* We've hit an = character: the data is over. */
2068 goto end_of_loop;
2069 default:
2070 /* We have an actual 6-bit value. Append it to the bits in n. */
2071 n = (n<<6) | v;
2072 if ((++n_idx) == 4) {
2073 /* We've accumulated 24 bits in n. Flush them. */
2074 *dest++ = (n>>16);
2075 *dest++ = (n>>8) & 0xff;
2076 *dest++ = (n) & 0xff;
2077 n_idx = 0;
2078 n = 0;
2082 end_of_loop:
2083 /* If we have leftover bits, we need to cope. */
2084 switch (n_idx) {
2085 case 0:
2086 default:
2087 /* No leftover bits. We win. */
2088 break;
2089 case 1:
2090 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2091 return -1;
2092 case 2:
2093 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2094 *dest++ = n >> 4;
2095 break;
2096 case 3:
2097 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2098 *dest++ = n >> 10;
2099 *dest++ = n >> 2;
2102 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2103 tor_assert((dest-dest_orig) <= INT_MAX);
2105 return (int)(dest-dest_orig);
2106 #endif
2108 #undef X
2109 #undef SP
2110 #undef PAD
2112 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2113 * and newline characters, and store the nul-terminated result in the first
2114 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2116 digest_to_base64(char *d64, const char *digest)
2118 char buf[256];
2119 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2120 buf[BASE64_DIGEST_LEN] = '\0';
2121 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2122 return 0;
2125 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2126 * trailing newline or = characters), decode it and store the result in the
2127 * first DIGEST_LEN bytes at <b>digest</b>. */
2129 digest_from_base64(char *digest, const char *d64)
2131 #ifdef USE_OPENSSL_BASE64
2132 char buf_in[BASE64_DIGEST_LEN+3];
2133 char buf[256];
2134 if (strlen(d64) != BASE64_DIGEST_LEN)
2135 return -1;
2136 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2137 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2138 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2139 return -1;
2140 memcpy(digest, buf, DIGEST_LEN);
2141 return 0;
2142 #else
2143 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2144 return 0;
2145 else
2146 return -1;
2147 #endif
2150 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2151 * that srclen*8 is a multiple of 5.
2153 void
2154 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2156 unsigned int i, bit, v, u;
2157 size_t nbits = srclen * 8;
2159 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2160 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2161 tor_assert(destlen < SIZE_T_CEILING);
2163 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2164 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2165 v = ((uint8_t)src[bit/8]) << 8;
2166 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2167 /* set u to the 5-bit value at the bit'th bit of src. */
2168 u = (v >> (11-(bit%8))) & 0x1F;
2169 dest[i] = BASE32_CHARS[u];
2171 dest[i] = '\0';
2174 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2175 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2178 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2180 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2181 * it ever shows up in the profile. */
2182 unsigned int i, j, bit;
2183 size_t nbits;
2184 char *tmp;
2185 nbits = srclen * 5;
2187 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2188 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2189 tor_assert(destlen < SIZE_T_CEILING);
2191 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2192 tmp = tor_malloc_zero(srclen);
2193 for (j = 0; j < srclen; ++j) {
2194 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2195 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2196 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2197 else {
2198 log_warn(LD_BUG, "illegal character in base32 encoded string");
2199 tor_free(tmp);
2200 return -1;
2204 /* Assemble result byte-wise by applying five possible cases. */
2205 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2206 switch (bit % 40) {
2207 case 0:
2208 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2209 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2210 break;
2211 case 8:
2212 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2213 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2214 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2215 break;
2216 case 16:
2217 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2218 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2219 break;
2220 case 24:
2221 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2222 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2223 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2224 break;
2225 case 32:
2226 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2227 ((uint8_t)tmp[(bit/5)+1]);
2228 break;
2232 memset(tmp, 0, srclen);
2233 tor_free(tmp);
2234 tmp = NULL;
2235 return 0;
2238 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2239 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2240 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2241 * are a salt; the 9th byte describes how much iteration to do.
2242 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2244 void
2245 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2246 size_t secret_len, const char *s2k_specifier)
2248 crypto_digest_env_t *d;
2249 uint8_t c;
2250 size_t count, tmplen;
2251 char *tmp;
2252 tor_assert(key_out_len < SIZE_T_CEILING);
2254 #define EXPBIAS 6
2255 c = s2k_specifier[8];
2256 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2257 #undef EXPBIAS
2259 tor_assert(key_out_len <= DIGEST_LEN);
2261 d = crypto_new_digest_env();
2262 tmplen = 8+secret_len;
2263 tmp = tor_malloc(tmplen);
2264 memcpy(tmp,s2k_specifier,8);
2265 memcpy(tmp+8,secret,secret_len);
2266 secret_len += 8;
2267 while (count) {
2268 if (count >= secret_len) {
2269 crypto_digest_add_bytes(d, tmp, secret_len);
2270 count -= secret_len;
2271 } else {
2272 crypto_digest_add_bytes(d, tmp, count);
2273 count = 0;
2276 crypto_digest_get_digest(d, key_out, key_out_len);
2277 memset(tmp, 0, tmplen);
2278 tor_free(tmp);
2279 crypto_free_digest_env(d);
2282 #ifdef TOR_IS_MULTITHREADED
2283 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2284 static void
2285 _openssl_locking_cb(int mode, int n, const char *file, int line)
2287 (void)file;
2288 (void)line;
2289 if (!_openssl_mutexes)
2290 /* This is not a really good fix for the
2291 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2292 * it can't hurt. */
2293 return;
2294 if (mode & CRYPTO_LOCK)
2295 tor_mutex_acquire(_openssl_mutexes[n]);
2296 else
2297 tor_mutex_release(_openssl_mutexes[n]);
2300 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2301 * as a lock. */
2302 struct CRYPTO_dynlock_value {
2303 tor_mutex_t *lock;
2306 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2307 * documentation in OpenSSL's docs for more info. */
2308 static struct CRYPTO_dynlock_value *
2309 _openssl_dynlock_create_cb(const char *file, int line)
2311 struct CRYPTO_dynlock_value *v;
2312 (void)file;
2313 (void)line;
2314 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2315 v->lock = tor_mutex_new();
2316 return v;
2319 /** OpenSSL callback function to acquire or release a lock: see
2320 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2321 static void
2322 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2323 const char *file, int line)
2325 (void)file;
2326 (void)line;
2327 if (mode & CRYPTO_LOCK)
2328 tor_mutex_acquire(v->lock);
2329 else
2330 tor_mutex_release(v->lock);
2333 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2334 * documentation in OpenSSL's docs for more info. */
2335 static void
2336 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2337 const char *file, int line)
2339 (void)file;
2340 (void)line;
2341 tor_mutex_free(v->lock);
2342 tor_free(v);
2345 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2346 * multithreaded. */
2347 static int
2348 setup_openssl_threading(void)
2350 int i;
2351 int n = CRYPTO_num_locks();
2352 _n_openssl_mutexes = n;
2353 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2354 for (i=0; i < n; ++i)
2355 _openssl_mutexes[i] = tor_mutex_new();
2356 CRYPTO_set_locking_callback(_openssl_locking_cb);
2357 CRYPTO_set_id_callback(tor_get_thread_id);
2358 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2359 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2360 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2361 return 0;
2363 #else
2364 static int
2365 setup_openssl_threading(void)
2367 return 0;
2369 #endif