Introduce the DynamicPrimes configuration option.
[tor.git] / src / common / crypto.c
blob790ea1646cc73a0d3339d3921c828e726f9b92a1
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-2011, 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 #ifndef WIN32_WINNT
17 #define WIN32_WINNT 0x400
18 #endif
19 #ifndef _WIN32_WINNT
20 #define _WIN32_WINNT 0x400
21 #endif
22 #define WIN32_LEAN_AND_MEAN
23 #include <windows.h>
24 #include <wincrypt.h>
25 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
26 * use either definition. */
27 #undef OCSP_RESPONSE
28 #endif
30 #include <openssl/err.h>
31 #include <openssl/rsa.h>
32 #include <openssl/pem.h>
33 #include <openssl/evp.h>
34 #include <openssl/engine.h>
35 #include <openssl/rand.h>
36 #include <openssl/opensslv.h>
37 #include <openssl/bn.h>
38 #include <openssl/dh.h>
39 #include <openssl/conf.h>
40 #include <openssl/hmac.h>
42 #ifdef HAVE_CTYPE_H
43 #include <ctype.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef HAVE_SYS_FCNTL_H
52 #include <sys/fcntl.h>
53 #endif
55 #define CRYPTO_PRIVATE
56 #include "crypto.h"
57 #include "../common/torlog.h"
58 #include "aes.h"
59 #include "../common/util.h"
60 #include "container.h"
61 #include "compat.h"
63 #if OPENSSL_VERSION_NUMBER < 0x00907000l
64 #error "We require OpenSSL >= 0.9.7"
65 #endif
67 #ifdef ANDROID
68 /* Android's OpenSSL seems to have removed all of its Engine support. */
69 #define DISABLE_ENGINES
70 #endif
72 #if OPENSSL_VERSION_NUMBER < 0x00908000l
73 /** @{ */
74 /** On OpenSSL versions before 0.9.8, there is no working SHA256
75 * implementation, so we use Tom St Denis's nice speedy one, slightly adapted
76 * to our needs. These macros make it usable by us. */
77 #define SHA256_CTX sha256_state
78 #define SHA256_Init sha256_init
79 #define SHA256_Update sha256_process
80 #define LTC_ARGCHK(x) tor_assert(x)
81 /** @} */
82 #include "sha256.c"
83 #define SHA256_Final(a,b) sha256_done(b,a)
85 static unsigned char *
86 SHA256(const unsigned char *m, size_t len, unsigned char *d)
88 SHA256_CTX ctx;
89 SHA256_Init(&ctx);
90 SHA256_Update(&ctx, m, len);
91 SHA256_Final(d, &ctx);
92 return d;
94 #endif
96 /** Macro: is k a valid RSA public or private key? */
97 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
98 /** Macro: is k a valid RSA private key? */
99 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
101 #ifdef TOR_IS_MULTITHREADED
102 /** A number of preallocated mutexes for use by OpenSSL. */
103 static tor_mutex_t **_openssl_mutexes = NULL;
104 /** How many mutexes have we allocated for use by OpenSSL? */
105 static int _n_openssl_mutexes = 0;
106 #endif
108 /** A public key, or a public/private key-pair. */
109 struct crypto_pk_env_t
111 int refs; /**< reference count, so we don't have to copy keys */
112 RSA *key; /**< The key itself */
115 /** Key and stream information for a stream cipher. */
116 struct crypto_cipher_env_t
118 char key[CIPHER_KEY_LEN]; /**< The raw key. */
119 aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
120 * encryption */
123 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
124 * while we're waiting for the second.*/
125 struct crypto_dh_env_t {
126 DH *dh; /**< The openssl DH object */
129 static int setup_openssl_threading(void);
130 static int tor_check_dh_key(int severity, BIGNUM *bn);
132 /** Return the number of bytes added by padding method <b>padding</b>.
134 static INLINE int
135 crypto_get_rsa_padding_overhead(int padding)
137 switch (padding)
139 case RSA_NO_PADDING: return 0;
140 case RSA_PKCS1_OAEP_PADDING: return 42;
141 case RSA_PKCS1_PADDING: return 11;
142 default: tor_assert(0); return -1;
146 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
148 static INLINE int
149 crypto_get_rsa_padding(int padding)
151 switch (padding)
153 case PK_NO_PADDING: return RSA_NO_PADDING;
154 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
155 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
156 default: tor_assert(0); return -1;
160 /** Boolean: has OpenSSL's crypto been initialized? */
161 static int _crypto_global_initialized = 0;
163 /** Log all pending crypto errors at level <b>severity</b>. Use
164 * <b>doing</b> to describe our current activities.
166 static void
167 crypto_log_errors(int severity, const char *doing)
169 unsigned long err;
170 const char *msg, *lib, *func;
171 while ((err = ERR_get_error()) != 0) {
172 msg = (const char*)ERR_reason_error_string(err);
173 lib = (const char*)ERR_lib_error_string(err);
174 func = (const char*)ERR_func_error_string(err);
175 if (!msg) msg = "(null)";
176 if (!lib) lib = "(null)";
177 if (!func) func = "(null)";
178 if (doing) {
179 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
180 doing, msg, lib, func);
181 } else {
182 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
187 #ifndef DISABLE_ENGINES
188 /** Log any OpenSSL engines we're using at NOTICE. */
189 static void
190 log_engine(const char *fn, ENGINE *e)
192 if (e) {
193 const char *name, *id;
194 name = ENGINE_get_name(e);
195 id = ENGINE_get_id(e);
196 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
197 name?name:"?", id?id:"?", fn);
198 } else {
199 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
202 #endif
204 #ifndef DISABLE_ENGINES
205 /** Try to load an engine in a shared library via fully qualified path.
207 static ENGINE *
208 try_load_engine(const char *path, const char *engine)
210 ENGINE *e = ENGINE_by_id("dynamic");
211 if (e) {
212 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
213 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
214 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
215 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
216 ENGINE_free(e);
217 e = NULL;
220 return e;
222 #endif
224 /** Initialize the crypto library. Return 0 on success, -1 on failure.
227 crypto_global_init(int useAccel, const char *accelName, const char *accelDir,
228 int DynamicPrimes)
230 if (!_crypto_global_initialized) {
231 ERR_load_crypto_strings();
232 OpenSSL_add_all_algorithms();
233 _crypto_global_initialized = 1;
234 setup_openssl_threading();
235 use_dynamic_primes = DynamicPrimes;
236 if (useAccel > 0) {
237 #ifdef DISABLE_ENGINES
238 (void)accelName;
239 (void)accelDir;
240 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
241 #else
242 ENGINE *e = NULL;
244 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
245 ENGINE_load_builtin_engines();
246 ENGINE_register_all_complete();
248 if (accelName) {
249 if (accelDir) {
250 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
251 " via path \"%s\".", accelName, accelDir);
252 e = try_load_engine(accelName, accelDir);
253 } else {
254 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
255 " acceleration support.", accelName);
256 e = ENGINE_by_id(accelName);
258 if (!e) {
259 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
260 accelName);
261 } else {
262 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
263 accelName);
266 if (e) {
267 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
268 " setting default ciphers.");
269 ENGINE_set_default(e, ENGINE_METHOD_ALL);
271 log_engine("RSA", ENGINE_get_default_RSA());
272 log_engine("DH", ENGINE_get_default_DH());
273 log_engine("RAND", ENGINE_get_default_RAND());
274 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
275 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
276 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
277 #endif
278 } else {
279 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
281 return crypto_seed_rng(1);
283 return 0;
286 /** Free crypto resources held by this thread. */
287 void
288 crypto_thread_cleanup(void)
290 ERR_remove_state(0);
293 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
296 crypto_global_cleanup(void)
298 EVP_cleanup();
299 ERR_remove_state(0);
300 ERR_free_strings();
302 #ifndef DISABLE_ENGINES
303 ENGINE_cleanup();
304 #endif
306 CONF_modules_unload(1);
307 CRYPTO_cleanup_all_ex_data();
308 #ifdef TOR_IS_MULTITHREADED
309 if (_n_openssl_mutexes) {
310 int n = _n_openssl_mutexes;
311 tor_mutex_t **ms = _openssl_mutexes;
312 int i;
313 _openssl_mutexes = NULL;
314 _n_openssl_mutexes = 0;
315 for (i=0;i<n;++i) {
316 tor_mutex_free(ms[i]);
318 tor_free(ms);
320 #endif
321 return 0;
324 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
325 crypto_pk_env_t *
326 _crypto_new_pk_env_rsa(RSA *rsa)
328 crypto_pk_env_t *env;
329 tor_assert(rsa);
330 env = tor_malloc(sizeof(crypto_pk_env_t));
331 env->refs = 1;
332 env->key = rsa;
333 return env;
336 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
337 * crypto_pk_env_t. */
338 RSA *
339 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
341 return env->key;
344 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
345 * private is set, include the private-key portion of the key. */
346 EVP_PKEY *
347 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
349 RSA *key = NULL;
350 EVP_PKEY *pkey = NULL;
351 tor_assert(env->key);
352 if (private) {
353 if (!(key = RSAPrivateKey_dup(env->key)))
354 goto error;
355 } else {
356 if (!(key = RSAPublicKey_dup(env->key)))
357 goto error;
359 if (!(pkey = EVP_PKEY_new()))
360 goto error;
361 if (!(EVP_PKEY_assign_RSA(pkey, key)))
362 goto error;
363 return pkey;
364 error:
365 if (pkey)
366 EVP_PKEY_free(pkey);
367 if (key)
368 RSA_free(key);
369 return NULL;
372 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
374 DH *
375 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
377 return dh->dh;
380 /** Allocate and return storage for a public key. The key itself will not yet
381 * be set.
383 crypto_pk_env_t *
384 crypto_new_pk_env(void)
386 RSA *rsa;
388 rsa = RSA_new();
389 tor_assert(rsa);
390 return _crypto_new_pk_env_rsa(rsa);
393 /** Release a reference to an asymmetric key; when all the references
394 * are released, free the key.
396 void
397 crypto_free_pk_env(crypto_pk_env_t *env)
399 if (!env)
400 return;
402 if (--env->refs > 0)
403 return;
404 tor_assert(env->refs == 0);
406 if (env->key)
407 RSA_free(env->key);
409 tor_free(env);
412 /** Create a new symmetric cipher for a given key and encryption flag
413 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
414 * on failure.
416 crypto_cipher_env_t *
417 crypto_create_init_cipher(const char *key, int encrypt_mode)
419 int r;
420 crypto_cipher_env_t *crypto = NULL;
422 if (! (crypto = crypto_new_cipher_env())) {
423 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
424 return NULL;
427 crypto_cipher_set_key(crypto, key);
429 if (encrypt_mode)
430 r = crypto_cipher_encrypt_init_cipher(crypto);
431 else
432 r = crypto_cipher_decrypt_init_cipher(crypto);
434 if (r)
435 goto error;
436 return crypto;
438 error:
439 if (crypto)
440 crypto_free_cipher_env(crypto);
441 return NULL;
444 /** Allocate and return a new symmetric cipher.
446 crypto_cipher_env_t *
447 crypto_new_cipher_env(void)
449 crypto_cipher_env_t *env;
451 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
452 env->cipher = aes_new_cipher();
453 return env;
456 /** Free a symmetric cipher.
458 void
459 crypto_free_cipher_env(crypto_cipher_env_t *env)
461 if (!env)
462 return;
464 tor_assert(env->cipher);
465 aes_free_cipher(env->cipher);
466 memset(env, 0, sizeof(crypto_cipher_env_t));
467 tor_free(env);
470 /* public key crypto */
472 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
473 * Return 0 on success, -1 on failure.
476 crypto_pk_generate_key_with_bits(crypto_pk_env_t *env, int bits)
478 tor_assert(env);
480 if (env->key)
481 RSA_free(env->key);
482 #if OPENSSL_VERSION_NUMBER < 0x00908000l
483 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
484 env->key = RSA_generate_key(bits, 65537, NULL, NULL);
485 #else
486 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
488 BIGNUM *e = BN_new();
489 RSA *r = NULL;
490 if (!e)
491 goto done;
492 if (! BN_set_word(e, 65537))
493 goto done;
494 r = RSA_new();
495 if (!r)
496 goto done;
497 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
498 goto done;
500 env->key = r;
501 r = NULL;
502 done:
503 if (e)
504 BN_free(e);
505 if (r)
506 RSA_free(r);
508 #endif
509 if (!env->key) {
510 crypto_log_errors(LOG_WARN, "generating RSA key");
511 return -1;
514 return 0;
517 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
518 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
519 * the string is nul-terminated.
521 /* Used here, and used for testing. */
523 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
524 const char *s, ssize_t len)
526 BIO *b;
528 tor_assert(env);
529 tor_assert(s);
530 tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
532 /* Create a read-only memory BIO, backed by the string 's' */
533 b = BIO_new_mem_buf((char*)s, (int)len);
534 if (!b)
535 return -1;
537 if (env->key)
538 RSA_free(env->key);
540 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
542 BIO_free(b);
544 if (!env->key) {
545 crypto_log_errors(LOG_WARN, "Error parsing private key");
546 return -1;
548 return 0;
551 /** Read a PEM-encoded private key from the file named by
552 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
555 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
556 const char *keyfile)
558 char *contents;
559 int r;
561 /* Read the file into a string. */
562 contents = read_file_to_str(keyfile, 0, NULL);
563 if (!contents) {
564 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
565 return -1;
568 /* Try to parse it. */
569 r = crypto_pk_read_private_key_from_string(env, contents, -1);
570 memset(contents, 0, strlen(contents));
571 tor_free(contents);
572 if (r)
573 return -1; /* read_private_key_from_string already warned, so we don't.*/
575 /* Make sure it's valid. */
576 if (crypto_pk_check_key(env) <= 0)
577 return -1;
579 return 0;
582 /** Helper function to implement crypto_pk_write_*_key_to_string. */
583 static int
584 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
585 size_t *len, int is_public)
587 BUF_MEM *buf;
588 BIO *b;
589 int r;
591 tor_assert(env);
592 tor_assert(env->key);
593 tor_assert(dest);
595 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
596 if (!b)
597 return -1;
599 /* Now you can treat b as if it were a file. Just use the
600 * PEM_*_bio_* functions instead of the non-bio variants.
602 if (is_public)
603 r = PEM_write_bio_RSAPublicKey(b, env->key);
604 else
605 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
607 if (!r) {
608 crypto_log_errors(LOG_WARN, "writing RSA key to string");
609 BIO_free(b);
610 return -1;
613 BIO_get_mem_ptr(b, &buf);
614 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
615 BIO_free(b);
617 *dest = tor_malloc(buf->length+1);
618 memcpy(*dest, buf->data, buf->length);
619 (*dest)[buf->length] = 0; /* nul terminate it */
620 *len = buf->length;
621 BUF_MEM_free(buf);
623 return 0;
626 /** PEM-encode the public key portion of <b>env</b> and write it to a
627 * newly allocated string. On success, set *<b>dest</b> to the new
628 * string, *<b>len</b> to the string's length, and return 0. On
629 * failure, return -1.
632 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
633 size_t *len)
635 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
638 /** PEM-encode the private key portion of <b>env</b> and write it to a
639 * newly allocated string. On success, set *<b>dest</b> to the new
640 * string, *<b>len</b> to the string's length, and return 0. On
641 * failure, return -1.
644 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
645 size_t *len)
647 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
650 /** Read a PEM-encoded public key from the first <b>len</b> characters of
651 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
652 * failure.
655 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
656 size_t len)
658 BIO *b;
660 tor_assert(env);
661 tor_assert(src);
662 tor_assert(len<INT_MAX);
664 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
665 if (!b)
666 return -1;
668 BIO_write(b, src, (int)len);
670 if (env->key)
671 RSA_free(env->key);
672 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
673 BIO_free(b);
674 if (!env->key) {
675 crypto_log_errors(LOG_WARN, "reading public key from string");
676 return -1;
679 return 0;
682 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
683 * PEM-encoded. Return 0 on success, -1 on failure.
686 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
687 const char *fname)
689 BIO *bio;
690 char *cp;
691 long len;
692 char *s;
693 int r;
695 tor_assert(PRIVATE_KEY_OK(env));
697 if (!(bio = BIO_new(BIO_s_mem())))
698 return -1;
699 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
700 == 0) {
701 crypto_log_errors(LOG_WARN, "writing private key");
702 BIO_free(bio);
703 return -1;
705 len = BIO_get_mem_data(bio, &cp);
706 tor_assert(len >= 0);
707 s = tor_malloc(len+1);
708 memcpy(s, cp, len);
709 s[len]='\0';
710 r = write_str_to_file(fname, s, 0);
711 BIO_free(bio);
712 memset(s, 0, strlen(s));
713 tor_free(s);
714 return r;
717 /** Return true iff <b>env</b> has a valid key.
720 crypto_pk_check_key(crypto_pk_env_t *env)
722 int r;
723 tor_assert(env);
725 r = RSA_check_key(env->key);
726 if (r <= 0)
727 crypto_log_errors(LOG_WARN,"checking RSA key");
728 return r;
731 /** Return true iff <b>key</b> contains the private-key portion of the RSA
732 * key. */
734 crypto_pk_key_is_private(const crypto_pk_env_t *key)
736 tor_assert(key);
737 return PRIVATE_KEY_OK(key);
740 /** Return true iff <b>env</b> contains a public key whose public exponent
741 * equals 65537.
744 crypto_pk_public_exponent_ok(crypto_pk_env_t *env)
746 tor_assert(env);
747 tor_assert(env->key);
749 return BN_is_word(env->key->e, 65537);
752 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
753 * if a==b, and 1 if a\>b.
756 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
758 int result;
760 if (!a || !b)
761 return -1;
763 if (!a->key || !b->key)
764 return -1;
766 tor_assert(PUBLIC_KEY_OK(a));
767 tor_assert(PUBLIC_KEY_OK(b));
768 result = BN_cmp((a->key)->n, (b->key)->n);
769 if (result)
770 return result;
771 return BN_cmp((a->key)->e, (b->key)->e);
774 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
775 size_t
776 crypto_pk_keysize(crypto_pk_env_t *env)
778 tor_assert(env);
779 tor_assert(env->key);
781 return (size_t) RSA_size(env->key);
784 /** Return the size of the public key modulus of <b>env</b>, in bits. */
786 crypto_pk_num_bits(crypto_pk_env_t *env)
788 tor_assert(env);
789 tor_assert(env->key);
790 tor_assert(env->key->n);
792 return BN_num_bits(env->key->n);
795 /** Increase the reference count of <b>env</b>, and return it.
797 crypto_pk_env_t *
798 crypto_pk_dup_key(crypto_pk_env_t *env)
800 tor_assert(env);
801 tor_assert(env->key);
803 env->refs++;
804 return env;
807 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
808 crypto_pk_env_t *
809 crypto_pk_copy_full(crypto_pk_env_t *env)
811 RSA *new_key;
812 int privatekey = 0;
813 tor_assert(env);
814 tor_assert(env->key);
816 if (PRIVATE_KEY_OK(env)) {
817 new_key = RSAPrivateKey_dup(env->key);
818 privatekey = 1;
819 } else {
820 new_key = RSAPublicKey_dup(env->key);
822 if (!new_key) {
823 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
824 privatekey?"private":"public");
825 crypto_log_errors(LOG_ERR,
826 privatekey ? "Duplicating a private key" :
827 "Duplicating a public key");
828 tor_fragile_assert();
829 return NULL;
832 return _crypto_new_pk_env_rsa(new_key);
835 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
836 * in <b>env</b>, using the padding method <b>padding</b>. On success,
837 * write the result to <b>to</b>, and return the number of bytes
838 * written. On failure, return -1.
840 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
841 * at least the length of the modulus of <b>env</b>.
844 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to, size_t tolen,
845 const char *from, size_t fromlen, int padding)
847 int r;
848 tor_assert(env);
849 tor_assert(from);
850 tor_assert(to);
851 tor_assert(fromlen<INT_MAX);
852 tor_assert(tolen >= crypto_pk_keysize(env));
854 r = RSA_public_encrypt((int)fromlen,
855 (unsigned char*)from, (unsigned char*)to,
856 env->key, crypto_get_rsa_padding(padding));
857 if (r<0) {
858 crypto_log_errors(LOG_WARN, "performing RSA encryption");
859 return -1;
861 return r;
864 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
865 * in <b>env</b>, using the padding method <b>padding</b>. On success,
866 * write the result to <b>to</b>, and return the number of bytes
867 * written. On failure, return -1.
869 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
870 * at least the length of the modulus of <b>env</b>.
873 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
874 size_t tolen,
875 const char *from, size_t fromlen,
876 int padding, int warnOnFailure)
878 int r;
879 tor_assert(env);
880 tor_assert(from);
881 tor_assert(to);
882 tor_assert(env->key);
883 tor_assert(fromlen<INT_MAX);
884 tor_assert(tolen >= crypto_pk_keysize(env));
885 if (!env->key->p)
886 /* Not a private key */
887 return -1;
889 r = RSA_private_decrypt((int)fromlen,
890 (unsigned char*)from, (unsigned char*)to,
891 env->key, crypto_get_rsa_padding(padding));
893 if (r<0) {
894 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
895 "performing RSA decryption");
896 return -1;
898 return r;
901 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
902 * public key in <b>env</b>, using PKCS1 padding. On success, write the
903 * signed data to <b>to</b>, and return the number of bytes written.
904 * On failure, return -1.
906 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
907 * at least the length of the modulus of <b>env</b>.
910 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
911 size_t tolen,
912 const char *from, size_t fromlen)
914 int r;
915 tor_assert(env);
916 tor_assert(from);
917 tor_assert(to);
918 tor_assert(fromlen < INT_MAX);
919 tor_assert(tolen >= crypto_pk_keysize(env));
920 r = RSA_public_decrypt((int)fromlen,
921 (unsigned char*)from, (unsigned char*)to,
922 env->key, RSA_PKCS1_PADDING);
924 if (r<0) {
925 crypto_log_errors(LOG_WARN, "checking RSA signature");
926 return -1;
928 return r;
931 /** Check a siglen-byte long signature at <b>sig</b> against
932 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
933 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
934 * SHA1(data). Else return -1.
937 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
938 size_t datalen, const char *sig, size_t siglen)
940 char digest[DIGEST_LEN];
941 char *buf;
942 size_t buflen;
943 int r;
945 tor_assert(env);
946 tor_assert(data);
947 tor_assert(sig);
948 tor_assert(datalen < SIZE_T_CEILING);
949 tor_assert(siglen < SIZE_T_CEILING);
951 if (crypto_digest(digest,data,datalen)<0) {
952 log_warn(LD_BUG, "couldn't compute digest");
953 return -1;
955 buflen = crypto_pk_keysize(env);
956 buf = tor_malloc(buflen);
957 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
958 if (r != DIGEST_LEN) {
959 log_warn(LD_CRYPTO, "Invalid signature");
960 tor_free(buf);
961 return -1;
963 if (tor_memneq(buf, digest, DIGEST_LEN)) {
964 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
965 tor_free(buf);
966 return -1;
968 tor_free(buf);
970 return 0;
973 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
974 * <b>env</b>, using PKCS1 padding. On success, write the signature to
975 * <b>to</b>, and return the number of bytes written. On failure, return
976 * -1.
978 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
979 * at least the length of the modulus of <b>env</b>.
982 crypto_pk_private_sign(crypto_pk_env_t *env, char *to, size_t tolen,
983 const char *from, size_t fromlen)
985 int r;
986 tor_assert(env);
987 tor_assert(from);
988 tor_assert(to);
989 tor_assert(fromlen < INT_MAX);
990 tor_assert(tolen >= crypto_pk_keysize(env));
991 if (!env->key->p)
992 /* Not a private key */
993 return -1;
995 r = RSA_private_encrypt((int)fromlen,
996 (unsigned char*)from, (unsigned char*)to,
997 env->key, RSA_PKCS1_PADDING);
998 if (r<0) {
999 crypto_log_errors(LOG_WARN, "generating RSA signature");
1000 return -1;
1002 return r;
1005 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1006 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1007 * store it in <b>to</b>. Return the number of bytes written on
1008 * success, and -1 on failure.
1010 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1011 * at least the length of the modulus of <b>env</b>.
1014 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to, size_t tolen,
1015 const char *from, size_t fromlen)
1017 int r;
1018 char digest[DIGEST_LEN];
1019 if (crypto_digest(digest,from,fromlen)<0)
1020 return -1;
1021 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
1022 memset(digest, 0, sizeof(digest));
1023 return r;
1026 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1027 * bytes of data from <b>from</b>, with padding type 'padding',
1028 * storing the results on <b>to</b>.
1030 * If no padding is used, the public key must be at least as large as
1031 * <b>from</b>.
1033 * Returns the number of bytes written on success, -1 on failure.
1035 * The encrypted data consists of:
1036 * - The source data, padded and encrypted with the public key, if the
1037 * padded source data is no longer than the public key, and <b>force</b>
1038 * is false, OR
1039 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1040 * padded and encrypted with the public key; followed by the rest of
1041 * the source data encrypted in AES-CTR mode with the symmetric key.
1044 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
1045 char *to, size_t tolen,
1046 const char *from,
1047 size_t fromlen,
1048 int padding, int force)
1050 int overhead, outlen, r;
1051 size_t pkeylen, symlen;
1052 crypto_cipher_env_t *cipher = NULL;
1053 char *buf = NULL;
1055 tor_assert(env);
1056 tor_assert(from);
1057 tor_assert(to);
1058 tor_assert(fromlen < SIZE_T_CEILING);
1060 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1061 pkeylen = crypto_pk_keysize(env);
1063 if (padding == PK_NO_PADDING && fromlen < pkeylen)
1064 return -1;
1066 if (!force && fromlen+overhead <= pkeylen) {
1067 /* It all fits in a single encrypt. */
1068 return crypto_pk_public_encrypt(env,to,
1069 tolen,
1070 from,fromlen,padding);
1072 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1073 tor_assert(tolen >= pkeylen);
1075 cipher = crypto_new_cipher_env();
1076 if (!cipher) return -1;
1077 if (crypto_cipher_generate_key(cipher)<0)
1078 goto err;
1079 /* You can't just run around RSA-encrypting any bitstream: if it's
1080 * greater than the RSA key, then OpenSSL will happily encrypt, and
1081 * later decrypt to the wrong value. So we set the first bit of
1082 * 'cipher->key' to 0 if we aren't padding. This means that our
1083 * symmetric key is really only 127 bits.
1085 if (padding == PK_NO_PADDING)
1086 cipher->key[0] &= 0x7f;
1087 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
1088 goto err;
1089 buf = tor_malloc(pkeylen+1);
1090 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1091 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1093 /* Length of symmetrically encrypted data. */
1094 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1096 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1097 if (outlen!=(int)pkeylen) {
1098 goto err;
1100 r = crypto_cipher_encrypt(cipher, to+outlen,
1101 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1103 if (r<0) goto err;
1104 memset(buf, 0, pkeylen);
1105 tor_free(buf);
1106 crypto_free_cipher_env(cipher);
1107 tor_assert(outlen+symlen < INT_MAX);
1108 return (int)(outlen + symlen);
1109 err:
1110 if (buf) {
1111 memset(buf, 0, pkeylen);
1112 tor_free(buf);
1114 if (cipher) crypto_free_cipher_env(cipher);
1115 return -1;
1118 /** Invert crypto_pk_public_hybrid_encrypt. */
1120 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1121 char *to,
1122 size_t tolen,
1123 const char *from,
1124 size_t fromlen,
1125 int padding, int warnOnFailure)
1127 int outlen, r;
1128 size_t pkeylen;
1129 crypto_cipher_env_t *cipher = NULL;
1130 char *buf = NULL;
1132 tor_assert(fromlen < SIZE_T_CEILING);
1133 pkeylen = crypto_pk_keysize(env);
1135 if (fromlen <= pkeylen) {
1136 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1137 warnOnFailure);
1140 buf = tor_malloc(pkeylen);
1141 outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
1142 warnOnFailure);
1143 if (outlen<0) {
1144 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1145 "Error decrypting public-key data");
1146 goto err;
1148 if (outlen < CIPHER_KEY_LEN) {
1149 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1150 "No room for a symmetric key");
1151 goto err;
1153 cipher = crypto_create_init_cipher(buf, 0);
1154 if (!cipher) {
1155 goto err;
1157 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1158 outlen -= CIPHER_KEY_LEN;
1159 tor_assert(tolen - outlen >= fromlen - pkeylen);
1160 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1161 if (r<0)
1162 goto err;
1163 memset(buf,0,pkeylen);
1164 tor_free(buf);
1165 crypto_free_cipher_env(cipher);
1166 tor_assert(outlen + fromlen < INT_MAX);
1167 return (int)(outlen + (fromlen-pkeylen));
1168 err:
1169 memset(buf,0,pkeylen);
1170 tor_free(buf);
1171 if (cipher) crypto_free_cipher_env(cipher);
1172 return -1;
1175 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1176 * Return -1 on error, or the number of characters used on success.
1179 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1181 int len;
1182 unsigned char *buf, *cp;
1183 len = i2d_RSAPublicKey(pk->key, NULL);
1184 if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
1185 return -1;
1186 cp = buf = tor_malloc(len+1);
1187 len = i2d_RSAPublicKey(pk->key, &cp);
1188 if (len < 0) {
1189 crypto_log_errors(LOG_WARN,"encoding public key");
1190 tor_free(buf);
1191 return -1;
1193 /* We don't encode directly into 'dest', because that would be illegal
1194 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1196 memcpy(dest,buf,len);
1197 tor_free(buf);
1198 return len;
1201 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1202 * success and NULL on failure.
1204 crypto_pk_env_t *
1205 crypto_pk_asn1_decode(const char *str, size_t len)
1207 RSA *rsa;
1208 unsigned char *buf;
1209 const unsigned char *cp;
1210 cp = buf = tor_malloc(len);
1211 memcpy(buf,str,len);
1212 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1213 tor_free(buf);
1214 if (!rsa) {
1215 crypto_log_errors(LOG_WARN,"decoding public key");
1216 return NULL;
1218 return _crypto_new_pk_env_rsa(rsa);
1221 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1222 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1223 * Return 0 on success, -1 on failure.
1226 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1228 unsigned char *buf, *bufp;
1229 int len;
1231 len = i2d_RSAPublicKey(pk->key, NULL);
1232 if (len < 0)
1233 return -1;
1234 buf = bufp = tor_malloc(len+1);
1235 len = i2d_RSAPublicKey(pk->key, &bufp);
1236 if (len < 0) {
1237 crypto_log_errors(LOG_WARN,"encoding public key");
1238 tor_free(buf);
1239 return -1;
1241 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1242 tor_free(buf);
1243 return -1;
1245 tor_free(buf);
1246 return 0;
1249 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1250 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1252 crypto_pk_get_all_digests(crypto_pk_env_t *pk, digests_t *digests_out)
1254 unsigned char *buf, *bufp;
1255 int len;
1257 len = i2d_RSAPublicKey(pk->key, NULL);
1258 if (len < 0)
1259 return -1;
1260 buf = bufp = tor_malloc(len+1);
1261 len = i2d_RSAPublicKey(pk->key, &bufp);
1262 if (len < 0) {
1263 crypto_log_errors(LOG_WARN,"encoding public key");
1264 tor_free(buf);
1265 return -1;
1267 if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
1268 tor_free(buf);
1269 return -1;
1271 tor_free(buf);
1272 return 0;
1275 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1276 * every four spaces. */
1277 /* static */ void
1278 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1280 int n = 0;
1281 char *end = out+outlen;
1282 tor_assert(outlen < SIZE_T_CEILING);
1284 while (*in && out<end) {
1285 *out++ = *in++;
1286 if (++n == 4 && *in && out<end) {
1287 n = 0;
1288 *out++ = ' ';
1291 tor_assert(out<end);
1292 *out = '\0';
1295 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1296 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1297 * space). Return 0 on success, -1 on failure.
1299 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1300 * of the public key, converted to hexadecimal, in upper case, with a
1301 * space after every four digits.
1303 * If <b>add_space</b> is false, omit the spaces.
1306 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1308 char digest[DIGEST_LEN];
1309 char hexdigest[HEX_DIGEST_LEN+1];
1310 if (crypto_pk_get_digest(pk, digest)) {
1311 return -1;
1313 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1314 if (add_space) {
1315 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1316 } else {
1317 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1319 return 0;
1322 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1325 crypto_pk_check_fingerprint_syntax(const char *s)
1327 int i;
1328 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1329 if ((i%5) == 4) {
1330 if (!TOR_ISSPACE(s[i])) return 0;
1331 } else {
1332 if (!TOR_ISXDIGIT(s[i])) return 0;
1335 if (s[FINGERPRINT_LEN]) return 0;
1336 return 1;
1339 /* symmetric crypto */
1341 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1342 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1345 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1347 tor_assert(env);
1349 return crypto_rand(env->key, CIPHER_KEY_LEN);
1352 /** Set the symmetric key for the cipher in <b>env</b> to the first
1353 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1355 void
1356 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1358 tor_assert(env);
1359 tor_assert(key);
1361 memcpy(env->key, key, CIPHER_KEY_LEN);
1364 /** Generate an initialization vector for our AES-CTR cipher; store it
1365 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1366 void
1367 crypto_cipher_generate_iv(char *iv_out)
1369 crypto_rand(iv_out, CIPHER_IV_LEN);
1372 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1373 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1374 * <b>iv</b>. */
1376 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1378 tor_assert(env);
1379 tor_assert(iv);
1380 aes_set_iv(env->cipher, iv);
1381 return 0;
1384 /** Return a pointer to the key set for the cipher in <b>env</b>.
1386 const char *
1387 crypto_cipher_get_key(crypto_cipher_env_t *env)
1389 return env->key;
1392 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1393 * success, -1 on failure.
1396 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1398 tor_assert(env);
1400 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1401 return 0;
1404 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1405 * success, -1 on failure.
1408 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1410 tor_assert(env);
1412 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1413 return 0;
1416 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1417 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1418 * On failure, return -1.
1421 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1422 const char *from, size_t fromlen)
1424 tor_assert(env);
1425 tor_assert(env->cipher);
1426 tor_assert(from);
1427 tor_assert(fromlen);
1428 tor_assert(to);
1429 tor_assert(fromlen < SIZE_T_CEILING);
1431 aes_crypt(env->cipher, from, fromlen, to);
1432 return 0;
1435 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1436 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1437 * On failure, return -1.
1440 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1441 const char *from, size_t fromlen)
1443 tor_assert(env);
1444 tor_assert(from);
1445 tor_assert(to);
1446 tor_assert(fromlen < SIZE_T_CEILING);
1448 aes_crypt(env->cipher, from, fromlen, to);
1449 return 0;
1452 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1453 * on success, return 0. On failure, return -1.
1456 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1458 tor_assert(len < SIZE_T_CEILING);
1459 aes_crypt_inplace(env->cipher, buf, len);
1460 return 0;
1463 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1464 * <b>cipher</b> to the buffer in <b>to</b> of length
1465 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1466 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1467 * number of bytes written, on failure, return -1.
1469 * This function adjusts the current position of the counter in <b>cipher</b>
1470 * to immediately after the encrypted data.
1473 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1474 char *to, size_t tolen,
1475 const char *from, size_t fromlen)
1477 tor_assert(cipher);
1478 tor_assert(from);
1479 tor_assert(to);
1480 tor_assert(fromlen < INT_MAX);
1482 if (fromlen < 1)
1483 return -1;
1484 if (tolen < fromlen + CIPHER_IV_LEN)
1485 return -1;
1487 crypto_cipher_generate_iv(to);
1488 if (crypto_cipher_set_iv(cipher, to)<0)
1489 return -1;
1490 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1491 return (int)(fromlen + CIPHER_IV_LEN);
1494 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1495 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1496 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1497 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1498 * number of bytes written, on failure, return -1.
1500 * This function adjusts the current position of the counter in <b>cipher</b>
1501 * to immediately after the decrypted data.
1504 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1505 char *to, size_t tolen,
1506 const char *from, size_t fromlen)
1508 tor_assert(cipher);
1509 tor_assert(from);
1510 tor_assert(to);
1511 tor_assert(fromlen < INT_MAX);
1513 if (fromlen <= CIPHER_IV_LEN)
1514 return -1;
1515 if (tolen < fromlen - CIPHER_IV_LEN)
1516 return -1;
1518 if (crypto_cipher_set_iv(cipher, from)<0)
1519 return -1;
1520 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1521 return (int)(fromlen - CIPHER_IV_LEN);
1524 /* SHA-1 */
1526 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1527 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1528 * Return 0 on success, -1 on failure.
1531 crypto_digest(char *digest, const char *m, size_t len)
1533 tor_assert(m);
1534 tor_assert(digest);
1535 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1538 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1539 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1540 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1542 crypto_digest256(char *digest, const char *m, size_t len,
1543 digest_algorithm_t algorithm)
1545 tor_assert(m);
1546 tor_assert(digest);
1547 tor_assert(algorithm == DIGEST_SHA256);
1548 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1551 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1552 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1553 * success, -1 on failure. */
1555 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1557 digest_algorithm_t i;
1558 tor_assert(ds_out);
1559 memset(ds_out, 0, sizeof(*ds_out));
1560 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1561 return -1;
1562 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1563 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1564 return -1;
1566 return 0;
1569 /** Return the name of an algorithm, as used in directory documents. */
1570 const char *
1571 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1573 switch (alg) {
1574 case DIGEST_SHA1:
1575 return "sha1";
1576 case DIGEST_SHA256:
1577 return "sha256";
1578 default:
1579 tor_fragile_assert();
1580 return "??unknown_digest??";
1584 /** Given the name of a digest algorithm, return its integer value, or -1 if
1585 * the name is not recognized. */
1587 crypto_digest_algorithm_parse_name(const char *name)
1589 if (!strcmp(name, "sha1"))
1590 return DIGEST_SHA1;
1591 else if (!strcmp(name, "sha256"))
1592 return DIGEST_SHA256;
1593 else
1594 return -1;
1597 /** Intermediate information about the digest of a stream of data. */
1598 struct crypto_digest_env_t {
1599 union {
1600 SHA_CTX sha1; /**< state for SHA1 */
1601 SHA256_CTX sha2; /**< state for SHA256 */
1602 } d; /**< State for the digest we're using. Only one member of the
1603 * union is usable, depending on the value of <b>algorithm</b>. */
1604 digest_algorithm_t algorithm : 8; /**< Which algorithm is in use? */
1607 /** Allocate and return a new digest object to compute SHA1 digests.
1609 crypto_digest_env_t *
1610 crypto_new_digest_env(void)
1612 crypto_digest_env_t *r;
1613 r = tor_malloc(sizeof(crypto_digest_env_t));
1614 SHA1_Init(&r->d.sha1);
1615 r->algorithm = DIGEST_SHA1;
1616 return r;
1619 /** Allocate and return a new digest object to compute 256-bit digests
1620 * using <b>algorithm</b>. */
1621 crypto_digest_env_t *
1622 crypto_new_digest256_env(digest_algorithm_t algorithm)
1624 crypto_digest_env_t *r;
1625 tor_assert(algorithm == DIGEST_SHA256);
1626 r = tor_malloc(sizeof(crypto_digest_env_t));
1627 SHA256_Init(&r->d.sha2);
1628 r->algorithm = algorithm;
1629 return r;
1632 /** Deallocate a digest object.
1634 void
1635 crypto_free_digest_env(crypto_digest_env_t *digest)
1637 if (!digest)
1638 return;
1639 memset(digest, 0, sizeof(crypto_digest_env_t));
1640 tor_free(digest);
1643 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1645 void
1646 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1647 size_t len)
1649 tor_assert(digest);
1650 tor_assert(data);
1651 /* Using the SHA*_*() calls directly means we don't support doing
1652 * SHA in hardware. But so far the delay of getting the question
1653 * to the hardware, and hearing the answer, is likely higher than
1654 * just doing it ourselves. Hashes are fast.
1656 switch (digest->algorithm) {
1657 case DIGEST_SHA1:
1658 SHA1_Update(&digest->d.sha1, (void*)data, len);
1659 break;
1660 case DIGEST_SHA256:
1661 SHA256_Update(&digest->d.sha2, (void*)data, len);
1662 break;
1663 default:
1664 tor_fragile_assert();
1665 break;
1669 /** Compute the hash of the data that has been passed to the digest
1670 * object; write the first out_len bytes of the result to <b>out</b>.
1671 * <b>out_len</b> must be \<= DIGEST256_LEN.
1673 void
1674 crypto_digest_get_digest(crypto_digest_env_t *digest,
1675 char *out, size_t out_len)
1677 unsigned char r[DIGEST256_LEN];
1678 crypto_digest_env_t tmpenv;
1679 tor_assert(digest);
1680 tor_assert(out);
1681 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1682 memcpy(&tmpenv, digest, sizeof(crypto_digest_env_t));
1683 switch (digest->algorithm) {
1684 case DIGEST_SHA1:
1685 tor_assert(out_len <= DIGEST_LEN);
1686 SHA1_Final(r, &tmpenv.d.sha1);
1687 break;
1688 case DIGEST_SHA256:
1689 tor_assert(out_len <= DIGEST256_LEN);
1690 SHA256_Final(r, &tmpenv.d.sha2);
1691 break;
1692 default:
1693 log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
1694 /* If fragile_assert is not enabled, then we should at least not
1695 * leak anything. */
1696 memset(r, 0xff, sizeof(r));
1697 tor_fragile_assert();
1698 break;
1700 memcpy(out, r, out_len);
1701 memset(r, 0, sizeof(r));
1704 /** Allocate and return a new digest object with the same state as
1705 * <b>digest</b>
1707 crypto_digest_env_t *
1708 crypto_digest_dup(const crypto_digest_env_t *digest)
1710 crypto_digest_env_t *r;
1711 tor_assert(digest);
1712 r = tor_malloc(sizeof(crypto_digest_env_t));
1713 memcpy(r,digest,sizeof(crypto_digest_env_t));
1714 return r;
1717 /** Replace the state of the digest object <b>into</b> with the state
1718 * of the digest object <b>from</b>.
1720 void
1721 crypto_digest_assign(crypto_digest_env_t *into,
1722 const crypto_digest_env_t *from)
1724 tor_assert(into);
1725 tor_assert(from);
1726 memcpy(into,from,sizeof(crypto_digest_env_t));
1729 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1730 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1731 * in <b>hmac_out</b>.
1733 void
1734 crypto_hmac_sha1(char *hmac_out,
1735 const char *key, size_t key_len,
1736 const char *msg, size_t msg_len)
1738 tor_assert(key_len < INT_MAX);
1739 tor_assert(msg_len < INT_MAX);
1740 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1741 (unsigned char*)hmac_out, NULL);
1744 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1745 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1746 * in <b>hmac_out</b>.
1748 void
1749 crypto_hmac_sha256(char *hmac_out,
1750 const char *key, size_t key_len,
1751 const char *msg, size_t msg_len)
1753 #if (OPENSSL_VERSION_NUMBER >= 0x00908000l)
1754 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1755 tor_assert(key_len < INT_MAX);
1756 tor_assert(msg_len < INT_MAX);
1757 HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1758 (unsigned char*)hmac_out, NULL);
1759 #else
1760 /* OpenSSL doesn't have an EVP implementation for SHA256. We'll need
1761 to do HMAC on our own.
1763 HMAC isn't so hard: To compute HMAC(key, msg):
1764 1. If len(key) > blocksize, key = H(key).
1765 2. If len(key) < blocksize, right-pad key up to blocksize with 0 bytes.
1766 3. let ipad = key xor 0x363636363636....36
1767 let opad = key xor 0x5c5c5c5c5c5c....5c
1768 The result is H(opad | H( ipad | msg ) )
1770 #define BLOCKSIZE 64
1771 #define DIGESTSIZE 32
1772 uint8_t k[BLOCKSIZE];
1773 uint8_t pad[BLOCKSIZE];
1774 uint8_t d[DIGESTSIZE];
1775 int i;
1776 SHA256_CTX st;
1778 tor_assert(key_len < INT_MAX);
1779 tor_assert(msg_len < INT_MAX);
1781 if (key_len <= BLOCKSIZE) {
1782 memset(k, 0, sizeof(k));
1783 memcpy(k, key, key_len); /* not time invariant in key_len */
1784 } else {
1785 SHA256((const uint8_t *)key, key_len, k);
1786 memset(k+DIGESTSIZE, 0, sizeof(k)-DIGESTSIZE);
1788 for (i = 0; i < BLOCKSIZE; ++i)
1789 pad[i] = k[i] ^ 0x36;
1790 SHA256_Init(&st);
1791 SHA256_Update(&st, pad, BLOCKSIZE);
1792 SHA256_Update(&st, (uint8_t*)msg, msg_len);
1793 SHA256_Final(d, &st);
1795 for (i = 0; i < BLOCKSIZE; ++i)
1796 pad[i] = k[i] ^ 0x5c;
1797 SHA256_Init(&st);
1798 SHA256_Update(&st, pad, BLOCKSIZE);
1799 SHA256_Update(&st, d, DIGESTSIZE);
1800 SHA256_Final((uint8_t*)hmac_out, &st);
1802 /* Now clear everything. */
1803 memset(k, 0, sizeof(k));
1804 memset(pad, 0, sizeof(pad));
1805 memset(d, 0, sizeof(d));
1806 memset(&st, 0, sizeof(st));
1807 #undef BLOCKSIZE
1808 #undef DIGESTSIZE
1809 #endif
1812 /* DH */
1814 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1815 static BIGNUM *dh_param_p = NULL;
1816 /** Shared P parameter for our TLS DH key exchanges. */
1817 static BIGNUM *dh_param_p_tls = NULL;
1818 /** Shared G parameter for our DH key exchanges. */
1819 static BIGNUM *dh_param_g = NULL;
1820 /** True if we use dynamic primes. */
1821 static int use_dynamic_primes = 0;
1823 /** Generate and return a reasonable and safe DH parameter p. */
1824 static BIGNUM *generate_rakshasa_prime(void)
1826 BIGNUM *rakshasa_prime, *misc;
1827 DH *dh_parameters;
1828 int r;
1829 int dh_codes;
1830 int rakshasa_bits = RAKSHASA_BITS;
1831 int generator = DH_GENERATOR;
1833 dh_parameters = DH_new();
1834 rakshasa_prime = BN_new();
1835 misc = BN_new();
1837 /** XXX - do we want to cache the result in a file? Or perhaps load from a file? */
1838 /* This implements the prime number strategy outlined in prop 179 */
1839 tor_assert(rakshasa_prime);
1840 log_notice(LD_OR, "Generating Rakshasa prime; this will take a while...");
1841 dh_parameters = DH_generate_parameters(rakshasa_bits, generator, NULL, NULL); // XXX Do we want a pretty call back?
1842 tor_assert(dh_parameters);
1843 log_notice(LD_OR, "Rakshasa prime generated!");
1844 log_notice(LD_OR, "Testing our Rakshasa prime; this will take a while...");
1845 r = DH_check(dh_parameters, &dh_codes);
1846 tor_assert(r);
1847 log_notice(LD_OR, "Rakshasa prime seems probabilistically reasonable!");
1848 misc = BN_copy(rakshasa_prime, dh_parameters->p);
1849 tor_assert(misc);
1850 DH_free(dh_parameters);
1852 return rakshasa_prime;
1855 /** Initialize dh_param_p and dh_param_g if they are not already
1856 * set. */
1857 static void
1858 init_dh_param(void)
1860 BIGNUM *rakshasa_prime, *p, *p2, *g;
1861 int r;
1862 if (dh_param_p && dh_param_g && dh_param_p_tls)
1863 return;
1865 rakshasa_prime = BN_new();
1866 p = BN_new();
1867 p2 = BN_new();
1868 g = BN_new();
1869 tor_assert(rakshasa_prime);
1870 tor_assert(p);
1871 tor_assert(p2);
1872 tor_assert(g);
1874 /* Set our generator for all DH parameters */
1875 r = BN_set_word(g, generator);
1876 tor_assert(r);
1878 /* This implements the prime number strategy outlined in prop 179 */
1879 if (use_dynamic_primes) {
1880 rakshasa_prime = generate_rakshasa_prime();
1883 /* This is from rfc2409, section 6.2. It's a safe prime, and
1884 supposedly it equals:
1885 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1887 r = BN_hex2bn(&p,
1888 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1889 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1890 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1891 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1892 "49286651ECE65381FFFFFFFFFFFFFFFF");
1893 tor_assert(r);
1894 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1895 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
1896 * prime.
1898 r = BN_hex2bn(&p2,
1899 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1900 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1901 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1902 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1903 "B0E7393E0F24218EB3");
1904 tor_assert(r);
1906 r = BN_set_word(g, 2);
1907 tor_assert(r);
1908 dh_param_p = p;
1909 if (rakshasa) {
1910 dh_param_p_tls = rakshasa_prime;
1911 } else {
1912 dh_param_p_tls = p2;
1914 dh_param_g = g;
1917 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
1918 * handshake. Since we exponentiate by this value, choosing a smaller one
1919 * lets our handhake go faster.
1921 #define DH_PRIVATE_KEY_BITS 320
1923 /** Allocate and return a new DH object for a key exchange.
1925 crypto_dh_env_t *
1926 crypto_dh_new(int dh_type)
1928 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1930 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
1931 dh_type == DH_TYPE_REND);
1933 if (!dh_param_p)
1934 init_dh_param();
1936 if (!(res->dh = DH_new()))
1937 goto err;
1939 if (dh_type == DH_TYPE_TLS) {
1940 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
1941 goto err;
1942 } else {
1943 if (!(res->dh->p = BN_dup(dh_param_p)))
1944 goto err;
1947 if (!(res->dh->g = BN_dup(dh_param_g)))
1948 goto err;
1950 res->dh->length = DH_PRIVATE_KEY_BITS;
1952 return res;
1953 err:
1954 crypto_log_errors(LOG_WARN, "creating DH object");
1955 if (res->dh) DH_free(res->dh); /* frees p and g too */
1956 tor_free(res);
1957 return NULL;
1960 /** Return the length of the DH key in <b>dh</b>, in bytes.
1963 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1965 tor_assert(dh);
1966 return DH_size(dh->dh);
1969 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1970 * success, -1 on failure.
1973 crypto_dh_generate_public(crypto_dh_env_t *dh)
1975 again:
1976 if (!DH_generate_key(dh->dh)) {
1977 crypto_log_errors(LOG_WARN, "generating DH key");
1978 return -1;
1980 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
1981 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1982 "the-universe chances really do happen. Trying again.");
1983 /* Free and clear the keys, so OpenSSL will actually try again. */
1984 BN_free(dh->dh->pub_key);
1985 BN_free(dh->dh->priv_key);
1986 dh->dh->pub_key = dh->dh->priv_key = NULL;
1987 goto again;
1989 return 0;
1992 /** Generate g^x as necessary, and write the g^x for the key exchange
1993 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1994 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1997 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1999 int bytes;
2000 tor_assert(dh);
2001 if (!dh->dh->pub_key) {
2002 if (crypto_dh_generate_public(dh)<0)
2003 return -1;
2006 tor_assert(dh->dh->pub_key);
2007 bytes = BN_num_bytes(dh->dh->pub_key);
2008 tor_assert(bytes >= 0);
2009 if (pubkey_len < (size_t)bytes) {
2010 log_warn(LD_CRYPTO,
2011 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2012 (int) pubkey_len, bytes);
2013 return -1;
2016 memset(pubkey, 0, pubkey_len);
2017 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
2019 return 0;
2022 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2023 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2024 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2026 static int
2027 tor_check_dh_key(int severity, BIGNUM *bn)
2029 BIGNUM *x;
2030 char *s;
2031 tor_assert(bn);
2032 x = BN_new();
2033 tor_assert(x);
2034 if (!dh_param_p)
2035 init_dh_param();
2036 BN_set_word(x, 1);
2037 if (BN_cmp(bn,x)<=0) {
2038 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
2039 goto err;
2041 BN_copy(x,dh_param_p);
2042 BN_sub_word(x, 1);
2043 if (BN_cmp(bn,x)>=0) {
2044 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
2045 goto err;
2047 BN_free(x);
2048 return 0;
2049 err:
2050 BN_free(x);
2051 s = BN_bn2hex(bn);
2052 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
2053 OPENSSL_free(s);
2054 return -1;
2057 #undef MIN
2058 #define MIN(a,b) ((a)<(b)?(a):(b))
2059 /** Given a DH key exchange object, and our peer's value of g^y (as a
2060 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2061 * <b>secret_bytes_out</b> bytes of shared key material and write them
2062 * to <b>secret_out</b>. Return the number of bytes generated on success,
2063 * or -1 on failure.
2065 * (We generate key material by computing
2066 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2067 * where || is concatenation.)
2069 ssize_t
2070 crypto_dh_compute_secret(int severity, crypto_dh_env_t *dh,
2071 const char *pubkey, size_t pubkey_len,
2072 char *secret_out, size_t secret_bytes_out)
2074 char *secret_tmp = NULL;
2075 BIGNUM *pubkey_bn = NULL;
2076 size_t secret_len=0, secret_tmp_len=0;
2077 int result=0;
2078 tor_assert(dh);
2079 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
2080 tor_assert(pubkey_len < INT_MAX);
2082 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
2083 (int)pubkey_len, NULL)))
2084 goto error;
2085 if (tor_check_dh_key(severity, pubkey_bn)<0) {
2086 /* Check for invalid public keys. */
2087 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
2088 goto error;
2090 secret_tmp_len = crypto_dh_get_bytes(dh);
2091 secret_tmp = tor_malloc(secret_tmp_len);
2092 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
2093 if (result < 0) {
2094 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
2095 goto error;
2097 secret_len = result;
2098 if (crypto_expand_key_material(secret_tmp, secret_len,
2099 secret_out, secret_bytes_out)<0)
2100 goto error;
2101 secret_len = secret_bytes_out;
2103 goto done;
2104 error:
2105 result = -1;
2106 done:
2107 crypto_log_errors(LOG_WARN, "completing DH handshake");
2108 if (pubkey_bn)
2109 BN_free(pubkey_bn);
2110 if (secret_tmp) {
2111 memset(secret_tmp, 0, secret_tmp_len);
2112 tor_free(secret_tmp);
2114 if (result < 0)
2115 return result;
2116 else
2117 return secret_len;
2120 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2121 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2122 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2123 * H(K | [00]) | H(K | [01]) | ....
2125 * Return 0 on success, -1 on failure.
2128 crypto_expand_key_material(const char *key_in, size_t key_in_len,
2129 char *key_out, size_t key_out_len)
2131 int i;
2132 char *cp, *tmp = tor_malloc(key_in_len+1);
2133 char digest[DIGEST_LEN];
2135 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2136 tor_assert(key_out_len <= DIGEST_LEN*256);
2138 memcpy(tmp, key_in, key_in_len);
2139 for (cp = key_out, i=0; cp < key_out+key_out_len;
2140 ++i, cp += DIGEST_LEN) {
2141 tmp[key_in_len] = i;
2142 if (crypto_digest(digest, tmp, key_in_len+1))
2143 goto err;
2144 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
2146 memset(tmp, 0, key_in_len+1);
2147 tor_free(tmp);
2148 memset(digest, 0, sizeof(digest));
2149 return 0;
2151 err:
2152 memset(tmp, 0, key_in_len+1);
2153 tor_free(tmp);
2154 memset(digest, 0, sizeof(digest));
2155 return -1;
2158 /** Free a DH key exchange object.
2160 void
2161 crypto_dh_free(crypto_dh_env_t *dh)
2163 if (!dh)
2164 return;
2165 tor_assert(dh->dh);
2166 DH_free(dh->dh);
2167 tor_free(dh);
2170 /* random numbers */
2172 /** How many bytes of entropy we add at once.
2174 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2175 * work for us too. */
2176 #define ADD_ENTROPY 32
2178 /** True iff we should use OpenSSL's RAND_poll function to add entropy to its
2179 * pool.
2181 * Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
2182 *"release".) */
2183 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
2185 /** True iff it's safe to use RAND_poll after setup.
2187 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2188 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2189 * that fd without checking whether it fit in the fd_set. Thus, if the
2190 * system has not just been started up, it is unsafe to call */
2191 #define RAND_POLL_IS_SAFE \
2192 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
2193 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
2194 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
2196 /** Set the seed of the weak RNG to a random value. */
2197 static void
2198 seed_weak_rng(void)
2200 unsigned seed;
2201 crypto_rand((void*)&seed, sizeof(seed));
2202 tor_init_weak_random(seed);
2205 /** Seed OpenSSL's random number generator with bytes from the operating
2206 * system. <b>startup</b> should be true iff we have just started Tor and
2207 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2210 crypto_seed_rng(int startup)
2212 int rand_poll_status = 0;
2214 /* local variables */
2215 #ifdef MS_WINDOWS
2216 unsigned char buf[ADD_ENTROPY];
2217 static int provider_set = 0;
2218 static HCRYPTPROV provider;
2219 #else
2220 char buf[ADD_ENTROPY];
2221 static const char *filenames[] = {
2222 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2224 int fd, i;
2225 size_t n;
2226 #endif
2228 #if HAVE_RAND_POLL
2229 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
2230 * entropy than we do. We'll try calling that, *and* calling our own entropy
2231 * functions. If one succeeds, we'll accept the RNG as seeded. */
2232 if (startup || RAND_POLL_IS_SAFE) {
2233 rand_poll_status = RAND_poll();
2234 if (rand_poll_status == 0)
2235 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2237 #endif
2239 #ifdef MS_WINDOWS
2240 if (!provider_set) {
2241 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2242 CRYPT_VERIFYCONTEXT)) {
2243 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
2244 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2245 return rand_poll_status ? 0 : -1;
2248 provider_set = 1;
2250 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
2251 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2252 return rand_poll_status ? 0 : -1;
2254 RAND_seed(buf, sizeof(buf));
2255 memset(buf, 0, sizeof(buf));
2256 seed_weak_rng();
2257 return 0;
2258 #else
2259 for (i = 0; filenames[i]; ++i) {
2260 fd = open(filenames[i], O_RDONLY, 0);
2261 if (fd<0) continue;
2262 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
2263 n = read_all(fd, buf, sizeof(buf), 0);
2264 close(fd);
2265 if (n != sizeof(buf)) {
2266 log_warn(LD_CRYPTO,
2267 "Error reading from entropy source (read only %lu bytes).",
2268 (unsigned long)n);
2269 return -1;
2271 RAND_seed(buf, (int)sizeof(buf));
2272 memset(buf, 0, sizeof(buf));
2273 seed_weak_rng();
2274 return 0;
2277 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
2278 return rand_poll_status ? 0 : -1;
2279 #endif
2282 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2283 * success, -1 on failure.
2286 crypto_rand(char *to, size_t n)
2288 int r;
2289 tor_assert(n < INT_MAX);
2290 tor_assert(to);
2291 r = RAND_bytes((unsigned char*)to, (int)n);
2292 if (r == 0)
2293 crypto_log_errors(LOG_WARN, "generating random data");
2294 return (r == 1) ? 0 : -1;
2297 /** Return a pseudorandom integer, chosen uniformly from the values
2298 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2299 * INT_MAX+1, inclusive. */
2301 crypto_rand_int(unsigned int max)
2303 unsigned int val;
2304 unsigned int cutoff;
2305 tor_assert(max <= ((unsigned int)INT_MAX)+1);
2306 tor_assert(max > 0); /* don't div by 0 */
2308 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2309 * distribution with clipping at the upper end of unsigned int's
2310 * range.
2312 cutoff = UINT_MAX - (UINT_MAX%max);
2313 while (1) {
2314 crypto_rand((char*)&val, sizeof(val));
2315 if (val < cutoff)
2316 return val % max;
2320 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2321 * between 0 and <b>max</b>-1. */
2322 uint64_t
2323 crypto_rand_uint64(uint64_t max)
2325 uint64_t val;
2326 uint64_t cutoff;
2327 tor_assert(max < UINT64_MAX);
2328 tor_assert(max > 0); /* don't div by 0 */
2330 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2331 * distribution with clipping at the upper end of unsigned int's
2332 * range.
2334 cutoff = UINT64_MAX - (UINT64_MAX%max);
2335 while (1) {
2336 crypto_rand((char*)&val, sizeof(val));
2337 if (val < cutoff)
2338 return val % max;
2342 /** Return a pseudorandom double d, chosen uniformly from the range
2343 * 0.0 <= d < 1.0.
2345 double
2346 crypto_rand_double(void)
2348 /* We just use an unsigned int here; we don't really care about getting
2349 * more than 32 bits of resolution */
2350 unsigned int uint;
2351 crypto_rand((char*)&uint, sizeof(uint));
2352 #if SIZEOF_INT == 4
2353 #define UINT_MAX_AS_DOUBLE 4294967296.0
2354 #elif SIZEOF_INT == 8
2355 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2356 #else
2357 #error SIZEOF_INT is neither 4 nor 8
2358 #endif
2359 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2362 /** Generate and return a new random hostname starting with <b>prefix</b>,
2363 * ending with <b>suffix</b>, and containing no less than
2364 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2365 * characters between. */
2366 char *
2367 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2368 const char *suffix)
2370 char *result, *rand_bytes;
2371 int randlen, rand_bytes_len;
2372 size_t resultlen, prefixlen;
2374 tor_assert(max_rand_len >= min_rand_len);
2375 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2376 prefixlen = strlen(prefix);
2377 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2379 rand_bytes_len = ((randlen*5)+7)/8;
2380 if (rand_bytes_len % 5)
2381 rand_bytes_len += 5 - (rand_bytes_len%5);
2382 rand_bytes = tor_malloc(rand_bytes_len);
2383 crypto_rand(rand_bytes, rand_bytes_len);
2385 result = tor_malloc(resultlen);
2386 memcpy(result, prefix, prefixlen);
2387 base32_encode(result+prefixlen, resultlen-prefixlen,
2388 rand_bytes, rand_bytes_len);
2389 tor_free(rand_bytes);
2390 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2392 return result;
2395 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2396 * is empty. */
2397 void *
2398 smartlist_choose(const smartlist_t *sl)
2400 int len = smartlist_len(sl);
2401 if (len)
2402 return smartlist_get(sl,crypto_rand_int(len));
2403 return NULL; /* no elements to choose from */
2406 /** Scramble the elements of <b>sl</b> into a random order. */
2407 void
2408 smartlist_shuffle(smartlist_t *sl)
2410 int i;
2411 /* From the end of the list to the front, choose at random from the
2412 positions we haven't looked at yet, and swap that position into the
2413 current position. Remember to give "no swap" the same probability as
2414 any other swap. */
2415 for (i = smartlist_len(sl)-1; i > 0; --i) {
2416 int j = crypto_rand_int(i+1);
2417 smartlist_swap(sl, i, j);
2421 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2422 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2423 * bytes. Return the number of bytes written on success; -1 if
2424 * destlen is too short, or other failure.
2427 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2429 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2430 * it ever shows up in the profile. */
2431 EVP_ENCODE_CTX ctx;
2432 int len, ret;
2433 tor_assert(srclen < INT_MAX);
2435 /* 48 bytes of input -> 64 bytes of output plus newline.
2436 Plus one more byte, in case I'm wrong.
2438 if (destlen < ((srclen/48)+1)*66)
2439 return -1;
2440 if (destlen > SIZE_T_CEILING)
2441 return -1;
2443 EVP_EncodeInit(&ctx);
2444 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2445 (unsigned char*)src, (int)srclen);
2446 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2447 ret += len;
2448 return ret;
2451 /** @{ */
2452 /** Special values used for the base64_decode_table */
2453 #define X 255
2454 #define SP 64
2455 #define PAD 65
2456 /** @} */
2457 /** Internal table mapping byte values to what they represent in base64.
2458 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2459 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2460 * end-of-string. */
2461 static const uint8_t base64_decode_table[256] = {
2462 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2463 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2464 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2465 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2466 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2467 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2468 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2469 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2470 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2471 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2472 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2473 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2474 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2475 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2476 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2477 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2480 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2481 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2482 * bytes. Return the number of bytes written on success; -1 if
2483 * destlen is too short, or other failure.
2485 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2486 * spaces or padding.
2488 * NOTE 2: This implementation does not check for the correct number of
2489 * padding "=" characters at the end of the string, and does not check
2490 * for internal padding characters.
2493 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2495 #ifdef USE_OPENSSL_BASE64
2496 EVP_ENCODE_CTX ctx;
2497 int len, ret;
2498 /* 64 bytes of input -> *up to* 48 bytes of output.
2499 Plus one more byte, in case I'm wrong.
2501 if (destlen < ((srclen/64)+1)*49)
2502 return -1;
2503 if (destlen > SIZE_T_CEILING)
2504 return -1;
2506 EVP_DecodeInit(&ctx);
2507 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2508 (unsigned char*)src, srclen);
2509 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2510 ret += len;
2511 return ret;
2512 #else
2513 const char *eos = src+srclen;
2514 uint32_t n=0;
2515 int n_idx=0;
2516 char *dest_orig = dest;
2518 /* Max number of bits == srclen*6.
2519 * Number of bytes required to hold all bits == (srclen*6)/8.
2520 * Yes, we want to round down: anything that hangs over the end of a
2521 * byte is padding. */
2522 if (destlen < (srclen*3)/4)
2523 return -1;
2524 if (destlen > SIZE_T_CEILING)
2525 return -1;
2527 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2528 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2529 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2531 for ( ; src < eos; ++src) {
2532 unsigned char c = (unsigned char) *src;
2533 uint8_t v = base64_decode_table[c];
2534 switch (v) {
2535 case X:
2536 /* This character isn't allowed in base64. */
2537 return -1;
2538 case SP:
2539 /* This character is whitespace, and has no effect. */
2540 continue;
2541 case PAD:
2542 /* We've hit an = character: the data is over. */
2543 goto end_of_loop;
2544 default:
2545 /* We have an actual 6-bit value. Append it to the bits in n. */
2546 n = (n<<6) | v;
2547 if ((++n_idx) == 4) {
2548 /* We've accumulated 24 bits in n. Flush them. */
2549 *dest++ = (n>>16);
2550 *dest++ = (n>>8) & 0xff;
2551 *dest++ = (n) & 0xff;
2552 n_idx = 0;
2553 n = 0;
2557 end_of_loop:
2558 /* If we have leftover bits, we need to cope. */
2559 switch (n_idx) {
2560 case 0:
2561 default:
2562 /* No leftover bits. We win. */
2563 break;
2564 case 1:
2565 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2566 return -1;
2567 case 2:
2568 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2569 *dest++ = n >> 4;
2570 break;
2571 case 3:
2572 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2573 *dest++ = n >> 10;
2574 *dest++ = n >> 2;
2577 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2578 tor_assert((dest-dest_orig) <= INT_MAX);
2580 return (int)(dest-dest_orig);
2581 #endif
2583 #undef X
2584 #undef SP
2585 #undef PAD
2587 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2588 * and newline characters, and store the nul-terminated result in the first
2589 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2591 digest_to_base64(char *d64, const char *digest)
2593 char buf[256];
2594 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2595 buf[BASE64_DIGEST_LEN] = '\0';
2596 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2597 return 0;
2600 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2601 * trailing newline or = characters), decode it and store the result in the
2602 * first DIGEST_LEN bytes at <b>digest</b>. */
2604 digest_from_base64(char *digest, const char *d64)
2606 #ifdef USE_OPENSSL_BASE64
2607 char buf_in[BASE64_DIGEST_LEN+3];
2608 char buf[256];
2609 if (strlen(d64) != BASE64_DIGEST_LEN)
2610 return -1;
2611 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2612 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2613 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2614 return -1;
2615 memcpy(digest, buf, DIGEST_LEN);
2616 return 0;
2617 #else
2618 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2619 return 0;
2620 else
2621 return -1;
2622 #endif
2625 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2626 * trailing = and newline characters, and store the nul-terminated result in
2627 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2629 digest256_to_base64(char *d64, const char *digest)
2631 char buf[256];
2632 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2633 buf[BASE64_DIGEST256_LEN] = '\0';
2634 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2635 return 0;
2638 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2639 * trailing newline or = characters), decode it and store the result in the
2640 * first DIGEST256_LEN bytes at <b>digest</b>. */
2642 digest256_from_base64(char *digest, const char *d64)
2644 #ifdef USE_OPENSSL_BASE64
2645 char buf_in[BASE64_DIGEST256_LEN+3];
2646 char buf[256];
2647 if (strlen(d64) != BASE64_DIGEST256_LEN)
2648 return -1;
2649 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2650 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2651 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2652 return -1;
2653 memcpy(digest, buf, DIGEST256_LEN);
2654 return 0;
2655 #else
2656 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2657 return 0;
2658 else
2659 return -1;
2660 #endif
2663 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2664 * that srclen*8 is a multiple of 5.
2666 void
2667 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2669 unsigned int i, v, u;
2670 size_t nbits = srclen * 8, bit;
2672 tor_assert(srclen < SIZE_T_CEILING/8);
2673 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2674 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2675 tor_assert(destlen < SIZE_T_CEILING);
2677 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2678 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2679 v = ((uint8_t)src[bit/8]) << 8;
2680 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2681 /* set u to the 5-bit value at the bit'th bit of src. */
2682 u = (v >> (11-(bit%8))) & 0x1F;
2683 dest[i] = BASE32_CHARS[u];
2685 dest[i] = '\0';
2688 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2689 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2692 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2694 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2695 * it ever shows up in the profile. */
2696 unsigned int i;
2697 size_t nbits, j, bit;
2698 char *tmp;
2699 nbits = srclen * 5;
2701 tor_assert(srclen < SIZE_T_CEILING / 5);
2702 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2703 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2704 tor_assert(destlen < SIZE_T_CEILING);
2706 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2707 tmp = tor_malloc_zero(srclen);
2708 for (j = 0; j < srclen; ++j) {
2709 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2710 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2711 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2712 else {
2713 log_warn(LD_BUG, "illegal character in base32 encoded string");
2714 tor_free(tmp);
2715 return -1;
2719 /* Assemble result byte-wise by applying five possible cases. */
2720 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2721 switch (bit % 40) {
2722 case 0:
2723 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2724 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2725 break;
2726 case 8:
2727 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2728 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2729 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2730 break;
2731 case 16:
2732 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2733 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2734 break;
2735 case 24:
2736 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2737 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2738 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2739 break;
2740 case 32:
2741 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2742 ((uint8_t)tmp[(bit/5)+1]);
2743 break;
2747 memset(tmp, 0, srclen);
2748 tor_free(tmp);
2749 tmp = NULL;
2750 return 0;
2753 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2754 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2755 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2756 * are a salt; the 9th byte describes how much iteration to do.
2757 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2759 void
2760 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2761 size_t secret_len, const char *s2k_specifier)
2763 crypto_digest_env_t *d;
2764 uint8_t c;
2765 size_t count, tmplen;
2766 char *tmp;
2767 tor_assert(key_out_len < SIZE_T_CEILING);
2769 #define EXPBIAS 6
2770 c = s2k_specifier[8];
2771 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2772 #undef EXPBIAS
2774 tor_assert(key_out_len <= DIGEST_LEN);
2776 d = crypto_new_digest_env();
2777 tmplen = 8+secret_len;
2778 tmp = tor_malloc(tmplen);
2779 memcpy(tmp,s2k_specifier,8);
2780 memcpy(tmp+8,secret,secret_len);
2781 secret_len += 8;
2782 while (count) {
2783 if (count >= secret_len) {
2784 crypto_digest_add_bytes(d, tmp, secret_len);
2785 count -= secret_len;
2786 } else {
2787 crypto_digest_add_bytes(d, tmp, count);
2788 count = 0;
2791 crypto_digest_get_digest(d, key_out, key_out_len);
2792 memset(tmp, 0, tmplen);
2793 tor_free(tmp);
2794 crypto_free_digest_env(d);
2797 #ifdef TOR_IS_MULTITHREADED
2798 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2799 static void
2800 _openssl_locking_cb(int mode, int n, const char *file, int line)
2802 (void)file;
2803 (void)line;
2804 if (!_openssl_mutexes)
2805 /* This is not a really good fix for the
2806 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2807 * it can't hurt. */
2808 return;
2809 if (mode & CRYPTO_LOCK)
2810 tor_mutex_acquire(_openssl_mutexes[n]);
2811 else
2812 tor_mutex_release(_openssl_mutexes[n]);
2815 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2816 * as a lock. */
2817 struct CRYPTO_dynlock_value {
2818 tor_mutex_t *lock;
2821 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2822 * documentation in OpenSSL's docs for more info. */
2823 static struct CRYPTO_dynlock_value *
2824 _openssl_dynlock_create_cb(const char *file, int line)
2826 struct CRYPTO_dynlock_value *v;
2827 (void)file;
2828 (void)line;
2829 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2830 v->lock = tor_mutex_new();
2831 return v;
2834 /** OpenSSL callback function to acquire or release a lock: see
2835 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2836 static void
2837 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2838 const char *file, int line)
2840 (void)file;
2841 (void)line;
2842 if (mode & CRYPTO_LOCK)
2843 tor_mutex_acquire(v->lock);
2844 else
2845 tor_mutex_release(v->lock);
2848 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2849 * documentation in OpenSSL's docs for more info. */
2850 static void
2851 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2852 const char *file, int line)
2854 (void)file;
2855 (void)line;
2856 tor_mutex_free(v->lock);
2857 tor_free(v);
2860 /** @{ */
2861 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2862 * multithreaded. */
2863 static int
2864 setup_openssl_threading(void)
2866 int i;
2867 int n = CRYPTO_num_locks();
2868 _n_openssl_mutexes = n;
2869 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2870 for (i=0; i < n; ++i)
2871 _openssl_mutexes[i] = tor_mutex_new();
2872 CRYPTO_set_locking_callback(_openssl_locking_cb);
2873 CRYPTO_set_id_callback(tor_get_thread_id);
2874 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2875 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2876 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2877 return 0;
2879 #else
2880 static int
2881 setup_openssl_threading(void)
2883 return 0;
2885 #endif
2886 /** @} */