sandbox: refactor string-based option-unchanged tests to use a macro
[tor.git] / src / common / crypto.c
bloba247a87d480d20c131f87b1f00cd6e19ece9fa4a
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-2013, 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 _WIN32
16 #ifndef _WIN32_WINNT
17 #define _WIN32_WINNT 0x0501
18 #endif
19 #define WIN32_LEAN_AND_MEAN
20 #include <windows.h>
21 #include <wincrypt.h>
22 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
23 * use either definition. */
24 #undef OCSP_RESPONSE
25 #endif
27 #include <openssl/err.h>
28 #include <openssl/rsa.h>
29 #include <openssl/pem.h>
30 #include <openssl/evp.h>
31 #include <openssl/engine.h>
32 #include <openssl/rand.h>
33 #include <openssl/opensslv.h>
34 #include <openssl/bn.h>
35 #include <openssl/dh.h>
36 #include <openssl/conf.h>
37 #include <openssl/hmac.h>
39 #ifdef HAVE_CTYPE_H
40 #include <ctype.h>
41 #endif
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 #ifdef HAVE_FCNTL_H
46 #include <fcntl.h>
47 #endif
48 #ifdef HAVE_SYS_FCNTL_H
49 #include <sys/fcntl.h>
50 #endif
52 #define CRYPTO_PRIVATE
53 #include "crypto.h"
54 #include "../common/torlog.h"
55 #include "aes.h"
56 #include "../common/util.h"
57 #include "container.h"
58 #include "compat.h"
59 #include "sandbox.h"
61 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
62 #error "We require OpenSSL >= 0.9.8"
63 #endif
65 #ifdef ANDROID
66 /* Android's OpenSSL seems to have removed all of its Engine support. */
67 #define DISABLE_ENGINES
68 #endif
70 /** Longest recognized */
71 #define MAX_DNS_LABEL_SIZE 63
73 /** Macro: is k a valid RSA public or private key? */
74 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
75 /** Macro: is k a valid RSA private key? */
76 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
78 #ifdef TOR_IS_MULTITHREADED
79 /** A number of preallocated mutexes for use by OpenSSL. */
80 static tor_mutex_t **openssl_mutexes_ = NULL;
81 /** How many mutexes have we allocated for use by OpenSSL? */
82 static int n_openssl_mutexes_ = 0;
83 #endif
85 /** A public key, or a public/private key-pair. */
86 struct crypto_pk_t
88 int refs; /**< reference count, so we don't have to copy keys */
89 RSA *key; /**< The key itself */
92 /** Key and stream information for a stream cipher. */
93 struct crypto_cipher_t
95 char key[CIPHER_KEY_LEN]; /**< The raw key. */
96 char iv[CIPHER_IV_LEN]; /**< The initial IV. */
97 aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
98 * encryption */
101 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
102 * while we're waiting for the second.*/
103 struct crypto_dh_t {
104 DH *dh; /**< The openssl DH object */
107 static int setup_openssl_threading(void);
108 static int tor_check_dh_key(int severity, BIGNUM *bn);
110 /** Return the number of bytes added by padding method <b>padding</b>.
112 static INLINE int
113 crypto_get_rsa_padding_overhead(int padding)
115 switch (padding)
117 case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
118 default: tor_assert(0); return -1;
122 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
124 static INLINE int
125 crypto_get_rsa_padding(int padding)
127 switch (padding)
129 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
130 default: tor_assert(0); return -1;
134 /** Boolean: has OpenSSL's crypto been initialized? */
135 static int crypto_early_initialized_ = 0;
137 /** Boolean: has OpenSSL's crypto been initialized? */
138 static int crypto_global_initialized_ = 0;
140 /** Log all pending crypto errors at level <b>severity</b>. Use
141 * <b>doing</b> to describe our current activities.
143 static void
144 crypto_log_errors(int severity, const char *doing)
146 unsigned long err;
147 const char *msg, *lib, *func;
148 while ((err = ERR_get_error()) != 0) {
149 msg = (const char*)ERR_reason_error_string(err);
150 lib = (const char*)ERR_lib_error_string(err);
151 func = (const char*)ERR_func_error_string(err);
152 if (!msg) msg = "(null)";
153 if (!lib) lib = "(null)";
154 if (!func) func = "(null)";
155 if (doing) {
156 tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
157 doing, msg, lib, func);
158 } else {
159 tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
160 msg, lib, func);
165 #ifndef DISABLE_ENGINES
166 /** Log any OpenSSL engines we're using at NOTICE. */
167 static void
168 log_engine(const char *fn, ENGINE *e)
170 if (e) {
171 const char *name, *id;
172 name = ENGINE_get_name(e);
173 id = ENGINE_get_id(e);
174 log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
175 fn, name?name:"?", id?id:"?");
176 } else {
177 log_info(LD_CRYPTO, "Using default implementation for %s", fn);
180 #endif
182 #ifndef DISABLE_ENGINES
183 /** Try to load an engine in a shared library via fully qualified path.
185 static ENGINE *
186 try_load_engine(const char *path, const char *engine)
188 ENGINE *e = ENGINE_by_id("dynamic");
189 if (e) {
190 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
191 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
192 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
193 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
194 ENGINE_free(e);
195 e = NULL;
198 return e;
200 #endif
202 /* Returns a trimmed and human-readable version of an openssl version string
203 * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
204 * May 2012' and this will parse them into a form similar to '1.0.0b' */
205 static char *
206 parse_openssl_version_str(const char *raw_version)
208 const char *end_of_version = NULL;
209 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
210 trim that down. */
211 if (!strcmpstart(raw_version, "OpenSSL ")) {
212 raw_version += strlen("OpenSSL ");
213 end_of_version = strchr(raw_version, ' ');
216 if (end_of_version)
217 return tor_strndup(raw_version,
218 end_of_version-raw_version);
219 else
220 return tor_strdup(raw_version);
223 static char *crypto_openssl_version_str = NULL;
224 /* Return a human-readable version of the run-time openssl version number. */
225 const char *
226 crypto_openssl_get_version_str(void)
228 if (crypto_openssl_version_str == NULL) {
229 const char *raw_version = SSLeay_version(SSLEAY_VERSION);
230 crypto_openssl_version_str = parse_openssl_version_str(raw_version);
232 return crypto_openssl_version_str;
235 static char *crypto_openssl_header_version_str = NULL;
236 /* Return a human-readable version of the compile-time openssl version
237 * number. */
238 const char *
239 crypto_openssl_get_header_version_str(void)
241 if (crypto_openssl_header_version_str == NULL) {
242 crypto_openssl_header_version_str =
243 parse_openssl_version_str(OPENSSL_VERSION_TEXT);
245 return crypto_openssl_header_version_str;
248 /** Make sure that openssl is using its default PRNG. Return 1 if we had to
249 * adjust it; 0 otherwise. */
250 static int
251 crypto_force_rand_ssleay(void)
253 if (RAND_get_rand_method() != RAND_SSLeay()) {
254 log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
255 "a replacement the OpenSSL RNG. Resetting it to the default "
256 "implementation.");
257 RAND_set_rand_method(RAND_SSLeay());
258 return 1;
260 return 0;
263 /** Set up the siphash key if we haven't already done so. */
265 crypto_init_siphash_key(void)
267 static int have_seeded_siphash = 0;
268 struct sipkey key;
269 if (have_seeded_siphash)
270 return 0;
272 if (crypto_rand((char*) &key, sizeof(key)) < 0)
273 return -1;
274 siphash_set_global_key(&key);
275 have_seeded_siphash = 1;
276 return 0;
279 /** Initialize the crypto library. Return 0 on success, -1 on failure.
282 crypto_early_init(void)
284 if (!crypto_early_initialized_) {
286 crypto_early_initialized_ = 1;
288 ERR_load_crypto_strings();
289 OpenSSL_add_all_algorithms();
291 setup_openssl_threading();
293 if (SSLeay() == OPENSSL_VERSION_NUMBER &&
294 !strcmp(SSLeay_version(SSLEAY_VERSION), OPENSSL_VERSION_TEXT)) {
295 log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
296 "(%lx: %s).", SSLeay(), SSLeay_version(SSLEAY_VERSION));
297 } else {
298 log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
299 "version we're running with. If you get weird crashes, that "
300 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
301 (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
302 SSLeay(), SSLeay_version(SSLEAY_VERSION));
305 if (SSLeay() < OPENSSL_V_SERIES(1,0,0)) {
306 log_notice(LD_CRYPTO,
307 "Your OpenSSL version seems to be %s. We recommend 1.0.0 "
308 "or later.",
309 crypto_openssl_get_version_str());
312 crypto_force_rand_ssleay();
314 if (crypto_seed_rng(1) < 0)
315 return -1;
316 if (crypto_init_siphash_key() < 0)
317 return -1;
319 return 0;
322 /** Initialize the crypto library. Return 0 on success, -1 on failure.
325 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
327 if (!crypto_global_initialized_) {
328 crypto_early_init();
330 crypto_global_initialized_ = 1;
332 if (useAccel > 0) {
333 #ifdef DISABLE_ENGINES
334 (void)accelName;
335 (void)accelDir;
336 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
337 #else
338 ENGINE *e = NULL;
340 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
341 ENGINE_load_builtin_engines();
342 ENGINE_register_all_complete();
344 if (accelName) {
345 if (accelDir) {
346 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
347 " via path \"%s\".", accelName, accelDir);
348 e = try_load_engine(accelName, accelDir);
349 } else {
350 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
351 " acceleration support.", accelName);
352 e = ENGINE_by_id(accelName);
354 if (!e) {
355 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
356 accelName);
357 } else {
358 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
359 accelName);
362 if (e) {
363 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
364 " setting default ciphers.");
365 ENGINE_set_default(e, ENGINE_METHOD_ALL);
367 /* Log, if available, the intersection of the set of algorithms
368 used by Tor and the set of algorithms available in the engine */
369 log_engine("RSA", ENGINE_get_default_RSA());
370 log_engine("DH", ENGINE_get_default_DH());
371 log_engine("ECDH", ENGINE_get_default_ECDH());
372 log_engine("ECDSA", ENGINE_get_default_ECDSA());
373 log_engine("RAND", ENGINE_get_default_RAND());
374 log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
375 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
376 log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
377 log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
378 log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
379 #ifdef NID_aes_128_ctr
380 log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
381 #endif
382 #ifdef NID_aes_128_gcm
383 log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
384 #endif
385 log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
386 #ifdef NID_aes_256_gcm
387 log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
388 #endif
390 #endif
391 } else {
392 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
395 if (crypto_force_rand_ssleay()) {
396 if (crypto_seed_rng(1) < 0)
397 return -1;
400 evaluate_evp_for_aes(-1);
401 evaluate_ctr_for_aes();
403 return 0;
406 /** Free crypto resources held by this thread. */
407 void
408 crypto_thread_cleanup(void)
410 ERR_remove_state(0);
413 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
414 crypto_pk_t *
415 crypto_new_pk_from_rsa_(RSA *rsa)
417 crypto_pk_t *env;
418 tor_assert(rsa);
419 env = tor_malloc(sizeof(crypto_pk_t));
420 env->refs = 1;
421 env->key = rsa;
422 return env;
425 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
426 * crypto_pk_t. */
427 RSA *
428 crypto_pk_get_rsa_(crypto_pk_t *env)
430 return env->key;
433 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
434 * private is set, include the private-key portion of the key. */
435 EVP_PKEY *
436 crypto_pk_get_evp_pkey_(crypto_pk_t *env, int private)
438 RSA *key = NULL;
439 EVP_PKEY *pkey = NULL;
440 tor_assert(env->key);
441 if (private) {
442 if (!(key = RSAPrivateKey_dup(env->key)))
443 goto error;
444 } else {
445 if (!(key = RSAPublicKey_dup(env->key)))
446 goto error;
448 if (!(pkey = EVP_PKEY_new()))
449 goto error;
450 if (!(EVP_PKEY_assign_RSA(pkey, key)))
451 goto error;
452 return pkey;
453 error:
454 if (pkey)
455 EVP_PKEY_free(pkey);
456 if (key)
457 RSA_free(key);
458 return NULL;
461 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
463 DH *
464 crypto_dh_get_dh_(crypto_dh_t *dh)
466 return dh->dh;
469 /** Allocate and return storage for a public key. The key itself will not yet
470 * be set.
472 crypto_pk_t *
473 crypto_pk_new(void)
475 RSA *rsa;
477 rsa = RSA_new();
478 tor_assert(rsa);
479 return crypto_new_pk_from_rsa_(rsa);
482 /** Release a reference to an asymmetric key; when all the references
483 * are released, free the key.
485 void
486 crypto_pk_free(crypto_pk_t *env)
488 if (!env)
489 return;
491 if (--env->refs > 0)
492 return;
493 tor_assert(env->refs == 0);
495 if (env->key)
496 RSA_free(env->key);
498 tor_free(env);
501 /** Allocate and return a new symmetric cipher using the provided key and iv.
502 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
503 * provide NULL in place of either one, it is generated at random.
505 crypto_cipher_t *
506 crypto_cipher_new_with_iv(const char *key, const char *iv)
508 crypto_cipher_t *env;
510 env = tor_malloc_zero(sizeof(crypto_cipher_t));
512 if (key == NULL)
513 crypto_rand(env->key, CIPHER_KEY_LEN);
514 else
515 memcpy(env->key, key, CIPHER_KEY_LEN);
516 if (iv == NULL)
517 crypto_rand(env->iv, CIPHER_IV_LEN);
518 else
519 memcpy(env->iv, iv, CIPHER_IV_LEN);
521 env->cipher = aes_new_cipher(env->key, env->iv);
523 return env;
526 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
527 * zero bytes. */
528 crypto_cipher_t *
529 crypto_cipher_new(const char *key)
531 char zeroiv[CIPHER_IV_LEN];
532 memset(zeroiv, 0, sizeof(zeroiv));
533 return crypto_cipher_new_with_iv(key, zeroiv);
536 /** Free a symmetric cipher.
538 void
539 crypto_cipher_free(crypto_cipher_t *env)
541 if (!env)
542 return;
544 tor_assert(env->cipher);
545 aes_cipher_free(env->cipher);
546 memwipe(env, 0, sizeof(crypto_cipher_t));
547 tor_free(env);
550 /* public key crypto */
552 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
553 * Return 0 on success, -1 on failure.
556 crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
558 tor_assert(env);
560 if (env->key)
561 RSA_free(env->key);
564 BIGNUM *e = BN_new();
565 RSA *r = NULL;
566 if (!e)
567 goto done;
568 if (! BN_set_word(e, 65537))
569 goto done;
570 r = RSA_new();
571 if (!r)
572 goto done;
573 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
574 goto done;
576 env->key = r;
577 r = NULL;
578 done:
579 if (e)
580 BN_clear_free(e);
581 if (r)
582 RSA_free(r);
585 if (!env->key) {
586 crypto_log_errors(LOG_WARN, "generating RSA key");
587 return -1;
590 return 0;
593 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
594 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
595 * the string is nul-terminated.
597 /* Used here, and used for testing. */
599 crypto_pk_read_private_key_from_string(crypto_pk_t *env,
600 const char *s, ssize_t len)
602 BIO *b;
604 tor_assert(env);
605 tor_assert(s);
606 tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
608 /* Create a read-only memory BIO, backed by the string 's' */
609 b = BIO_new_mem_buf((char*)s, (int)len);
610 if (!b)
611 return -1;
613 if (env->key)
614 RSA_free(env->key);
616 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
618 BIO_free(b);
620 if (!env->key) {
621 crypto_log_errors(LOG_WARN, "Error parsing private key");
622 return -1;
624 return 0;
627 /** Read a PEM-encoded private key from the file named by
628 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
631 crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
632 const char *keyfile)
634 char *contents;
635 int r;
637 /* Read the file into a string. */
638 contents = read_file_to_str(keyfile, 0, NULL);
639 if (!contents) {
640 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
641 return -1;
644 /* Try to parse it. */
645 r = crypto_pk_read_private_key_from_string(env, contents, -1);
646 memwipe(contents, 0, strlen(contents));
647 tor_free(contents);
648 if (r)
649 return -1; /* read_private_key_from_string already warned, so we don't.*/
651 /* Make sure it's valid. */
652 if (crypto_pk_check_key(env) <= 0)
653 return -1;
655 return 0;
658 /** Helper function to implement crypto_pk_write_*_key_to_string. */
659 static int
660 crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
661 size_t *len, int is_public)
663 BUF_MEM *buf;
664 BIO *b;
665 int r;
667 tor_assert(env);
668 tor_assert(env->key);
669 tor_assert(dest);
671 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
672 if (!b)
673 return -1;
675 /* Now you can treat b as if it were a file. Just use the
676 * PEM_*_bio_* functions instead of the non-bio variants.
678 if (is_public)
679 r = PEM_write_bio_RSAPublicKey(b, env->key);
680 else
681 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
683 if (!r) {
684 crypto_log_errors(LOG_WARN, "writing RSA key to string");
685 BIO_free(b);
686 return -1;
689 BIO_get_mem_ptr(b, &buf);
690 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
691 BIO_free(b);
693 *dest = tor_malloc(buf->length+1);
694 memcpy(*dest, buf->data, buf->length);
695 (*dest)[buf->length] = 0; /* nul terminate it */
696 *len = buf->length;
697 BUF_MEM_free(buf);
699 return 0;
702 /** PEM-encode the public key portion of <b>env</b> and write it to a
703 * newly allocated string. On success, set *<b>dest</b> to the new
704 * string, *<b>len</b> to the string's length, and return 0. On
705 * failure, return -1.
708 crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
709 size_t *len)
711 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
714 /** PEM-encode the private key portion of <b>env</b> and write it to a
715 * newly allocated string. On success, set *<b>dest</b> to the new
716 * string, *<b>len</b> to the string's length, and return 0. On
717 * failure, return -1.
720 crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
721 size_t *len)
723 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
726 /** Read a PEM-encoded public key from the first <b>len</b> characters of
727 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
728 * failure.
731 crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
732 size_t len)
734 BIO *b;
736 tor_assert(env);
737 tor_assert(src);
738 tor_assert(len<INT_MAX);
740 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
741 if (!b)
742 return -1;
744 BIO_write(b, src, (int)len);
746 if (env->key)
747 RSA_free(env->key);
748 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
749 BIO_free(b);
750 if (!env->key) {
751 crypto_log_errors(LOG_WARN, "reading public key from string");
752 return -1;
755 return 0;
758 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
759 * PEM-encoded. Return 0 on success, -1 on failure.
762 crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
763 const char *fname)
765 BIO *bio;
766 char *cp;
767 long len;
768 char *s;
769 int r;
771 tor_assert(PRIVATE_KEY_OK(env));
773 if (!(bio = BIO_new(BIO_s_mem())))
774 return -1;
775 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
776 == 0) {
777 crypto_log_errors(LOG_WARN, "writing private key");
778 BIO_free(bio);
779 return -1;
781 len = BIO_get_mem_data(bio, &cp);
782 tor_assert(len >= 0);
783 s = tor_malloc(len+1);
784 memcpy(s, cp, len);
785 s[len]='\0';
786 r = write_str_to_file(fname, s, 0);
787 BIO_free(bio);
788 memwipe(s, 0, strlen(s));
789 tor_free(s);
790 return r;
793 /** Return true iff <b>env</b> has a valid key.
796 crypto_pk_check_key(crypto_pk_t *env)
798 int r;
799 tor_assert(env);
801 r = RSA_check_key(env->key);
802 if (r <= 0)
803 crypto_log_errors(LOG_WARN,"checking RSA key");
804 return r;
807 /** Return true iff <b>key</b> contains the private-key portion of the RSA
808 * key. */
810 crypto_pk_key_is_private(const crypto_pk_t *key)
812 tor_assert(key);
813 return PRIVATE_KEY_OK(key);
816 /** Return true iff <b>env</b> contains a public key whose public exponent
817 * equals 65537.
820 crypto_pk_public_exponent_ok(crypto_pk_t *env)
822 tor_assert(env);
823 tor_assert(env->key);
825 return BN_is_word(env->key->e, 65537);
828 /** Compare the public-key components of a and b. Return less than 0
829 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
830 * considered to be less than all non-NULL keys, and equal to itself.
832 * Note that this may leak information about the keys through timing.
835 crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
837 int result;
838 char a_is_non_null = (a != NULL) && (a->key != NULL);
839 char b_is_non_null = (b != NULL) && (b->key != NULL);
840 char an_argument_is_null = !a_is_non_null | !b_is_non_null;
842 result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
843 if (an_argument_is_null)
844 return result;
846 tor_assert(PUBLIC_KEY_OK(a));
847 tor_assert(PUBLIC_KEY_OK(b));
848 result = BN_cmp((a->key)->n, (b->key)->n);
849 if (result)
850 return result;
851 return BN_cmp((a->key)->e, (b->key)->e);
854 /** Compare the public-key components of a and b. Return non-zero iff
855 * a==b. A NULL key is considered to be distinct from all non-NULL
856 * keys, and equal to itself.
858 * Note that this may leak information about the keys through timing.
861 crypto_pk_eq_keys(crypto_pk_t *a, crypto_pk_t *b)
863 return (crypto_pk_cmp_keys(a, b) == 0);
866 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
867 size_t
868 crypto_pk_keysize(crypto_pk_t *env)
870 tor_assert(env);
871 tor_assert(env->key);
873 return (size_t) RSA_size(env->key);
876 /** Return the size of the public key modulus of <b>env</b>, in bits. */
878 crypto_pk_num_bits(crypto_pk_t *env)
880 tor_assert(env);
881 tor_assert(env->key);
882 tor_assert(env->key->n);
884 return BN_num_bits(env->key->n);
887 /** Increase the reference count of <b>env</b>, and return it.
889 crypto_pk_t *
890 crypto_pk_dup_key(crypto_pk_t *env)
892 tor_assert(env);
893 tor_assert(env->key);
895 env->refs++;
896 return env;
899 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
900 crypto_pk_t *
901 crypto_pk_copy_full(crypto_pk_t *env)
903 RSA *new_key;
904 int privatekey = 0;
905 tor_assert(env);
906 tor_assert(env->key);
908 if (PRIVATE_KEY_OK(env)) {
909 new_key = RSAPrivateKey_dup(env->key);
910 privatekey = 1;
911 } else {
912 new_key = RSAPublicKey_dup(env->key);
914 if (!new_key) {
915 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
916 privatekey?"private":"public");
917 crypto_log_errors(LOG_ERR,
918 privatekey ? "Duplicating a private key" :
919 "Duplicating a public key");
920 tor_fragile_assert();
921 return NULL;
924 return crypto_new_pk_from_rsa_(new_key);
927 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
928 * in <b>env</b>, using the padding method <b>padding</b>. On success,
929 * write the result to <b>to</b>, and return the number of bytes
930 * written. On failure, return -1.
932 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
933 * at least the length of the modulus of <b>env</b>.
936 crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
937 const char *from, size_t fromlen, int padding)
939 int r;
940 tor_assert(env);
941 tor_assert(from);
942 tor_assert(to);
943 tor_assert(fromlen<INT_MAX);
944 tor_assert(tolen >= crypto_pk_keysize(env));
946 r = RSA_public_encrypt((int)fromlen,
947 (unsigned char*)from, (unsigned char*)to,
948 env->key, crypto_get_rsa_padding(padding));
949 if (r<0) {
950 crypto_log_errors(LOG_WARN, "performing RSA encryption");
951 return -1;
953 return r;
956 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
957 * in <b>env</b>, using the padding method <b>padding</b>. On success,
958 * write the result to <b>to</b>, and return the number of bytes
959 * written. On failure, return -1.
961 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
962 * at least the length of the modulus of <b>env</b>.
965 crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
966 size_t tolen,
967 const char *from, size_t fromlen,
968 int padding, int warnOnFailure)
970 int r;
971 tor_assert(env);
972 tor_assert(from);
973 tor_assert(to);
974 tor_assert(env->key);
975 tor_assert(fromlen<INT_MAX);
976 tor_assert(tolen >= crypto_pk_keysize(env));
977 if (!env->key->p)
978 /* Not a private key */
979 return -1;
981 r = RSA_private_decrypt((int)fromlen,
982 (unsigned char*)from, (unsigned char*)to,
983 env->key, crypto_get_rsa_padding(padding));
985 if (r<0) {
986 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
987 "performing RSA decryption");
988 return -1;
990 return r;
993 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
994 * public key in <b>env</b>, using PKCS1 padding. On success, write the
995 * signed data to <b>to</b>, and return the number of bytes written.
996 * On failure, return -1.
998 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
999 * at least the length of the modulus of <b>env</b>.
1002 crypto_pk_public_checksig(crypto_pk_t *env, char *to,
1003 size_t tolen,
1004 const char *from, size_t fromlen)
1006 int r;
1007 tor_assert(env);
1008 tor_assert(from);
1009 tor_assert(to);
1010 tor_assert(fromlen < INT_MAX);
1011 tor_assert(tolen >= crypto_pk_keysize(env));
1012 r = RSA_public_decrypt((int)fromlen,
1013 (unsigned char*)from, (unsigned char*)to,
1014 env->key, RSA_PKCS1_PADDING);
1016 if (r<0) {
1017 crypto_log_errors(LOG_WARN, "checking RSA signature");
1018 return -1;
1020 return r;
1023 /** Check a siglen-byte long signature at <b>sig</b> against
1024 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
1025 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
1026 * SHA1(data). Else return -1.
1029 crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
1030 size_t datalen, const char *sig, size_t siglen)
1032 char digest[DIGEST_LEN];
1033 char *buf;
1034 size_t buflen;
1035 int r;
1037 tor_assert(env);
1038 tor_assert(data);
1039 tor_assert(sig);
1040 tor_assert(datalen < SIZE_T_CEILING);
1041 tor_assert(siglen < SIZE_T_CEILING);
1043 if (crypto_digest(digest,data,datalen)<0) {
1044 log_warn(LD_BUG, "couldn't compute digest");
1045 return -1;
1047 buflen = crypto_pk_keysize(env);
1048 buf = tor_malloc(buflen);
1049 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
1050 if (r != DIGEST_LEN) {
1051 log_warn(LD_CRYPTO, "Invalid signature");
1052 tor_free(buf);
1053 return -1;
1055 if (tor_memneq(buf, digest, DIGEST_LEN)) {
1056 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
1057 tor_free(buf);
1058 return -1;
1060 tor_free(buf);
1062 return 0;
1065 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
1066 * <b>env</b>, using PKCS1 padding. On success, write the signature to
1067 * <b>to</b>, and return the number of bytes written. On failure, return
1068 * -1.
1070 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1071 * at least the length of the modulus of <b>env</b>.
1074 crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
1075 const char *from, size_t fromlen)
1077 int r;
1078 tor_assert(env);
1079 tor_assert(from);
1080 tor_assert(to);
1081 tor_assert(fromlen < INT_MAX);
1082 tor_assert(tolen >= crypto_pk_keysize(env));
1083 if (!env->key->p)
1084 /* Not a private key */
1085 return -1;
1087 r = RSA_private_encrypt((int)fromlen,
1088 (unsigned char*)from, (unsigned char*)to,
1089 env->key, RSA_PKCS1_PADDING);
1090 if (r<0) {
1091 crypto_log_errors(LOG_WARN, "generating RSA signature");
1092 return -1;
1094 return r;
1097 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1098 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1099 * store it in <b>to</b>. Return the number of bytes written on
1100 * success, and -1 on failure.
1102 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1103 * at least the length of the modulus of <b>env</b>.
1106 crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
1107 const char *from, size_t fromlen)
1109 int r;
1110 char digest[DIGEST_LEN];
1111 if (crypto_digest(digest,from,fromlen)<0)
1112 return -1;
1113 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
1114 memwipe(digest, 0, sizeof(digest));
1115 return r;
1118 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1119 * bytes of data from <b>from</b>, with padding type 'padding',
1120 * storing the results on <b>to</b>.
1122 * Returns the number of bytes written on success, -1 on failure.
1124 * The encrypted data consists of:
1125 * - The source data, padded and encrypted with the public key, if the
1126 * padded source data is no longer than the public key, and <b>force</b>
1127 * is false, OR
1128 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1129 * padded and encrypted with the public key; followed by the rest of
1130 * the source data encrypted in AES-CTR mode with the symmetric key.
1133 crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
1134 char *to, size_t tolen,
1135 const char *from,
1136 size_t fromlen,
1137 int padding, int force)
1139 int overhead, outlen, r;
1140 size_t pkeylen, symlen;
1141 crypto_cipher_t *cipher = NULL;
1142 char *buf = NULL;
1144 tor_assert(env);
1145 tor_assert(from);
1146 tor_assert(to);
1147 tor_assert(fromlen < SIZE_T_CEILING);
1149 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1150 pkeylen = crypto_pk_keysize(env);
1152 if (!force && fromlen+overhead <= pkeylen) {
1153 /* It all fits in a single encrypt. */
1154 return crypto_pk_public_encrypt(env,to,
1155 tolen,
1156 from,fromlen,padding);
1158 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1159 tor_assert(tolen >= pkeylen);
1161 cipher = crypto_cipher_new(NULL); /* generate a new key. */
1163 buf = tor_malloc(pkeylen+1);
1164 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1165 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1167 /* Length of symmetrically encrypted data. */
1168 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1170 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1171 if (outlen!=(int)pkeylen) {
1172 goto err;
1174 r = crypto_cipher_encrypt(cipher, to+outlen,
1175 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1177 if (r<0) goto err;
1178 memwipe(buf, 0, pkeylen);
1179 tor_free(buf);
1180 crypto_cipher_free(cipher);
1181 tor_assert(outlen+symlen < INT_MAX);
1182 return (int)(outlen + symlen);
1183 err:
1185 memwipe(buf, 0, pkeylen);
1186 tor_free(buf);
1187 crypto_cipher_free(cipher);
1188 return -1;
1191 /** Invert crypto_pk_public_hybrid_encrypt. */
1193 crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
1194 char *to,
1195 size_t tolen,
1196 const char *from,
1197 size_t fromlen,
1198 int padding, int warnOnFailure)
1200 int outlen, r;
1201 size_t pkeylen;
1202 crypto_cipher_t *cipher = NULL;
1203 char *buf = NULL;
1205 tor_assert(fromlen < SIZE_T_CEILING);
1206 pkeylen = crypto_pk_keysize(env);
1208 if (fromlen <= pkeylen) {
1209 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1210 warnOnFailure);
1213 buf = tor_malloc(pkeylen);
1214 outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
1215 warnOnFailure);
1216 if (outlen<0) {
1217 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1218 "Error decrypting public-key data");
1219 goto err;
1221 if (outlen < CIPHER_KEY_LEN) {
1222 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1223 "No room for a symmetric key");
1224 goto err;
1226 cipher = crypto_cipher_new(buf);
1227 if (!cipher) {
1228 goto err;
1230 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1231 outlen -= CIPHER_KEY_LEN;
1232 tor_assert(tolen - outlen >= fromlen - pkeylen);
1233 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1234 if (r<0)
1235 goto err;
1236 memwipe(buf,0,pkeylen);
1237 tor_free(buf);
1238 crypto_cipher_free(cipher);
1239 tor_assert(outlen + fromlen < INT_MAX);
1240 return (int)(outlen + (fromlen-pkeylen));
1241 err:
1242 memwipe(buf,0,pkeylen);
1243 tor_free(buf);
1244 crypto_cipher_free(cipher);
1245 return -1;
1248 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1249 * Return -1 on error, or the number of characters used on success.
1252 crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
1254 int len;
1255 unsigned char *buf = NULL;
1257 len = i2d_RSAPublicKey(pk->key, &buf);
1258 if (len < 0 || buf == NULL)
1259 return -1;
1261 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
1262 OPENSSL_free(buf);
1263 return -1;
1265 /* We don't encode directly into 'dest', because that would be illegal
1266 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1268 memcpy(dest,buf,len);
1269 OPENSSL_free(buf);
1270 return len;
1273 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1274 * success and NULL on failure.
1276 crypto_pk_t *
1277 crypto_pk_asn1_decode(const char *str, size_t len)
1279 RSA *rsa;
1280 unsigned char *buf;
1281 const unsigned char *cp;
1282 cp = buf = tor_malloc(len);
1283 memcpy(buf,str,len);
1284 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1285 tor_free(buf);
1286 if (!rsa) {
1287 crypto_log_errors(LOG_WARN,"decoding public key");
1288 return NULL;
1290 return crypto_new_pk_from_rsa_(rsa);
1293 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1294 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1295 * Return 0 on success, -1 on failure.
1298 crypto_pk_get_digest(crypto_pk_t *pk, char *digest_out)
1300 unsigned char *buf = NULL;
1301 int len;
1303 len = i2d_RSAPublicKey(pk->key, &buf);
1304 if (len < 0 || buf == NULL)
1305 return -1;
1306 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1307 OPENSSL_free(buf);
1308 return -1;
1310 OPENSSL_free(buf);
1311 return 0;
1314 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1315 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1317 crypto_pk_get_all_digests(crypto_pk_t *pk, digests_t *digests_out)
1319 unsigned char *buf = NULL;
1320 int len;
1322 len = i2d_RSAPublicKey(pk->key, &buf);
1323 if (len < 0 || buf == NULL)
1324 return -1;
1325 if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
1326 OPENSSL_free(buf);
1327 return -1;
1329 OPENSSL_free(buf);
1330 return 0;
1333 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1334 * every four spaces. */
1335 void
1336 crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
1338 int n = 0;
1339 char *end = out+outlen;
1340 tor_assert(outlen < SIZE_T_CEILING);
1342 while (*in && out<end) {
1343 *out++ = *in++;
1344 if (++n == 4 && *in && out<end) {
1345 n = 0;
1346 *out++ = ' ';
1349 tor_assert(out<end);
1350 *out = '\0';
1353 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1354 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1355 * space). Return 0 on success, -1 on failure.
1357 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1358 * of the public key, converted to hexadecimal, in upper case, with a
1359 * space after every four digits.
1361 * If <b>add_space</b> is false, omit the spaces.
1364 crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
1366 char digest[DIGEST_LEN];
1367 char hexdigest[HEX_DIGEST_LEN+1];
1368 if (crypto_pk_get_digest(pk, digest)) {
1369 return -1;
1371 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1372 if (add_space) {
1373 crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1374 } else {
1375 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1377 return 0;
1380 /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
1381 * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
1382 * bytes of space). Return 0 on success, -1 on failure.
1384 * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
1385 * of the ASN.1 encoding of the public key, converted to hexadecimal, in
1386 * upper case.
1389 crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
1391 char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
1392 if (crypto_pk_get_digest(pk, digest)) {
1393 return -1;
1395 if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
1396 return -1;
1398 base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
1399 return 0;
1402 /* symmetric crypto */
1404 /** Return a pointer to the key set for the cipher in <b>env</b>.
1406 const char *
1407 crypto_cipher_get_key(crypto_cipher_t *env)
1409 return env->key;
1412 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1413 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1414 * On failure, return -1.
1417 crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
1418 const char *from, size_t fromlen)
1420 tor_assert(env);
1421 tor_assert(env->cipher);
1422 tor_assert(from);
1423 tor_assert(fromlen);
1424 tor_assert(to);
1425 tor_assert(fromlen < SIZE_T_CEILING);
1427 aes_crypt(env->cipher, from, fromlen, to);
1428 return 0;
1431 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1432 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1433 * On failure, return -1.
1436 crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
1437 const char *from, size_t fromlen)
1439 tor_assert(env);
1440 tor_assert(from);
1441 tor_assert(to);
1442 tor_assert(fromlen < SIZE_T_CEILING);
1444 aes_crypt(env->cipher, from, fromlen, to);
1445 return 0;
1448 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1449 * on success, return 0. On failure, return -1.
1452 crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
1454 tor_assert(len < SIZE_T_CEILING);
1455 aes_crypt_inplace(env->cipher, buf, len);
1456 return 0;
1459 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1460 * <b>key</b> to the buffer in <b>to</b> of length
1461 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1462 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1463 * number of bytes written, on failure, return -1.
1466 crypto_cipher_encrypt_with_iv(const char *key,
1467 char *to, size_t tolen,
1468 const char *from, size_t fromlen)
1470 crypto_cipher_t *cipher;
1471 tor_assert(from);
1472 tor_assert(to);
1473 tor_assert(fromlen < INT_MAX);
1475 if (fromlen < 1)
1476 return -1;
1477 if (tolen < fromlen + CIPHER_IV_LEN)
1478 return -1;
1480 cipher = crypto_cipher_new_with_iv(key, NULL);
1482 memcpy(to, cipher->iv, CIPHER_IV_LEN);
1483 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1484 crypto_cipher_free(cipher);
1485 return (int)(fromlen + CIPHER_IV_LEN);
1488 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1489 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1490 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1491 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1492 * number of bytes written, on failure, return -1.
1495 crypto_cipher_decrypt_with_iv(const char *key,
1496 char *to, size_t tolen,
1497 const char *from, size_t fromlen)
1499 crypto_cipher_t *cipher;
1500 tor_assert(key);
1501 tor_assert(from);
1502 tor_assert(to);
1503 tor_assert(fromlen < INT_MAX);
1505 if (fromlen <= CIPHER_IV_LEN)
1506 return -1;
1507 if (tolen < fromlen - CIPHER_IV_LEN)
1508 return -1;
1510 cipher = crypto_cipher_new_with_iv(key, from);
1512 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1513 crypto_cipher_free(cipher);
1514 return (int)(fromlen - CIPHER_IV_LEN);
1517 /* SHA-1 */
1519 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1520 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1521 * Return 0 on success, -1 on failure.
1524 crypto_digest(char *digest, const char *m, size_t len)
1526 tor_assert(m);
1527 tor_assert(digest);
1528 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1531 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1532 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1533 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1535 crypto_digest256(char *digest, const char *m, size_t len,
1536 digest_algorithm_t algorithm)
1538 tor_assert(m);
1539 tor_assert(digest);
1540 tor_assert(algorithm == DIGEST_SHA256);
1541 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1544 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1545 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1546 * success, -1 on failure. */
1548 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1550 int i;
1551 tor_assert(ds_out);
1552 memset(ds_out, 0, sizeof(*ds_out));
1553 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1554 return -1;
1555 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1556 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1557 return -1;
1559 return 0;
1562 /** Return the name of an algorithm, as used in directory documents. */
1563 const char *
1564 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1566 switch (alg) {
1567 case DIGEST_SHA1:
1568 return "sha1";
1569 case DIGEST_SHA256:
1570 return "sha256";
1571 default:
1572 tor_fragile_assert();
1573 return "??unknown_digest??";
1577 /** Given the name of a digest algorithm, return its integer value, or -1 if
1578 * the name is not recognized. */
1580 crypto_digest_algorithm_parse_name(const char *name)
1582 if (!strcmp(name, "sha1"))
1583 return DIGEST_SHA1;
1584 else if (!strcmp(name, "sha256"))
1585 return DIGEST_SHA256;
1586 else
1587 return -1;
1590 /** Intermediate information about the digest of a stream of data. */
1591 struct crypto_digest_t {
1592 union {
1593 SHA_CTX sha1; /**< state for SHA1 */
1594 SHA256_CTX sha2; /**< state for SHA256 */
1595 } d; /**< State for the digest we're using. Only one member of the
1596 * union is usable, depending on the value of <b>algorithm</b>. */
1597 digest_algorithm_bitfield_t algorithm : 8; /**< Which algorithm is in use? */
1600 /** Allocate and return a new digest object to compute SHA1 digests.
1602 crypto_digest_t *
1603 crypto_digest_new(void)
1605 crypto_digest_t *r;
1606 r = tor_malloc(sizeof(crypto_digest_t));
1607 SHA1_Init(&r->d.sha1);
1608 r->algorithm = DIGEST_SHA1;
1609 return r;
1612 /** Allocate and return a new digest object to compute 256-bit digests
1613 * using <b>algorithm</b>. */
1614 crypto_digest_t *
1615 crypto_digest256_new(digest_algorithm_t algorithm)
1617 crypto_digest_t *r;
1618 tor_assert(algorithm == DIGEST_SHA256);
1619 r = tor_malloc(sizeof(crypto_digest_t));
1620 SHA256_Init(&r->d.sha2);
1621 r->algorithm = algorithm;
1622 return r;
1625 /** Deallocate a digest object.
1627 void
1628 crypto_digest_free(crypto_digest_t *digest)
1630 if (!digest)
1631 return;
1632 memwipe(digest, 0, sizeof(crypto_digest_t));
1633 tor_free(digest);
1636 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1638 void
1639 crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
1640 size_t len)
1642 tor_assert(digest);
1643 tor_assert(data);
1644 /* Using the SHA*_*() calls directly means we don't support doing
1645 * SHA in hardware. But so far the delay of getting the question
1646 * to the hardware, and hearing the answer, is likely higher than
1647 * just doing it ourselves. Hashes are fast.
1649 switch (digest->algorithm) {
1650 case DIGEST_SHA1:
1651 SHA1_Update(&digest->d.sha1, (void*)data, len);
1652 break;
1653 case DIGEST_SHA256:
1654 SHA256_Update(&digest->d.sha2, (void*)data, len);
1655 break;
1656 default:
1657 tor_fragile_assert();
1658 break;
1662 /** Compute the hash of the data that has been passed to the digest
1663 * object; write the first out_len bytes of the result to <b>out</b>.
1664 * <b>out_len</b> must be \<= DIGEST256_LEN.
1666 void
1667 crypto_digest_get_digest(crypto_digest_t *digest,
1668 char *out, size_t out_len)
1670 unsigned char r[DIGEST256_LEN];
1671 crypto_digest_t tmpenv;
1672 tor_assert(digest);
1673 tor_assert(out);
1674 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1675 memcpy(&tmpenv, digest, sizeof(crypto_digest_t));
1676 switch (digest->algorithm) {
1677 case DIGEST_SHA1:
1678 tor_assert(out_len <= DIGEST_LEN);
1679 SHA1_Final(r, &tmpenv.d.sha1);
1680 break;
1681 case DIGEST_SHA256:
1682 tor_assert(out_len <= DIGEST256_LEN);
1683 SHA256_Final(r, &tmpenv.d.sha2);
1684 break;
1685 default:
1686 log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
1687 /* If fragile_assert is not enabled, then we should at least not
1688 * leak anything. */
1689 memset(r, 0xff, sizeof(r));
1690 tor_fragile_assert();
1691 break;
1693 memcpy(out, r, out_len);
1694 memwipe(r, 0, sizeof(r));
1697 /** Allocate and return a new digest object with the same state as
1698 * <b>digest</b>
1700 crypto_digest_t *
1701 crypto_digest_dup(const crypto_digest_t *digest)
1703 crypto_digest_t *r;
1704 tor_assert(digest);
1705 r = tor_malloc(sizeof(crypto_digest_t));
1706 memcpy(r,digest,sizeof(crypto_digest_t));
1707 return r;
1710 /** Replace the state of the digest object <b>into</b> with the state
1711 * of the digest object <b>from</b>.
1713 void
1714 crypto_digest_assign(crypto_digest_t *into,
1715 const crypto_digest_t *from)
1717 tor_assert(into);
1718 tor_assert(from);
1719 memcpy(into,from,sizeof(crypto_digest_t));
1722 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1723 * at <b>digest_out</b> to the hash of the concatenation of those strings,
1724 * plus the optional string <b>append</b>, computed with the algorithm
1725 * <b>alg</b>.
1726 * <b>out_len</b> must be \<= DIGEST256_LEN. */
1727 void
1728 crypto_digest_smartlist(char *digest_out, size_t len_out,
1729 const smartlist_t *lst, const char *append,
1730 digest_algorithm_t alg)
1732 crypto_digest_t *d;
1733 if (alg == DIGEST_SHA1)
1734 d = crypto_digest_new();
1735 else
1736 d = crypto_digest256_new(alg);
1737 SMARTLIST_FOREACH(lst, const char *, cp,
1738 crypto_digest_add_bytes(d, cp, strlen(cp)));
1739 if (append)
1740 crypto_digest_add_bytes(d, append, strlen(append));
1741 crypto_digest_get_digest(d, digest_out, len_out);
1742 crypto_digest_free(d);
1745 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1746 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
1747 * result in <b>hmac_out</b>.
1749 void
1750 crypto_hmac_sha256(char *hmac_out,
1751 const char *key, size_t key_len,
1752 const char *msg, size_t msg_len)
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);
1761 /* DH */
1763 /** Our DH 'g' parameter */
1764 #define DH_GENERATOR 2
1766 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1767 static BIGNUM *dh_param_p = NULL;
1768 /** Shared P parameter for our TLS DH key exchanges. */
1769 static BIGNUM *dh_param_p_tls = NULL;
1770 /** Shared G parameter for our DH key exchanges. */
1771 static BIGNUM *dh_param_g = NULL;
1773 /** Generate and return a reasonable and safe DH parameter p. */
1774 static BIGNUM *
1775 crypto_generate_dynamic_dh_modulus(void)
1777 BIGNUM *dynamic_dh_modulus;
1778 DH *dh_parameters;
1779 int r, dh_codes;
1780 char *s;
1782 dynamic_dh_modulus = BN_new();
1783 tor_assert(dynamic_dh_modulus);
1785 dh_parameters = DH_generate_parameters(DH_BYTES*8, DH_GENERATOR, NULL, NULL);
1786 tor_assert(dh_parameters);
1788 r = DH_check(dh_parameters, &dh_codes);
1789 tor_assert(r && !dh_codes);
1791 BN_copy(dynamic_dh_modulus, dh_parameters->p);
1792 tor_assert(dynamic_dh_modulus);
1794 DH_free(dh_parameters);
1796 { /* log the dynamic DH modulus: */
1797 s = BN_bn2hex(dynamic_dh_modulus);
1798 tor_assert(s);
1799 log_info(LD_OR, "Dynamic DH modulus generated: [%s]", s);
1800 OPENSSL_free(s);
1803 return dynamic_dh_modulus;
1806 /** Store our dynamic DH modulus (and its group parameters) to
1807 <b>fname</b> for future use. */
1808 static int
1809 crypto_store_dynamic_dh_modulus(const char *fname)
1811 int len, new_len;
1812 DH *dh = NULL;
1813 unsigned char *dh_string_repr = NULL;
1814 char *base64_encoded_dh = NULL;
1815 char *file_string = NULL;
1816 int retval = -1;
1817 static const char file_header[] = "# This file contains stored Diffie-"
1818 "Hellman parameters for future use.\n# You *do not* need to edit this "
1819 "file.\n\n";
1821 tor_assert(fname);
1823 if (!dh_param_p_tls) {
1824 log_info(LD_CRYPTO, "Tried to store a DH modulus that does not exist.");
1825 goto done;
1828 if (!(dh = DH_new()))
1829 goto done;
1830 if (!(dh->p = BN_dup(dh_param_p_tls)))
1831 goto done;
1832 if (!(dh->g = BN_new()))
1833 goto done;
1834 if (!BN_set_word(dh->g, DH_GENERATOR))
1835 goto done;
1837 len = i2d_DHparams(dh, &dh_string_repr);
1838 if ((len < 0) || (dh_string_repr == NULL)) {
1839 log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (2).");
1840 goto done;
1843 base64_encoded_dh = tor_malloc_zero(len * 2); /* should be enough */
1844 new_len = base64_encode(base64_encoded_dh, len * 2,
1845 (char *)dh_string_repr, len);
1846 if (new_len < 0) {
1847 log_warn(LD_CRYPTO, "Error occured while base64-encoding DH modulus.");
1848 goto done;
1851 /* concatenate file header and the dh parameters blob */
1852 new_len = tor_asprintf(&file_string, "%s%s", file_header, base64_encoded_dh);
1854 /* write to file */
1855 if (write_bytes_to_new_file(fname, file_string, new_len, 0) < 0) {
1856 log_info(LD_CRYPTO, "'%s' was already occupied.", fname);
1857 goto done;
1860 retval = 0;
1862 done:
1863 if (dh)
1864 DH_free(dh);
1865 if (dh_string_repr)
1866 OPENSSL_free(dh_string_repr);
1867 tor_free(base64_encoded_dh);
1868 tor_free(file_string);
1870 return retval;
1873 /** Return the dynamic DH modulus stored in <b>fname</b>. If there is no
1874 dynamic DH modulus stored in <b>fname</b>, return NULL. */
1875 static BIGNUM *
1876 crypto_get_stored_dynamic_dh_modulus(const char *fname)
1878 int retval;
1879 char *contents = NULL;
1880 const char *contents_tmp = NULL;
1881 int dh_codes;
1882 DH *stored_dh = NULL;
1883 BIGNUM *dynamic_dh_modulus = NULL;
1884 int length = 0;
1885 unsigned char *base64_decoded_dh = NULL;
1886 const unsigned char *cp = NULL;
1888 tor_assert(fname);
1890 contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
1891 if (!contents) {
1892 log_info(LD_CRYPTO, "Could not open file '%s'", fname);
1893 goto done; /*usually means that ENOENT. don't try to move file to broken.*/
1896 /* skip the file header */
1897 contents_tmp = eat_whitespace(contents);
1898 if (!*contents_tmp) {
1899 log_warn(LD_CRYPTO, "Stored dynamic DH modulus file "
1900 "seems corrupted (eat_whitespace).");
1901 goto err;
1904 /* 'fname' contains the DH parameters stored in base64-ed DER
1905 * format. We are only interested in the DH modulus.
1906 * NOTE: We allocate more storage here than we need. Since we're already
1907 * doing that, we can also add 1 byte extra to appease Coverity's
1908 * scanner. */
1910 cp = base64_decoded_dh = tor_malloc_zero(strlen(contents_tmp) + 1);
1911 length = base64_decode((char *)base64_decoded_dh, strlen(contents_tmp),
1912 contents_tmp, strlen(contents_tmp));
1913 if (length < 0) {
1914 log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (base64).");
1915 goto err;
1918 stored_dh = d2i_DHparams(NULL, &cp, length);
1919 if ((!stored_dh) || (cp - base64_decoded_dh != length)) {
1920 log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (d2i).");
1921 goto err;
1924 { /* check the cryptographic qualities of the stored dynamic DH modulus: */
1925 retval = DH_check(stored_dh, &dh_codes);
1926 if (!retval || dh_codes) {
1927 log_warn(LD_CRYPTO, "Stored dynamic DH modulus is not a safe prime.");
1928 goto err;
1931 retval = DH_size(stored_dh);
1932 if (retval < DH_BYTES) {
1933 log_warn(LD_CRYPTO, "Stored dynamic DH modulus is smaller "
1934 "than '%d' bits.", DH_BYTES*8);
1935 goto err;
1938 if (!BN_is_word(stored_dh->g, 2)) {
1939 log_warn(LD_CRYPTO, "Stored dynamic DH parameters do not use '2' "
1940 "as the group generator.");
1941 goto err;
1945 { /* log the dynamic DH modulus: */
1946 char *s = BN_bn2hex(stored_dh->p);
1947 tor_assert(s);
1948 log_info(LD_OR, "Found stored dynamic DH modulus: [%s]", s);
1949 OPENSSL_free(s);
1952 goto done;
1954 err:
1957 /* move broken prime to $filename.broken */
1958 char *fname_new=NULL;
1959 tor_asprintf(&fname_new, "%s.broken", fname);
1961 log_warn(LD_CRYPTO, "Moving broken dynamic DH prime to '%s'.", fname_new);
1963 if (replace_file(fname, fname_new))
1964 log_notice(LD_CRYPTO, "Error while moving '%s' to '%s'.",
1965 fname, fname_new);
1967 tor_free(fname_new);
1970 if (stored_dh) {
1971 DH_free(stored_dh);
1972 stored_dh = NULL;
1975 done:
1976 tor_free(contents);
1977 tor_free(base64_decoded_dh);
1979 if (stored_dh) {
1980 dynamic_dh_modulus = BN_dup(stored_dh->p);
1981 DH_free(stored_dh);
1984 return dynamic_dh_modulus;
1987 /** Set the global TLS Diffie-Hellman modulus.
1988 * If <b>dynamic_dh_modulus_fname</b> is set, try to read a dynamic DH modulus
1989 * off it and use it as the DH modulus. If that's not possible,
1990 * generate a new dynamic DH modulus.
1991 * If <b>dynamic_dh_modulus_fname</b> is NULL, use the Apache mod_ssl DH
1992 * modulus. */
1993 void
1994 crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname)
1996 BIGNUM *tls_prime = NULL;
1997 int store_dh_prime_afterwards = 0;
1998 int r;
2000 /* If the space is occupied, free the previous TLS DH prime */
2001 if (dh_param_p_tls) {
2002 BN_clear_free(dh_param_p_tls);
2003 dh_param_p_tls = NULL;
2006 if (dynamic_dh_modulus_fname) { /* use dynamic DH modulus: */
2007 log_info(LD_OR, "Using stored dynamic DH modulus.");
2008 tls_prime = crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname);
2010 if (!tls_prime) {
2011 log_notice(LD_OR, "Generating fresh dynamic DH modulus. "
2012 "This might take a while...");
2013 tls_prime = crypto_generate_dynamic_dh_modulus();
2015 store_dh_prime_afterwards++;
2017 } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
2018 tls_prime = BN_new();
2019 tor_assert(tls_prime);
2021 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
2022 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
2023 * prime.
2025 r =BN_hex2bn(&tls_prime,
2026 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
2027 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
2028 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
2029 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
2030 "B0E7393E0F24218EB3");
2031 tor_assert(r);
2034 tor_assert(tls_prime);
2036 dh_param_p_tls = tls_prime;
2038 if (store_dh_prime_afterwards)
2039 /* save the new dynamic DH modulus to disk. */
2040 if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname)) {
2041 log_notice(LD_CRYPTO, "Failed while storing dynamic DH modulus. "
2042 "Make sure your data directory is sane.");
2046 /** Initialize dh_param_p and dh_param_g if they are not already
2047 * set. */
2048 static void
2049 init_dh_param(void)
2051 BIGNUM *circuit_dh_prime, *generator;
2052 int r;
2053 if (dh_param_p && dh_param_g)
2054 return;
2056 circuit_dh_prime = BN_new();
2057 generator = BN_new();
2058 tor_assert(circuit_dh_prime && generator);
2060 /* Set our generator for all DH parameters */
2061 r = BN_set_word(generator, DH_GENERATOR);
2062 tor_assert(r);
2064 /* This is from rfc2409, section 6.2. It's a safe prime, and
2065 supposedly it equals:
2066 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
2068 r = BN_hex2bn(&circuit_dh_prime,
2069 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
2070 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
2071 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
2072 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
2073 "49286651ECE65381FFFFFFFFFFFFFFFF");
2074 tor_assert(r);
2076 /* Set the new values as the global DH parameters. */
2077 dh_param_p = circuit_dh_prime;
2078 dh_param_g = generator;
2080 /* Ensure that we have TLS DH parameters set up, too, even if we're
2081 going to change them soon. */
2082 if (!dh_param_p_tls) {
2083 crypto_set_tls_dh_prime(NULL);
2087 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
2088 * handshake. Since we exponentiate by this value, choosing a smaller one
2089 * lets our handhake go faster.
2091 #define DH_PRIVATE_KEY_BITS 320
2093 /** Allocate and return a new DH object for a key exchange.
2095 crypto_dh_t *
2096 crypto_dh_new(int dh_type)
2098 crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
2100 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
2101 dh_type == DH_TYPE_REND);
2103 if (!dh_param_p)
2104 init_dh_param();
2106 if (!(res->dh = DH_new()))
2107 goto err;
2109 if (dh_type == DH_TYPE_TLS) {
2110 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
2111 goto err;
2112 } else {
2113 if (!(res->dh->p = BN_dup(dh_param_p)))
2114 goto err;
2117 if (!(res->dh->g = BN_dup(dh_param_g)))
2118 goto err;
2120 res->dh->length = DH_PRIVATE_KEY_BITS;
2122 return res;
2123 err:
2124 crypto_log_errors(LOG_WARN, "creating DH object");
2125 if (res->dh) DH_free(res->dh); /* frees p and g too */
2126 tor_free(res);
2127 return NULL;
2130 /** Return a copy of <b>dh</b>, sharing its internal state. */
2131 crypto_dh_t *
2132 crypto_dh_dup(const crypto_dh_t *dh)
2134 crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
2135 dh_new->dh = dh->dh;
2136 DH_up_ref(dh->dh);
2137 return dh_new;
2140 /** Return the length of the DH key in <b>dh</b>, in bytes.
2143 crypto_dh_get_bytes(crypto_dh_t *dh)
2145 tor_assert(dh);
2146 return DH_size(dh->dh);
2149 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2150 * success, -1 on failure.
2153 crypto_dh_generate_public(crypto_dh_t *dh)
2155 again:
2156 if (!DH_generate_key(dh->dh)) {
2157 crypto_log_errors(LOG_WARN, "generating DH key");
2158 return -1;
2160 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
2161 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
2162 "the-universe chances really do happen. Trying again.");
2163 /* Free and clear the keys, so OpenSSL will actually try again. */
2164 BN_clear_free(dh->dh->pub_key);
2165 BN_clear_free(dh->dh->priv_key);
2166 dh->dh->pub_key = dh->dh->priv_key = NULL;
2167 goto again;
2169 return 0;
2172 /** Generate g^x as necessary, and write the g^x for the key exchange
2173 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2174 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2177 crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
2179 int bytes;
2180 tor_assert(dh);
2181 if (!dh->dh->pub_key) {
2182 if (crypto_dh_generate_public(dh)<0)
2183 return -1;
2186 tor_assert(dh->dh->pub_key);
2187 bytes = BN_num_bytes(dh->dh->pub_key);
2188 tor_assert(bytes >= 0);
2189 if (pubkey_len < (size_t)bytes) {
2190 log_warn(LD_CRYPTO,
2191 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2192 (int) pubkey_len, bytes);
2193 return -1;
2196 memset(pubkey, 0, pubkey_len);
2197 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
2199 return 0;
2202 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2203 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2204 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2206 static int
2207 tor_check_dh_key(int severity, BIGNUM *bn)
2209 BIGNUM *x;
2210 char *s;
2211 tor_assert(bn);
2212 x = BN_new();
2213 tor_assert(x);
2214 if (!dh_param_p)
2215 init_dh_param();
2216 BN_set_word(x, 1);
2217 if (BN_cmp(bn,x)<=0) {
2218 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
2219 goto err;
2221 BN_copy(x,dh_param_p);
2222 BN_sub_word(x, 1);
2223 if (BN_cmp(bn,x)>=0) {
2224 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
2225 goto err;
2227 BN_clear_free(x);
2228 return 0;
2229 err:
2230 BN_clear_free(x);
2231 s = BN_bn2hex(bn);
2232 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
2233 OPENSSL_free(s);
2234 return -1;
2237 #undef MIN
2238 #define MIN(a,b) ((a)<(b)?(a):(b))
2239 /** Given a DH key exchange object, and our peer's value of g^y (as a
2240 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2241 * <b>secret_bytes_out</b> bytes of shared key material and write them
2242 * to <b>secret_out</b>. Return the number of bytes generated on success,
2243 * or -1 on failure.
2245 * (We generate key material by computing
2246 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2247 * where || is concatenation.)
2249 ssize_t
2250 crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
2251 const char *pubkey, size_t pubkey_len,
2252 char *secret_out, size_t secret_bytes_out)
2254 char *secret_tmp = NULL;
2255 BIGNUM *pubkey_bn = NULL;
2256 size_t secret_len=0, secret_tmp_len=0;
2257 int result=0;
2258 tor_assert(dh);
2259 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
2260 tor_assert(pubkey_len < INT_MAX);
2262 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
2263 (int)pubkey_len, NULL)))
2264 goto error;
2265 if (tor_check_dh_key(severity, pubkey_bn)<0) {
2266 /* Check for invalid public keys. */
2267 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
2268 goto error;
2270 secret_tmp_len = crypto_dh_get_bytes(dh);
2271 secret_tmp = tor_malloc(secret_tmp_len);
2272 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
2273 if (result < 0) {
2274 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
2275 goto error;
2277 secret_len = result;
2278 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
2279 (uint8_t*)secret_out, secret_bytes_out)<0)
2280 goto error;
2281 secret_len = secret_bytes_out;
2283 goto done;
2284 error:
2285 result = -1;
2286 done:
2287 crypto_log_errors(LOG_WARN, "completing DH handshake");
2288 if (pubkey_bn)
2289 BN_clear_free(pubkey_bn);
2290 if (secret_tmp) {
2291 memwipe(secret_tmp, 0, secret_tmp_len);
2292 tor_free(secret_tmp);
2294 if (result < 0)
2295 return result;
2296 else
2297 return secret_len;
2300 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2301 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2302 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2303 * H(K | [00]) | H(K | [01]) | ....
2305 * This is the key expansion algorithm used in the "TAP" circuit extension
2306 * mechanism; it shouldn't be used for new protocols.
2308 * Return 0 on success, -1 on failure.
2311 crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
2312 uint8_t *key_out, size_t key_out_len)
2314 int i;
2315 uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
2316 uint8_t digest[DIGEST_LEN];
2318 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2319 tor_assert(key_out_len <= DIGEST_LEN*256);
2321 memcpy(tmp, key_in, key_in_len);
2322 for (cp = key_out, i=0; cp < key_out+key_out_len;
2323 ++i, cp += DIGEST_LEN) {
2324 tmp[key_in_len] = i;
2325 if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
2326 goto err;
2327 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
2329 memwipe(tmp, 0, key_in_len+1);
2330 tor_free(tmp);
2331 memwipe(digest, 0, sizeof(digest));
2332 return 0;
2334 err:
2335 memwipe(tmp, 0, key_in_len+1);
2336 tor_free(tmp);
2337 memwipe(digest, 0, sizeof(digest));
2338 return -1;
2341 /** Expand some secret key material according to RFC5869, using SHA256 as the
2342 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2343 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2344 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2345 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2346 * bytes to <b>key_out</b> and return 0. On failure, return -1.
2349 crypto_expand_key_material_rfc5869_sha256(
2350 const uint8_t *key_in, size_t key_in_len,
2351 const uint8_t *salt_in, size_t salt_in_len,
2352 const uint8_t *info_in, size_t info_in_len,
2353 uint8_t *key_out, size_t key_out_len)
2355 uint8_t prk[DIGEST256_LEN];
2356 uint8_t tmp[DIGEST256_LEN + 128 + 1];
2357 uint8_t mac[DIGEST256_LEN];
2358 int i;
2359 uint8_t *outp;
2360 size_t tmp_len;
2362 crypto_hmac_sha256((char*)prk,
2363 (const char*)salt_in, salt_in_len,
2364 (const char*)key_in, key_in_len);
2366 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2367 tor_assert(key_out_len <= DIGEST256_LEN * 256);
2368 tor_assert(info_in_len <= 128);
2369 memset(tmp, 0, sizeof(tmp));
2370 outp = key_out;
2371 i = 1;
2373 while (key_out_len) {
2374 size_t n;
2375 if (i > 1) {
2376 memcpy(tmp, mac, DIGEST256_LEN);
2377 memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
2378 tmp[DIGEST256_LEN+info_in_len] = i;
2379 tmp_len = DIGEST256_LEN + info_in_len + 1;
2380 } else {
2381 memcpy(tmp, info_in, info_in_len);
2382 tmp[info_in_len] = i;
2383 tmp_len = info_in_len + 1;
2385 crypto_hmac_sha256((char*)mac,
2386 (const char*)prk, DIGEST256_LEN,
2387 (const char*)tmp, tmp_len);
2388 n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
2389 memcpy(outp, mac, n);
2390 key_out_len -= n;
2391 outp += n;
2392 ++i;
2395 memwipe(tmp, 0, sizeof(tmp));
2396 memwipe(mac, 0, sizeof(mac));
2397 return 0;
2400 /** Free a DH key exchange object.
2402 void
2403 crypto_dh_free(crypto_dh_t *dh)
2405 if (!dh)
2406 return;
2407 tor_assert(dh->dh);
2408 DH_free(dh->dh);
2409 tor_free(dh);
2412 /* random numbers */
2414 /** How many bytes of entropy we add at once.
2416 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2417 * work for us too. */
2418 #define ADD_ENTROPY 32
2420 /** True iff it's safe to use RAND_poll after setup.
2422 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2423 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2424 * that fd without checking whether it fit in the fd_set. Thus, if the
2425 * system has not just been started up, it is unsafe to call */
2426 #define RAND_POLL_IS_SAFE \
2427 (OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2429 /** Set the seed of the weak RNG to a random value. */
2430 void
2431 crypto_seed_weak_rng(tor_weak_rng_t *rng)
2433 unsigned seed;
2434 crypto_rand((void*)&seed, sizeof(seed));
2435 tor_init_weak_random(rng, seed);
2438 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2439 * storing it into <b>out</b>.
2442 crypto_strongest_rand(uint8_t *out, size_t out_len)
2444 #ifdef _WIN32
2445 static int provider_set = 0;
2446 static HCRYPTPROV provider;
2447 #else
2448 static const char *filenames[] = {
2449 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2451 int fd, i;
2452 size_t n;
2453 #endif
2455 #ifdef _WIN32
2456 if (!provider_set) {
2457 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2458 CRYPT_VERIFYCONTEXT)) {
2459 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
2460 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2461 return -1;
2464 provider_set = 1;
2466 if (!CryptGenRandom(provider, out_len, out)) {
2467 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2468 return -1;
2471 return 0;
2472 #else
2473 for (i = 0; filenames[i]; ++i) {
2474 log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
2475 fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
2476 if (fd<0) continue;
2477 log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
2478 n = read_all(fd, (char*)out, out_len, 0);
2479 close(fd);
2480 if (n != out_len) {
2481 log_warn(LD_CRYPTO,
2482 "Error reading from entropy source (read only %lu bytes).",
2483 (unsigned long)n);
2484 return -1;
2487 return 0;
2490 log_warn(LD_CRYPTO, "Cannot get strong entropy: no entropy source found.");
2491 return -1;
2492 #endif
2495 /** Seed OpenSSL's random number generator with bytes from the operating
2496 * system. <b>startup</b> should be true iff we have just started Tor and
2497 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2500 crypto_seed_rng(int startup)
2502 int rand_poll_ok = 0, load_entropy_ok = 0;
2503 uint8_t buf[ADD_ENTROPY];
2505 /* OpenSSL has a RAND_poll function that knows about more kinds of
2506 * entropy than we do. We'll try calling that, *and* calling our own entropy
2507 * functions. If one succeeds, we'll accept the RNG as seeded. */
2508 if (startup || RAND_POLL_IS_SAFE) {
2509 rand_poll_ok = RAND_poll();
2510 if (rand_poll_ok == 0)
2511 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2514 load_entropy_ok = !crypto_strongest_rand(buf, sizeof(buf));
2515 if (load_entropy_ok) {
2516 RAND_seed(buf, sizeof(buf));
2519 memwipe(buf, 0, sizeof(buf));
2521 if (rand_poll_ok || load_entropy_ok)
2522 return 0;
2523 else
2524 return -1;
2527 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2528 * success, -1 on failure.
2530 MOCK_IMPL(int,
2531 crypto_rand, (char *to, size_t n))
2533 int r;
2534 tor_assert(n < INT_MAX);
2535 tor_assert(to);
2536 r = RAND_bytes((unsigned char*)to, (int)n);
2537 if (r == 0)
2538 crypto_log_errors(LOG_WARN, "generating random data");
2539 return (r == 1) ? 0 : -1;
2542 /** Return a pseudorandom integer, chosen uniformly from the values
2543 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2544 * INT_MAX+1, inclusive. */
2546 crypto_rand_int(unsigned int max)
2548 unsigned int val;
2549 unsigned int cutoff;
2550 tor_assert(max <= ((unsigned int)INT_MAX)+1);
2551 tor_assert(max > 0); /* don't div by 0 */
2553 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2554 * distribution with clipping at the upper end of unsigned int's
2555 * range.
2557 cutoff = UINT_MAX - (UINT_MAX%max);
2558 while (1) {
2559 crypto_rand((char*)&val, sizeof(val));
2560 if (val < cutoff)
2561 return val % max;
2565 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2566 * between 0 and <b>max</b>-1. */
2567 uint64_t
2568 crypto_rand_uint64(uint64_t max)
2570 uint64_t val;
2571 uint64_t cutoff;
2572 tor_assert(max < UINT64_MAX);
2573 tor_assert(max > 0); /* don't div by 0 */
2575 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2576 * distribution with clipping at the upper end of unsigned int's
2577 * range.
2579 cutoff = UINT64_MAX - (UINT64_MAX%max);
2580 while (1) {
2581 crypto_rand((char*)&val, sizeof(val));
2582 if (val < cutoff)
2583 return val % max;
2587 /** Return a pseudorandom double d, chosen uniformly from the range
2588 * 0.0 <= d < 1.0.
2590 double
2591 crypto_rand_double(void)
2593 /* We just use an unsigned int here; we don't really care about getting
2594 * more than 32 bits of resolution */
2595 unsigned int uint;
2596 crypto_rand((char*)&uint, sizeof(uint));
2597 #if SIZEOF_INT == 4
2598 #define UINT_MAX_AS_DOUBLE 4294967296.0
2599 #elif SIZEOF_INT == 8
2600 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2601 #else
2602 #error SIZEOF_INT is neither 4 nor 8
2603 #endif
2604 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2607 /** Generate and return a new random hostname starting with <b>prefix</b>,
2608 * ending with <b>suffix</b>, and containing no fewer than
2609 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2610 * characters between.
2612 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2614 char *
2615 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2616 const char *suffix)
2618 char *result, *rand_bytes;
2619 int randlen, rand_bytes_len;
2620 size_t resultlen, prefixlen;
2622 if (max_rand_len > MAX_DNS_LABEL_SIZE)
2623 max_rand_len = MAX_DNS_LABEL_SIZE;
2624 if (min_rand_len > max_rand_len)
2625 min_rand_len = max_rand_len;
2627 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2629 prefixlen = strlen(prefix);
2630 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2632 rand_bytes_len = ((randlen*5)+7)/8;
2633 if (rand_bytes_len % 5)
2634 rand_bytes_len += 5 - (rand_bytes_len%5);
2635 rand_bytes = tor_malloc(rand_bytes_len);
2636 crypto_rand(rand_bytes, rand_bytes_len);
2638 result = tor_malloc(resultlen);
2639 memcpy(result, prefix, prefixlen);
2640 base32_encode(result+prefixlen, resultlen-prefixlen,
2641 rand_bytes, rand_bytes_len);
2642 tor_free(rand_bytes);
2643 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2645 return result;
2648 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2649 * is empty. */
2650 void *
2651 smartlist_choose(const smartlist_t *sl)
2653 int len = smartlist_len(sl);
2654 if (len)
2655 return smartlist_get(sl,crypto_rand_int(len));
2656 return NULL; /* no elements to choose from */
2659 /** Scramble the elements of <b>sl</b> into a random order. */
2660 void
2661 smartlist_shuffle(smartlist_t *sl)
2663 int i;
2664 /* From the end of the list to the front, choose at random from the
2665 positions we haven't looked at yet, and swap that position into the
2666 current position. Remember to give "no swap" the same probability as
2667 any other swap. */
2668 for (i = smartlist_len(sl)-1; i > 0; --i) {
2669 int j = crypto_rand_int(i+1);
2670 smartlist_swap(sl, i, j);
2674 /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2675 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2676 * bytes. Return the number of bytes written on success; -1 if
2677 * destlen is too short, or other failure.
2680 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2682 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2683 * it ever shows up in the profile. */
2684 EVP_ENCODE_CTX ctx;
2685 int len, ret;
2686 tor_assert(srclen < INT_MAX);
2688 /* 48 bytes of input -> 64 bytes of output plus newline.
2689 Plus one more byte, in case I'm wrong.
2691 if (destlen < ((srclen/48)+1)*66)
2692 return -1;
2693 if (destlen > SIZE_T_CEILING)
2694 return -1;
2696 EVP_EncodeInit(&ctx);
2697 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2698 (unsigned char*)src, (int)srclen);
2699 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2700 ret += len;
2701 return ret;
2704 /** @{ */
2705 /** Special values used for the base64_decode_table */
2706 #define X 255
2707 #define SP 64
2708 #define PAD 65
2709 /** @} */
2710 /** Internal table mapping byte values to what they represent in base64.
2711 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2712 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2713 * end-of-string. */
2714 static const uint8_t base64_decode_table[256] = {
2715 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2716 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2717 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2718 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2719 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2720 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2721 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2722 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2723 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2724 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2725 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2726 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2727 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2728 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2729 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2730 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2733 /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2734 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2735 * bytes. Return the number of bytes written on success; -1 if
2736 * destlen is too short, or other failure.
2738 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2739 * spaces or padding.
2741 * NOTE 2: This implementation does not check for the correct number of
2742 * padding "=" characters at the end of the string, and does not check
2743 * for internal padding characters.
2746 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2748 #ifdef USE_OPENSSL_BASE64
2749 EVP_ENCODE_CTX ctx;
2750 int len, ret;
2751 /* 64 bytes of input -> *up to* 48 bytes of output.
2752 Plus one more byte, in case I'm wrong.
2754 if (destlen < ((srclen/64)+1)*49)
2755 return -1;
2756 if (destlen > SIZE_T_CEILING)
2757 return -1;
2759 EVP_DecodeInit(&ctx);
2760 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2761 (unsigned char*)src, srclen);
2762 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2763 ret += len;
2764 return ret;
2765 #else
2766 const char *eos = src+srclen;
2767 uint32_t n=0;
2768 int n_idx=0;
2769 char *dest_orig = dest;
2771 /* Max number of bits == srclen*6.
2772 * Number of bytes required to hold all bits == (srclen*6)/8.
2773 * Yes, we want to round down: anything that hangs over the end of a
2774 * byte is padding. */
2775 if (destlen < (srclen*3)/4)
2776 return -1;
2777 if (destlen > SIZE_T_CEILING)
2778 return -1;
2780 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2781 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2782 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2784 for ( ; src < eos; ++src) {
2785 unsigned char c = (unsigned char) *src;
2786 uint8_t v = base64_decode_table[c];
2787 switch (v) {
2788 case X:
2789 /* This character isn't allowed in base64. */
2790 return -1;
2791 case SP:
2792 /* This character is whitespace, and has no effect. */
2793 continue;
2794 case PAD:
2795 /* We've hit an = character: the data is over. */
2796 goto end_of_loop;
2797 default:
2798 /* We have an actual 6-bit value. Append it to the bits in n. */
2799 n = (n<<6) | v;
2800 if ((++n_idx) == 4) {
2801 /* We've accumulated 24 bits in n. Flush them. */
2802 *dest++ = (n>>16);
2803 *dest++ = (n>>8) & 0xff;
2804 *dest++ = (n) & 0xff;
2805 n_idx = 0;
2806 n = 0;
2810 end_of_loop:
2811 /* If we have leftover bits, we need to cope. */
2812 switch (n_idx) {
2813 case 0:
2814 default:
2815 /* No leftover bits. We win. */
2816 break;
2817 case 1:
2818 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2819 return -1;
2820 case 2:
2821 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2822 *dest++ = n >> 4;
2823 break;
2824 case 3:
2825 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2826 *dest++ = n >> 10;
2827 *dest++ = n >> 2;
2830 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2831 tor_assert((dest-dest_orig) <= INT_MAX);
2833 return (int)(dest-dest_orig);
2834 #endif
2836 #undef X
2837 #undef SP
2838 #undef PAD
2840 /** Base64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2841 * and newline characters, and store the nul-terminated result in the first
2842 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2844 digest_to_base64(char *d64, const char *digest)
2846 char buf[256];
2847 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2848 buf[BASE64_DIGEST_LEN] = '\0';
2849 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2850 return 0;
2853 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2854 * trailing newline or = characters), decode it and store the result in the
2855 * first DIGEST_LEN bytes at <b>digest</b>. */
2857 digest_from_base64(char *digest, const char *d64)
2859 #ifdef USE_OPENSSL_BASE64
2860 char buf_in[BASE64_DIGEST_LEN+3];
2861 char buf[256];
2862 if (strlen(d64) != BASE64_DIGEST_LEN)
2863 return -1;
2864 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2865 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2866 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2867 return -1;
2868 memcpy(digest, buf, DIGEST_LEN);
2869 return 0;
2870 #else
2871 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2872 return 0;
2873 else
2874 return -1;
2875 #endif
2878 /** Base64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2879 * trailing = and newline characters, and store the nul-terminated result in
2880 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2882 digest256_to_base64(char *d64, const char *digest)
2884 char buf[256];
2885 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2886 buf[BASE64_DIGEST256_LEN] = '\0';
2887 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2888 return 0;
2891 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2892 * trailing newline or = characters), decode it and store the result in the
2893 * first DIGEST256_LEN bytes at <b>digest</b>. */
2895 digest256_from_base64(char *digest, const char *d64)
2897 #ifdef USE_OPENSSL_BASE64
2898 char buf_in[BASE64_DIGEST256_LEN+3];
2899 char buf[256];
2900 if (strlen(d64) != BASE64_DIGEST256_LEN)
2901 return -1;
2902 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2903 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2904 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2905 return -1;
2906 memcpy(digest, buf, DIGEST256_LEN);
2907 return 0;
2908 #else
2909 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2910 return 0;
2911 else
2912 return -1;
2913 #endif
2916 /** Implements base32 encoding as in RFC 4648. Limitation: Requires
2917 * that srclen*8 is a multiple of 5.
2919 void
2920 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2922 unsigned int i, v, u;
2923 size_t nbits = srclen * 8, bit;
2925 tor_assert(srclen < SIZE_T_CEILING/8);
2926 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2927 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2928 tor_assert(destlen < SIZE_T_CEILING);
2930 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2931 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2932 v = ((uint8_t)src[bit/8]) << 8;
2933 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2934 /* set u to the 5-bit value at the bit'th bit of src. */
2935 u = (v >> (11-(bit%8))) & 0x1F;
2936 dest[i] = BASE32_CHARS[u];
2938 dest[i] = '\0';
2941 /** Implements base32 decoding as in RFC 4648. Limitation: Requires
2942 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2945 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2947 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2948 * it ever shows up in the profile. */
2949 unsigned int i;
2950 size_t nbits, j, bit;
2951 char *tmp;
2952 nbits = srclen * 5;
2954 tor_assert(srclen < SIZE_T_CEILING / 5);
2955 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2956 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2957 tor_assert(destlen < SIZE_T_CEILING);
2959 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2960 tmp = tor_malloc_zero(srclen);
2961 for (j = 0; j < srclen; ++j) {
2962 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2963 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2964 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2965 else {
2966 log_warn(LD_BUG, "illegal character in base32 encoded string");
2967 tor_free(tmp);
2968 return -1;
2972 /* Assemble result byte-wise by applying five possible cases. */
2973 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2974 switch (bit % 40) {
2975 case 0:
2976 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2977 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2978 break;
2979 case 8:
2980 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2981 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2982 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2983 break;
2984 case 16:
2985 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2986 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2987 break;
2988 case 24:
2989 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2990 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2991 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2992 break;
2993 case 32:
2994 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2995 ((uint8_t)tmp[(bit/5)+1]);
2996 break;
3000 memwipe(tmp, 0, srclen);
3001 tor_free(tmp);
3002 tmp = NULL;
3003 return 0;
3006 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
3007 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
3008 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
3009 * are a salt; the 9th byte describes how much iteration to do.
3010 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
3012 void
3013 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
3014 size_t secret_len, const char *s2k_specifier)
3016 crypto_digest_t *d;
3017 uint8_t c;
3018 size_t count, tmplen;
3019 char *tmp;
3020 tor_assert(key_out_len < SIZE_T_CEILING);
3022 #define EXPBIAS 6
3023 c = s2k_specifier[8];
3024 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
3025 #undef EXPBIAS
3027 tor_assert(key_out_len <= DIGEST_LEN);
3029 d = crypto_digest_new();
3030 tmplen = 8+secret_len;
3031 tmp = tor_malloc(tmplen);
3032 memcpy(tmp,s2k_specifier,8);
3033 memcpy(tmp+8,secret,secret_len);
3034 secret_len += 8;
3035 while (count) {
3036 if (count >= secret_len) {
3037 crypto_digest_add_bytes(d, tmp, secret_len);
3038 count -= secret_len;
3039 } else {
3040 crypto_digest_add_bytes(d, tmp, count);
3041 count = 0;
3044 crypto_digest_get_digest(d, key_out, key_out_len);
3045 memwipe(tmp, 0, tmplen);
3046 tor_free(tmp);
3047 crypto_digest_free(d);
3051 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
3052 * the value <b>byte</b>.
3054 * This function is preferable to memset, since many compilers will happily
3055 * optimize out memset() when they can convince themselves that the data being
3056 * cleared will never be read.
3058 * Right now, our convention is to use this function when we are wiping data
3059 * that's about to become inaccessible, such as stack buffers that are about
3060 * to go out of scope or structures that are about to get freed. (In
3061 * practice, it appears that the compilers we're currently using will optimize
3062 * out the memset()s for stack-allocated buffers, but not those for
3063 * about-to-be-freed structures. That could change, though, so we're being
3064 * wary.) If there are live reads for the data, then you can just use
3065 * memset().
3067 void
3068 memwipe(void *mem, uint8_t byte, size_t sz)
3070 /* Because whole-program-optimization exists, we may not be able to just
3071 * have this function call "memset". A smart compiler could inline it, then
3072 * eliminate dead memsets, and declare itself to be clever. */
3074 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
3075 * based on the pointer value, then uses that junk to update a global
3076 * variable. It's an elaborate ruse to trick the compiler into not
3077 * optimizing out the "wipe this memory" code. Read it if you like zany
3078 * programming tricks! In later versions of Tor, we should look for better
3079 * not-optimized-out memory wiping stuff. */
3080 OPENSSL_cleanse(mem, sz);
3081 /* Just in case some caller of memwipe() is relying on getting a buffer
3082 * filled with a particular value, fill the buffer.
3084 * If this function gets inlined, this memset might get eliminated, but
3085 * that's okay: We only care about this particular memset in the case where
3086 * the caller should have been using memset(), and the memset() wouldn't get
3087 * eliminated. In other words, this is here so that we won't break anything
3088 * if somebody accidentally calls memwipe() instead of memset().
3090 memset(mem, byte, sz);
3093 #ifdef TOR_IS_MULTITHREADED
3095 #ifndef OPENSSL_THREADS
3096 #error OpenSSL has been built without thread support. Tor requires an \
3097 OpenSSL library with thread support enabled.
3098 #endif
3100 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3101 static void
3102 openssl_locking_cb_(int mode, int n, const char *file, int line)
3104 (void)file;
3105 (void)line;
3106 if (!openssl_mutexes_)
3107 /* This is not a really good fix for the
3108 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3109 * it can't hurt. */
3110 return;
3111 if (mode & CRYPTO_LOCK)
3112 tor_mutex_acquire(openssl_mutexes_[n]);
3113 else
3114 tor_mutex_release(openssl_mutexes_[n]);
3117 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3118 * as a lock. */
3119 struct CRYPTO_dynlock_value {
3120 tor_mutex_t *lock;
3123 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3124 * documentation in OpenSSL's docs for more info. */
3125 static struct CRYPTO_dynlock_value *
3126 openssl_dynlock_create_cb_(const char *file, int line)
3128 struct CRYPTO_dynlock_value *v;
3129 (void)file;
3130 (void)line;
3131 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
3132 v->lock = tor_mutex_new();
3133 return v;
3136 /** OpenSSL callback function to acquire or release a lock: see
3137 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3138 static void
3139 openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
3140 const char *file, int line)
3142 (void)file;
3143 (void)line;
3144 if (mode & CRYPTO_LOCK)
3145 tor_mutex_acquire(v->lock);
3146 else
3147 tor_mutex_release(v->lock);
3150 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3151 * documentation in OpenSSL's docs for more info. */
3152 static void
3153 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
3154 const char *file, int line)
3156 (void)file;
3157 (void)line;
3158 tor_mutex_free(v->lock);
3159 tor_free(v);
3162 /** @{ */
3163 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3164 * multithreaded. */
3165 static int
3166 setup_openssl_threading(void)
3168 int i;
3169 int n = CRYPTO_num_locks();
3170 n_openssl_mutexes_ = n;
3171 openssl_mutexes_ = tor_malloc(n*sizeof(tor_mutex_t *));
3172 for (i=0; i < n; ++i)
3173 openssl_mutexes_[i] = tor_mutex_new();
3174 CRYPTO_set_locking_callback(openssl_locking_cb_);
3175 CRYPTO_set_id_callback(tor_get_thread_id);
3176 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
3177 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
3178 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
3179 return 0;
3181 #else
3182 static int
3183 setup_openssl_threading(void)
3185 return 0;
3187 #endif
3189 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3192 crypto_global_cleanup(void)
3194 EVP_cleanup();
3195 ERR_remove_state(0);
3196 ERR_free_strings();
3198 if (dh_param_p)
3199 BN_clear_free(dh_param_p);
3200 if (dh_param_p_tls)
3201 BN_clear_free(dh_param_p_tls);
3202 if (dh_param_g)
3203 BN_clear_free(dh_param_g);
3205 #ifndef DISABLE_ENGINES
3206 ENGINE_cleanup();
3207 #endif
3209 CONF_modules_unload(1);
3210 CRYPTO_cleanup_all_ex_data();
3211 #ifdef TOR_IS_MULTITHREADED
3212 if (n_openssl_mutexes_) {
3213 int n = n_openssl_mutexes_;
3214 tor_mutex_t **ms = openssl_mutexes_;
3215 int i;
3216 openssl_mutexes_ = NULL;
3217 n_openssl_mutexes_ = 0;
3218 for (i=0;i<n;++i) {
3219 tor_mutex_free(ms[i]);
3221 tor_free(ms);
3223 #endif
3224 tor_free(crypto_openssl_version_str);
3225 tor_free(crypto_openssl_header_version_str);
3226 return 0;
3229 /** @} */