Fix some conversion problems
[tor.git] / src / common / crypto.c
blobf0d4fbbf21ec9947865f6081b15a8c7236d4cba2
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-2015, 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 "torlog.h"
55 #include "aes.h"
56 #include "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 /** A number of preallocated mutexes for use by OpenSSL. */
79 static tor_mutex_t **openssl_mutexes_ = NULL;
80 /** How many mutexes have we allocated for use by OpenSSL? */
81 static int n_openssl_mutexes_ = 0;
83 /** A public key, or a public/private key-pair. */
84 struct crypto_pk_t
86 int refs; /**< reference count, so we don't have to copy keys */
87 RSA *key; /**< The key itself */
90 /** Key and stream information for a stream cipher. */
91 struct crypto_cipher_t
93 char key[CIPHER_KEY_LEN]; /**< The raw key. */
94 char iv[CIPHER_IV_LEN]; /**< The initial IV. */
95 aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
96 * encryption */
99 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
100 * while we're waiting for the second.*/
101 struct crypto_dh_t {
102 DH *dh; /**< The openssl DH object */
105 static int setup_openssl_threading(void);
106 static int tor_check_dh_key(int severity, BIGNUM *bn);
108 /** Return the number of bytes added by padding method <b>padding</b>.
110 static INLINE int
111 crypto_get_rsa_padding_overhead(int padding)
113 switch (padding)
115 case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
116 default: tor_assert(0); return -1;
120 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
122 static INLINE int
123 crypto_get_rsa_padding(int padding)
125 switch (padding)
127 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
128 default: tor_assert(0); return -1;
132 /** Boolean: has OpenSSL's crypto been initialized? */
133 static int crypto_early_initialized_ = 0;
135 /** Boolean: has OpenSSL's crypto been initialized? */
136 static int crypto_global_initialized_ = 0;
138 /** Log all pending crypto errors at level <b>severity</b>. Use
139 * <b>doing</b> to describe our current activities.
141 static void
142 crypto_log_errors(int severity, const char *doing)
144 unsigned long err;
145 const char *msg, *lib, *func;
146 while ((err = ERR_get_error()) != 0) {
147 msg = (const char*)ERR_reason_error_string(err);
148 lib = (const char*)ERR_lib_error_string(err);
149 func = (const char*)ERR_func_error_string(err);
150 if (!msg) msg = "(null)";
151 if (!lib) lib = "(null)";
152 if (!func) func = "(null)";
153 if (doing) {
154 tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
155 doing, msg, lib, func);
156 } else {
157 tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
158 msg, lib, func);
163 #ifndef DISABLE_ENGINES
164 /** Log any OpenSSL engines we're using at NOTICE. */
165 static void
166 log_engine(const char *fn, ENGINE *e)
168 if (e) {
169 const char *name, *id;
170 name = ENGINE_get_name(e);
171 id = ENGINE_get_id(e);
172 log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
173 fn, name?name:"?", id?id:"?");
174 } else {
175 log_info(LD_CRYPTO, "Using default implementation for %s", fn);
178 #endif
180 #ifndef DISABLE_ENGINES
181 /** Try to load an engine in a shared library via fully qualified path.
183 static ENGINE *
184 try_load_engine(const char *path, const char *engine)
186 ENGINE *e = ENGINE_by_id("dynamic");
187 if (e) {
188 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
189 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
190 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
191 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
192 ENGINE_free(e);
193 e = NULL;
196 return e;
198 #endif
200 /* Returns a trimmed and human-readable version of an openssl version string
201 * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
202 * May 2012' and this will parse them into a form similar to '1.0.0b' */
203 static char *
204 parse_openssl_version_str(const char *raw_version)
206 const char *end_of_version = NULL;
207 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
208 trim that down. */
209 if (!strcmpstart(raw_version, "OpenSSL ")) {
210 raw_version += strlen("OpenSSL ");
211 end_of_version = strchr(raw_version, ' ');
214 if (end_of_version)
215 return tor_strndup(raw_version,
216 end_of_version-raw_version);
217 else
218 return tor_strdup(raw_version);
221 static char *crypto_openssl_version_str = NULL;
222 /* Return a human-readable version of the run-time openssl version number. */
223 const char *
224 crypto_openssl_get_version_str(void)
226 if (crypto_openssl_version_str == NULL) {
227 const char *raw_version = SSLeay_version(SSLEAY_VERSION);
228 crypto_openssl_version_str = parse_openssl_version_str(raw_version);
230 return crypto_openssl_version_str;
233 static char *crypto_openssl_header_version_str = NULL;
234 /* Return a human-readable version of the compile-time openssl version
235 * number. */
236 const char *
237 crypto_openssl_get_header_version_str(void)
239 if (crypto_openssl_header_version_str == NULL) {
240 crypto_openssl_header_version_str =
241 parse_openssl_version_str(OPENSSL_VERSION_TEXT);
243 return crypto_openssl_header_version_str;
246 /** Make sure that openssl is using its default PRNG. Return 1 if we had to
247 * adjust it; 0 otherwise. */
248 static int
249 crypto_force_rand_ssleay(void)
251 if (RAND_get_rand_method() != RAND_SSLeay()) {
252 log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
253 "a replacement the OpenSSL RNG. Resetting it to the default "
254 "implementation.");
255 RAND_set_rand_method(RAND_SSLeay());
256 return 1;
258 return 0;
261 /** Set up the siphash key if we haven't already done so. */
263 crypto_init_siphash_key(void)
265 static int have_seeded_siphash = 0;
266 struct sipkey key;
267 if (have_seeded_siphash)
268 return 0;
270 if (crypto_rand((char*) &key, sizeof(key)) < 0)
271 return -1;
272 siphash_set_global_key(&key);
273 have_seeded_siphash = 1;
274 return 0;
277 /** Initialize the crypto library. Return 0 on success, -1 on failure.
280 crypto_early_init(void)
282 if (!crypto_early_initialized_) {
284 crypto_early_initialized_ = 1;
286 ERR_load_crypto_strings();
287 OpenSSL_add_all_algorithms();
289 setup_openssl_threading();
291 if (SSLeay() == OPENSSL_VERSION_NUMBER &&
292 !strcmp(SSLeay_version(SSLEAY_VERSION), OPENSSL_VERSION_TEXT)) {
293 log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
294 "(%lx: %s).", SSLeay(), SSLeay_version(SSLEAY_VERSION));
295 } else {
296 log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
297 "version we're running with. If you get weird crashes, that "
298 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
299 (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
300 SSLeay(), SSLeay_version(SSLEAY_VERSION));
303 if (SSLeay() < OPENSSL_V_SERIES(1,0,0)) {
304 log_notice(LD_CRYPTO,
305 "Your OpenSSL version seems to be %s. We recommend 1.0.0 "
306 "or later.",
307 crypto_openssl_get_version_str());
310 crypto_force_rand_ssleay();
312 if (crypto_seed_rng(1) < 0)
313 return -1;
314 if (crypto_init_siphash_key() < 0)
315 return -1;
317 return 0;
320 /** Initialize the crypto library. Return 0 on success, -1 on failure.
323 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
325 if (!crypto_global_initialized_) {
326 crypto_early_init();
328 crypto_global_initialized_ = 1;
330 if (useAccel > 0) {
331 #ifdef DISABLE_ENGINES
332 (void)accelName;
333 (void)accelDir;
334 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
335 #else
336 ENGINE *e = NULL;
338 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
339 ENGINE_load_builtin_engines();
340 ENGINE_register_all_complete();
342 if (accelName) {
343 if (accelDir) {
344 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
345 " via path \"%s\".", accelName, accelDir);
346 e = try_load_engine(accelName, accelDir);
347 } else {
348 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
349 " acceleration support.", accelName);
350 e = ENGINE_by_id(accelName);
352 if (!e) {
353 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
354 accelName);
355 } else {
356 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
357 accelName);
360 if (e) {
361 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
362 " setting default ciphers.");
363 ENGINE_set_default(e, ENGINE_METHOD_ALL);
365 /* Log, if available, the intersection of the set of algorithms
366 used by Tor and the set of algorithms available in the engine */
367 log_engine("RSA", ENGINE_get_default_RSA());
368 log_engine("DH", ENGINE_get_default_DH());
369 log_engine("ECDH", ENGINE_get_default_ECDH());
370 log_engine("ECDSA", ENGINE_get_default_ECDSA());
371 log_engine("RAND", ENGINE_get_default_RAND());
372 log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
373 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
374 log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
375 log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
376 log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
377 #ifdef NID_aes_128_ctr
378 log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
379 #endif
380 #ifdef NID_aes_128_gcm
381 log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
382 #endif
383 log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
384 #ifdef NID_aes_256_gcm
385 log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
386 #endif
388 #endif
389 } else {
390 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
393 if (crypto_force_rand_ssleay()) {
394 if (crypto_seed_rng(1) < 0)
395 return -1;
398 evaluate_evp_for_aes(-1);
399 evaluate_ctr_for_aes();
401 return 0;
404 /** Free crypto resources held by this thread. */
405 void
406 crypto_thread_cleanup(void)
408 ERR_remove_state(0);
411 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
412 crypto_pk_t *
413 crypto_new_pk_from_rsa_(RSA *rsa)
415 crypto_pk_t *env;
416 tor_assert(rsa);
417 env = tor_malloc(sizeof(crypto_pk_t));
418 env->refs = 1;
419 env->key = rsa;
420 return env;
423 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
424 * crypto_pk_t. */
425 RSA *
426 crypto_pk_get_rsa_(crypto_pk_t *env)
428 return env->key;
431 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
432 * private is set, include the private-key portion of the key. */
433 EVP_PKEY *
434 crypto_pk_get_evp_pkey_(crypto_pk_t *env, int private)
436 RSA *key = NULL;
437 EVP_PKEY *pkey = NULL;
438 tor_assert(env->key);
439 if (private) {
440 if (!(key = RSAPrivateKey_dup(env->key)))
441 goto error;
442 } else {
443 if (!(key = RSAPublicKey_dup(env->key)))
444 goto error;
446 if (!(pkey = EVP_PKEY_new()))
447 goto error;
448 if (!(EVP_PKEY_assign_RSA(pkey, key)))
449 goto error;
450 return pkey;
451 error:
452 if (pkey)
453 EVP_PKEY_free(pkey);
454 if (key)
455 RSA_free(key);
456 return NULL;
459 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
461 DH *
462 crypto_dh_get_dh_(crypto_dh_t *dh)
464 return dh->dh;
467 /** Allocate and return storage for a public key. The key itself will not yet
468 * be set.
470 crypto_pk_t *
471 crypto_pk_new(void)
473 RSA *rsa;
475 rsa = RSA_new();
476 tor_assert(rsa);
477 return crypto_new_pk_from_rsa_(rsa);
480 /** Release a reference to an asymmetric key; when all the references
481 * are released, free the key.
483 void
484 crypto_pk_free(crypto_pk_t *env)
486 if (!env)
487 return;
489 if (--env->refs > 0)
490 return;
491 tor_assert(env->refs == 0);
493 if (env->key)
494 RSA_free(env->key);
496 tor_free(env);
499 /** Allocate and return a new symmetric cipher using the provided key and iv.
500 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
501 * provide NULL in place of either one, it is generated at random.
503 crypto_cipher_t *
504 crypto_cipher_new_with_iv(const char *key, const char *iv)
506 crypto_cipher_t *env;
508 env = tor_malloc_zero(sizeof(crypto_cipher_t));
510 if (key == NULL)
511 crypto_rand(env->key, CIPHER_KEY_LEN);
512 else
513 memcpy(env->key, key, CIPHER_KEY_LEN);
514 if (iv == NULL)
515 crypto_rand(env->iv, CIPHER_IV_LEN);
516 else
517 memcpy(env->iv, iv, CIPHER_IV_LEN);
519 env->cipher = aes_new_cipher(env->key, env->iv);
521 return env;
524 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
525 * zero bytes. */
526 crypto_cipher_t *
527 crypto_cipher_new(const char *key)
529 char zeroiv[CIPHER_IV_LEN];
530 memset(zeroiv, 0, sizeof(zeroiv));
531 return crypto_cipher_new_with_iv(key, zeroiv);
534 /** Free a symmetric cipher.
536 void
537 crypto_cipher_free(crypto_cipher_t *env)
539 if (!env)
540 return;
542 tor_assert(env->cipher);
543 aes_cipher_free(env->cipher);
544 memwipe(env, 0, sizeof(crypto_cipher_t));
545 tor_free(env);
548 /* public key crypto */
550 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
551 * Return 0 on success, -1 on failure.
554 crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
556 tor_assert(env);
558 if (env->key)
559 RSA_free(env->key);
562 BIGNUM *e = BN_new();
563 RSA *r = NULL;
564 if (!e)
565 goto done;
566 if (! BN_set_word(e, 65537))
567 goto done;
568 r = RSA_new();
569 if (!r)
570 goto done;
571 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
572 goto done;
574 env->key = r;
575 r = NULL;
576 done:
577 if (e)
578 BN_clear_free(e);
579 if (r)
580 RSA_free(r);
583 if (!env->key) {
584 crypto_log_errors(LOG_WARN, "generating RSA key");
585 return -1;
588 return 0;
591 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
592 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
593 * the string is nul-terminated.
595 /* Used here, and used for testing. */
597 crypto_pk_read_private_key_from_string(crypto_pk_t *env,
598 const char *s, ssize_t len)
600 BIO *b;
602 tor_assert(env);
603 tor_assert(s);
604 tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
606 /* Create a read-only memory BIO, backed by the string 's' */
607 b = BIO_new_mem_buf((char*)s, (int)len);
608 if (!b)
609 return -1;
611 if (env->key)
612 RSA_free(env->key);
614 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
616 BIO_free(b);
618 if (!env->key) {
619 crypto_log_errors(LOG_WARN, "Error parsing private key");
620 return -1;
622 return 0;
625 /** Read a PEM-encoded private key from the file named by
626 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
629 crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
630 const char *keyfile)
632 char *contents;
633 int r;
635 /* Read the file into a string. */
636 contents = read_file_to_str(keyfile, 0, NULL);
637 if (!contents) {
638 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
639 return -1;
642 /* Try to parse it. */
643 r = crypto_pk_read_private_key_from_string(env, contents, -1);
644 memwipe(contents, 0, strlen(contents));
645 tor_free(contents);
646 if (r)
647 return -1; /* read_private_key_from_string already warned, so we don't.*/
649 /* Make sure it's valid. */
650 if (crypto_pk_check_key(env) <= 0)
651 return -1;
653 return 0;
656 /** Helper function to implement crypto_pk_write_*_key_to_string. */
657 static int
658 crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
659 size_t *len, int is_public)
661 BUF_MEM *buf;
662 BIO *b;
663 int r;
665 tor_assert(env);
666 tor_assert(env->key);
667 tor_assert(dest);
669 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
670 if (!b)
671 return -1;
673 /* Now you can treat b as if it were a file. Just use the
674 * PEM_*_bio_* functions instead of the non-bio variants.
676 if (is_public)
677 r = PEM_write_bio_RSAPublicKey(b, env->key);
678 else
679 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
681 if (!r) {
682 crypto_log_errors(LOG_WARN, "writing RSA key to string");
683 BIO_free(b);
684 return -1;
687 BIO_get_mem_ptr(b, &buf);
688 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
689 BIO_free(b);
691 *dest = tor_malloc(buf->length+1);
692 memcpy(*dest, buf->data, buf->length);
693 (*dest)[buf->length] = 0; /* nul terminate it */
694 *len = buf->length;
695 BUF_MEM_free(buf);
697 return 0;
700 /** PEM-encode the public key portion of <b>env</b> and write it to a
701 * newly allocated string. On success, set *<b>dest</b> to the new
702 * string, *<b>len</b> to the string's length, and return 0. On
703 * failure, return -1.
706 crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
707 size_t *len)
709 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
712 /** PEM-encode the private key portion of <b>env</b> and write it to a
713 * newly allocated string. On success, set *<b>dest</b> to the new
714 * string, *<b>len</b> to the string's length, and return 0. On
715 * failure, return -1.
718 crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
719 size_t *len)
721 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
724 /** Read a PEM-encoded public key from the first <b>len</b> characters of
725 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
726 * failure.
729 crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
730 size_t len)
732 BIO *b;
734 tor_assert(env);
735 tor_assert(src);
736 tor_assert(len<INT_MAX);
738 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
739 if (!b)
740 return -1;
742 BIO_write(b, src, (int)len);
744 if (env->key)
745 RSA_free(env->key);
746 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
747 BIO_free(b);
748 if (!env->key) {
749 crypto_log_errors(LOG_WARN, "reading public key from string");
750 return -1;
753 return 0;
756 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
757 * PEM-encoded. Return 0 on success, -1 on failure.
760 crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
761 const char *fname)
763 BIO *bio;
764 char *cp;
765 long len;
766 char *s;
767 int r;
769 tor_assert(PRIVATE_KEY_OK(env));
771 if (!(bio = BIO_new(BIO_s_mem())))
772 return -1;
773 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
774 == 0) {
775 crypto_log_errors(LOG_WARN, "writing private key");
776 BIO_free(bio);
777 return -1;
779 len = BIO_get_mem_data(bio, &cp);
780 tor_assert(len >= 0);
781 s = tor_malloc(len+1);
782 memcpy(s, cp, len);
783 s[len]='\0';
784 r = write_str_to_file(fname, s, 0);
785 BIO_free(bio);
786 memwipe(s, 0, strlen(s));
787 tor_free(s);
788 return r;
791 /** Return true iff <b>env</b> has a valid key.
794 crypto_pk_check_key(crypto_pk_t *env)
796 int r;
797 tor_assert(env);
799 r = RSA_check_key(env->key);
800 if (r <= 0)
801 crypto_log_errors(LOG_WARN,"checking RSA key");
802 return r;
805 /** Return true iff <b>key</b> contains the private-key portion of the RSA
806 * key. */
808 crypto_pk_key_is_private(const crypto_pk_t *key)
810 tor_assert(key);
811 return PRIVATE_KEY_OK(key);
814 /** Return true iff <b>env</b> contains a public key whose public exponent
815 * equals 65537.
818 crypto_pk_public_exponent_ok(crypto_pk_t *env)
820 tor_assert(env);
821 tor_assert(env->key);
823 return BN_is_word(env->key->e, 65537);
826 /** Compare the public-key components of a and b. Return less than 0
827 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
828 * considered to be less than all non-NULL keys, and equal to itself.
830 * Note that this may leak information about the keys through timing.
833 crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
835 int result;
836 char a_is_non_null = (a != NULL) && (a->key != NULL);
837 char b_is_non_null = (b != NULL) && (b->key != NULL);
838 char an_argument_is_null = !a_is_non_null | !b_is_non_null;
840 result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
841 if (an_argument_is_null)
842 return result;
844 tor_assert(PUBLIC_KEY_OK(a));
845 tor_assert(PUBLIC_KEY_OK(b));
846 result = BN_cmp((a->key)->n, (b->key)->n);
847 if (result)
848 return result;
849 return BN_cmp((a->key)->e, (b->key)->e);
852 /** Compare the public-key components of a and b. Return non-zero iff
853 * a==b. A NULL key is considered to be distinct from all non-NULL
854 * keys, and equal to itself.
856 * Note that this may leak information about the keys through timing.
859 crypto_pk_eq_keys(crypto_pk_t *a, crypto_pk_t *b)
861 return (crypto_pk_cmp_keys(a, b) == 0);
864 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
865 size_t
866 crypto_pk_keysize(crypto_pk_t *env)
868 tor_assert(env);
869 tor_assert(env->key);
871 return (size_t) RSA_size(env->key);
874 /** Return the size of the public key modulus of <b>env</b>, in bits. */
876 crypto_pk_num_bits(crypto_pk_t *env)
878 tor_assert(env);
879 tor_assert(env->key);
880 tor_assert(env->key->n);
882 return BN_num_bits(env->key->n);
885 /** Increase the reference count of <b>env</b>, and return it.
887 crypto_pk_t *
888 crypto_pk_dup_key(crypto_pk_t *env)
890 tor_assert(env);
891 tor_assert(env->key);
893 env->refs++;
894 return env;
897 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
898 crypto_pk_t *
899 crypto_pk_copy_full(crypto_pk_t *env)
901 RSA *new_key;
902 int privatekey = 0;
903 tor_assert(env);
904 tor_assert(env->key);
906 if (PRIVATE_KEY_OK(env)) {
907 new_key = RSAPrivateKey_dup(env->key);
908 privatekey = 1;
909 } else {
910 new_key = RSAPublicKey_dup(env->key);
912 if (!new_key) {
913 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
914 privatekey?"private":"public");
915 crypto_log_errors(LOG_ERR,
916 privatekey ? "Duplicating a private key" :
917 "Duplicating a public key");
918 tor_fragile_assert();
919 return NULL;
922 return crypto_new_pk_from_rsa_(new_key);
925 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
926 * in <b>env</b>, using the padding method <b>padding</b>. On success,
927 * write the result to <b>to</b>, and return the number of bytes
928 * written. On failure, return -1.
930 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
931 * at least the length of the modulus of <b>env</b>.
934 crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
935 const char *from, size_t fromlen, int padding)
937 int r;
938 tor_assert(env);
939 tor_assert(from);
940 tor_assert(to);
941 tor_assert(fromlen<INT_MAX);
942 tor_assert(tolen >= crypto_pk_keysize(env));
944 r = RSA_public_encrypt((int)fromlen,
945 (unsigned char*)from, (unsigned char*)to,
946 env->key, crypto_get_rsa_padding(padding));
947 if (r<0) {
948 crypto_log_errors(LOG_WARN, "performing RSA encryption");
949 return -1;
951 return r;
954 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
955 * in <b>env</b>, using the padding method <b>padding</b>. On success,
956 * write the result to <b>to</b>, and return the number of bytes
957 * written. On failure, return -1.
959 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
960 * at least the length of the modulus of <b>env</b>.
963 crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
964 size_t tolen,
965 const char *from, size_t fromlen,
966 int padding, int warnOnFailure)
968 int r;
969 tor_assert(env);
970 tor_assert(from);
971 tor_assert(to);
972 tor_assert(env->key);
973 tor_assert(fromlen<INT_MAX);
974 tor_assert(tolen >= crypto_pk_keysize(env));
975 if (!env->key->p)
976 /* Not a private key */
977 return -1;
979 r = RSA_private_decrypt((int)fromlen,
980 (unsigned char*)from, (unsigned char*)to,
981 env->key, crypto_get_rsa_padding(padding));
983 if (r<0) {
984 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
985 "performing RSA decryption");
986 return -1;
988 return r;
991 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
992 * public key in <b>env</b>, using PKCS1 padding. On success, write the
993 * signed data to <b>to</b>, and return the number of bytes written.
994 * On failure, return -1.
996 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
997 * at least the length of the modulus of <b>env</b>.
1000 crypto_pk_public_checksig(crypto_pk_t *env, char *to,
1001 size_t tolen,
1002 const char *from, size_t fromlen)
1004 int r;
1005 tor_assert(env);
1006 tor_assert(from);
1007 tor_assert(to);
1008 tor_assert(fromlen < INT_MAX);
1009 tor_assert(tolen >= crypto_pk_keysize(env));
1010 r = RSA_public_decrypt((int)fromlen,
1011 (unsigned char*)from, (unsigned char*)to,
1012 env->key, RSA_PKCS1_PADDING);
1014 if (r<0) {
1015 crypto_log_errors(LOG_INFO, "checking RSA signature");
1016 return -1;
1018 return r;
1021 /** Check a siglen-byte long signature at <b>sig</b> against
1022 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
1023 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
1024 * SHA1(data). Else return -1.
1027 crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
1028 size_t datalen, const char *sig, size_t siglen)
1030 char digest[DIGEST_LEN];
1031 char *buf;
1032 size_t buflen;
1033 int r;
1035 tor_assert(env);
1036 tor_assert(data);
1037 tor_assert(sig);
1038 tor_assert(datalen < SIZE_T_CEILING);
1039 tor_assert(siglen < SIZE_T_CEILING);
1041 if (crypto_digest(digest,data,datalen)<0) {
1042 log_warn(LD_BUG, "couldn't compute digest");
1043 return -1;
1045 buflen = crypto_pk_keysize(env);
1046 buf = tor_malloc(buflen);
1047 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
1048 if (r != DIGEST_LEN) {
1049 log_warn(LD_CRYPTO, "Invalid signature");
1050 tor_free(buf);
1051 return -1;
1053 if (tor_memneq(buf, digest, DIGEST_LEN)) {
1054 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
1055 tor_free(buf);
1056 return -1;
1058 tor_free(buf);
1060 return 0;
1063 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
1064 * <b>env</b>, using PKCS1 padding. On success, write the signature to
1065 * <b>to</b>, and return the number of bytes written. On failure, return
1066 * -1.
1068 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1069 * at least the length of the modulus of <b>env</b>.
1072 crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
1073 const char *from, size_t fromlen)
1075 int r;
1076 tor_assert(env);
1077 tor_assert(from);
1078 tor_assert(to);
1079 tor_assert(fromlen < INT_MAX);
1080 tor_assert(tolen >= crypto_pk_keysize(env));
1081 if (!env->key->p)
1082 /* Not a private key */
1083 return -1;
1085 r = RSA_private_encrypt((int)fromlen,
1086 (unsigned char*)from, (unsigned char*)to,
1087 env->key, RSA_PKCS1_PADDING);
1088 if (r<0) {
1089 crypto_log_errors(LOG_WARN, "generating RSA signature");
1090 return -1;
1092 return r;
1095 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1096 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1097 * store it in <b>to</b>. Return the number of bytes written on
1098 * success, and -1 on failure.
1100 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1101 * at least the length of the modulus of <b>env</b>.
1104 crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
1105 const char *from, size_t fromlen)
1107 int r;
1108 char digest[DIGEST_LEN];
1109 if (crypto_digest(digest,from,fromlen)<0)
1110 return -1;
1111 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
1112 memwipe(digest, 0, sizeof(digest));
1113 return r;
1116 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1117 * bytes of data from <b>from</b>, with padding type 'padding',
1118 * storing the results on <b>to</b>.
1120 * Returns the number of bytes written on success, -1 on failure.
1122 * The encrypted data consists of:
1123 * - The source data, padded and encrypted with the public key, if the
1124 * padded source data is no longer than the public key, and <b>force</b>
1125 * is false, OR
1126 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1127 * padded and encrypted with the public key; followed by the rest of
1128 * the source data encrypted in AES-CTR mode with the symmetric key.
1131 crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
1132 char *to, size_t tolen,
1133 const char *from,
1134 size_t fromlen,
1135 int padding, int force)
1137 int overhead, outlen, r;
1138 size_t pkeylen, symlen;
1139 crypto_cipher_t *cipher = NULL;
1140 char *buf = NULL;
1142 tor_assert(env);
1143 tor_assert(from);
1144 tor_assert(to);
1145 tor_assert(fromlen < SIZE_T_CEILING);
1147 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1148 pkeylen = crypto_pk_keysize(env);
1150 if (!force && fromlen+overhead <= pkeylen) {
1151 /* It all fits in a single encrypt. */
1152 return crypto_pk_public_encrypt(env,to,
1153 tolen,
1154 from,fromlen,padding);
1156 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1157 tor_assert(tolen >= pkeylen);
1159 cipher = crypto_cipher_new(NULL); /* generate a new key. */
1161 buf = tor_malloc(pkeylen+1);
1162 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1163 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1165 /* Length of symmetrically encrypted data. */
1166 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1168 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1169 if (outlen!=(int)pkeylen) {
1170 goto err;
1172 r = crypto_cipher_encrypt(cipher, to+outlen,
1173 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1175 if (r<0) goto err;
1176 memwipe(buf, 0, pkeylen);
1177 tor_free(buf);
1178 crypto_cipher_free(cipher);
1179 tor_assert(outlen+symlen < INT_MAX);
1180 return (int)(outlen + symlen);
1181 err:
1183 memwipe(buf, 0, pkeylen);
1184 tor_free(buf);
1185 crypto_cipher_free(cipher);
1186 return -1;
1189 /** Invert crypto_pk_public_hybrid_encrypt. */
1191 crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
1192 char *to,
1193 size_t tolen,
1194 const char *from,
1195 size_t fromlen,
1196 int padding, int warnOnFailure)
1198 int outlen, r;
1199 size_t pkeylen;
1200 crypto_cipher_t *cipher = NULL;
1201 char *buf = NULL;
1203 tor_assert(fromlen < SIZE_T_CEILING);
1204 pkeylen = crypto_pk_keysize(env);
1206 if (fromlen <= pkeylen) {
1207 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1208 warnOnFailure);
1211 buf = tor_malloc(pkeylen);
1212 outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
1213 warnOnFailure);
1214 if (outlen<0) {
1215 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1216 "Error decrypting public-key data");
1217 goto err;
1219 if (outlen < CIPHER_KEY_LEN) {
1220 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1221 "No room for a symmetric key");
1222 goto err;
1224 cipher = crypto_cipher_new(buf);
1225 if (!cipher) {
1226 goto err;
1228 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1229 outlen -= CIPHER_KEY_LEN;
1230 tor_assert(tolen - outlen >= fromlen - pkeylen);
1231 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1232 if (r<0)
1233 goto err;
1234 memwipe(buf,0,pkeylen);
1235 tor_free(buf);
1236 crypto_cipher_free(cipher);
1237 tor_assert(outlen + fromlen < INT_MAX);
1238 return (int)(outlen + (fromlen-pkeylen));
1239 err:
1240 memwipe(buf,0,pkeylen);
1241 tor_free(buf);
1242 crypto_cipher_free(cipher);
1243 return -1;
1246 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1247 * Return -1 on error, or the number of characters used on success.
1250 crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
1252 int len;
1253 unsigned char *buf = NULL;
1255 len = i2d_RSAPublicKey(pk->key, &buf);
1256 if (len < 0 || buf == NULL)
1257 return -1;
1259 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
1260 OPENSSL_free(buf);
1261 return -1;
1263 /* We don't encode directly into 'dest', because that would be illegal
1264 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1266 memcpy(dest,buf,len);
1267 OPENSSL_free(buf);
1268 return len;
1271 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1272 * success and NULL on failure.
1274 crypto_pk_t *
1275 crypto_pk_asn1_decode(const char *str, size_t len)
1277 RSA *rsa;
1278 unsigned char *buf;
1279 const unsigned char *cp;
1280 cp = buf = tor_malloc(len);
1281 memcpy(buf,str,len);
1282 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1283 tor_free(buf);
1284 if (!rsa) {
1285 crypto_log_errors(LOG_WARN,"decoding public key");
1286 return NULL;
1288 return crypto_new_pk_from_rsa_(rsa);
1291 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1292 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1293 * Return 0 on success, -1 on failure.
1296 crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
1298 unsigned char *buf = NULL;
1299 int len;
1301 len = i2d_RSAPublicKey(pk->key, &buf);
1302 if (len < 0 || buf == NULL)
1303 return -1;
1304 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1305 OPENSSL_free(buf);
1306 return -1;
1308 OPENSSL_free(buf);
1309 return 0;
1312 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1313 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1315 crypto_pk_get_all_digests(crypto_pk_t *pk, digests_t *digests_out)
1317 unsigned char *buf = NULL;
1318 int len;
1320 len = i2d_RSAPublicKey(pk->key, &buf);
1321 if (len < 0 || buf == NULL)
1322 return -1;
1323 if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
1324 OPENSSL_free(buf);
1325 return -1;
1327 OPENSSL_free(buf);
1328 return 0;
1331 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1332 * every four spaces. */
1333 void
1334 crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
1336 int n = 0;
1337 char *end = out+outlen;
1338 tor_assert(outlen < SIZE_T_CEILING);
1340 while (*in && out<end) {
1341 *out++ = *in++;
1342 if (++n == 4 && *in && out<end) {
1343 n = 0;
1344 *out++ = ' ';
1347 tor_assert(out<end);
1348 *out = '\0';
1351 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1352 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1353 * space). Return 0 on success, -1 on failure.
1355 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1356 * of the public key, converted to hexadecimal, in upper case, with a
1357 * space after every four digits.
1359 * If <b>add_space</b> is false, omit the spaces.
1362 crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
1364 char digest[DIGEST_LEN];
1365 char hexdigest[HEX_DIGEST_LEN+1];
1366 if (crypto_pk_get_digest(pk, digest)) {
1367 return -1;
1369 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1370 if (add_space) {
1371 crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1372 } else {
1373 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1375 return 0;
1378 /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
1379 * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
1380 * bytes of space). Return 0 on success, -1 on failure.
1382 * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
1383 * of the ASN.1 encoding of the public key, converted to hexadecimal, in
1384 * upper case.
1387 crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
1389 char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
1390 if (crypto_pk_get_digest(pk, digest)) {
1391 return -1;
1393 if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
1394 return -1;
1396 base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
1397 return 0;
1400 /* symmetric crypto */
1402 /** Return a pointer to the key set for the cipher in <b>env</b>.
1404 const char *
1405 crypto_cipher_get_key(crypto_cipher_t *env)
1407 return env->key;
1410 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1411 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1412 * On failure, return -1.
1415 crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
1416 const char *from, size_t fromlen)
1418 tor_assert(env);
1419 tor_assert(env->cipher);
1420 tor_assert(from);
1421 tor_assert(fromlen);
1422 tor_assert(to);
1423 tor_assert(fromlen < SIZE_T_CEILING);
1425 aes_crypt(env->cipher, from, fromlen, to);
1426 return 0;
1429 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1430 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1431 * On failure, return -1.
1434 crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
1435 const char *from, size_t fromlen)
1437 tor_assert(env);
1438 tor_assert(from);
1439 tor_assert(to);
1440 tor_assert(fromlen < SIZE_T_CEILING);
1442 aes_crypt(env->cipher, from, fromlen, to);
1443 return 0;
1446 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1447 * on success, return 0. On failure, return -1.
1450 crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
1452 tor_assert(len < SIZE_T_CEILING);
1453 aes_crypt_inplace(env->cipher, buf, len);
1454 return 0;
1457 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1458 * <b>key</b> to the buffer in <b>to</b> of length
1459 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1460 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1461 * number of bytes written, on failure, return -1.
1464 crypto_cipher_encrypt_with_iv(const char *key,
1465 char *to, size_t tolen,
1466 const char *from, size_t fromlen)
1468 crypto_cipher_t *cipher;
1469 tor_assert(from);
1470 tor_assert(to);
1471 tor_assert(fromlen < INT_MAX);
1473 if (fromlen < 1)
1474 return -1;
1475 if (tolen < fromlen + CIPHER_IV_LEN)
1476 return -1;
1478 cipher = crypto_cipher_new_with_iv(key, NULL);
1480 memcpy(to, cipher->iv, CIPHER_IV_LEN);
1481 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1482 crypto_cipher_free(cipher);
1483 return (int)(fromlen + CIPHER_IV_LEN);
1486 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1487 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1488 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1489 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1490 * number of bytes written, on failure, return -1.
1493 crypto_cipher_decrypt_with_iv(const char *key,
1494 char *to, size_t tolen,
1495 const char *from, size_t fromlen)
1497 crypto_cipher_t *cipher;
1498 tor_assert(key);
1499 tor_assert(from);
1500 tor_assert(to);
1501 tor_assert(fromlen < INT_MAX);
1503 if (fromlen <= CIPHER_IV_LEN)
1504 return -1;
1505 if (tolen < fromlen - CIPHER_IV_LEN)
1506 return -1;
1508 cipher = crypto_cipher_new_with_iv(key, from);
1510 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1511 crypto_cipher_free(cipher);
1512 return (int)(fromlen - CIPHER_IV_LEN);
1515 /* SHA-1 */
1517 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1518 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1519 * Return 0 on success, -1 on failure.
1522 crypto_digest(char *digest, const char *m, size_t len)
1524 tor_assert(m);
1525 tor_assert(digest);
1526 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1529 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1530 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1531 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1533 crypto_digest256(char *digest, const char *m, size_t len,
1534 digest_algorithm_t algorithm)
1536 tor_assert(m);
1537 tor_assert(digest);
1538 tor_assert(algorithm == DIGEST_SHA256);
1539 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1542 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1543 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1544 * success, -1 on failure. */
1546 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1548 int i;
1549 tor_assert(ds_out);
1550 memset(ds_out, 0, sizeof(*ds_out));
1551 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1552 return -1;
1553 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1554 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1555 return -1;
1557 return 0;
1560 /** Return the name of an algorithm, as used in directory documents. */
1561 const char *
1562 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1564 switch (alg) {
1565 case DIGEST_SHA1:
1566 return "sha1";
1567 case DIGEST_SHA256:
1568 return "sha256";
1569 default:
1570 tor_fragile_assert();
1571 return "??unknown_digest??";
1575 /** Given the name of a digest algorithm, return its integer value, or -1 if
1576 * the name is not recognized. */
1578 crypto_digest_algorithm_parse_name(const char *name)
1580 if (!strcmp(name, "sha1"))
1581 return DIGEST_SHA1;
1582 else if (!strcmp(name, "sha256"))
1583 return DIGEST_SHA256;
1584 else
1585 return -1;
1588 /** Intermediate information about the digest of a stream of data. */
1589 struct crypto_digest_t {
1590 union {
1591 SHA_CTX sha1; /**< state for SHA1 */
1592 SHA256_CTX sha2; /**< state for SHA256 */
1593 } d; /**< State for the digest we're using. Only one member of the
1594 * union is usable, depending on the value of <b>algorithm</b>. */
1595 digest_algorithm_bitfield_t algorithm : 8; /**< Which algorithm is in use? */
1598 /** Allocate and return a new digest object to compute SHA1 digests.
1600 crypto_digest_t *
1601 crypto_digest_new(void)
1603 crypto_digest_t *r;
1604 r = tor_malloc(sizeof(crypto_digest_t));
1605 SHA1_Init(&r->d.sha1);
1606 r->algorithm = DIGEST_SHA1;
1607 return r;
1610 /** Allocate and return a new digest object to compute 256-bit digests
1611 * using <b>algorithm</b>. */
1612 crypto_digest_t *
1613 crypto_digest256_new(digest_algorithm_t algorithm)
1615 crypto_digest_t *r;
1616 tor_assert(algorithm == DIGEST_SHA256);
1617 r = tor_malloc(sizeof(crypto_digest_t));
1618 SHA256_Init(&r->d.sha2);
1619 r->algorithm = algorithm;
1620 return r;
1623 /** Deallocate a digest object.
1625 void
1626 crypto_digest_free(crypto_digest_t *digest)
1628 if (!digest)
1629 return;
1630 memwipe(digest, 0, sizeof(crypto_digest_t));
1631 tor_free(digest);
1634 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1636 void
1637 crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
1638 size_t len)
1640 tor_assert(digest);
1641 tor_assert(data);
1642 /* Using the SHA*_*() calls directly means we don't support doing
1643 * SHA in hardware. But so far the delay of getting the question
1644 * to the hardware, and hearing the answer, is likely higher than
1645 * just doing it ourselves. Hashes are fast.
1647 switch (digest->algorithm) {
1648 case DIGEST_SHA1:
1649 SHA1_Update(&digest->d.sha1, (void*)data, len);
1650 break;
1651 case DIGEST_SHA256:
1652 SHA256_Update(&digest->d.sha2, (void*)data, len);
1653 break;
1654 default:
1655 tor_fragile_assert();
1656 break;
1660 /** Compute the hash of the data that has been passed to the digest
1661 * object; write the first out_len bytes of the result to <b>out</b>.
1662 * <b>out_len</b> must be \<= DIGEST256_LEN.
1664 void
1665 crypto_digest_get_digest(crypto_digest_t *digest,
1666 char *out, size_t out_len)
1668 unsigned char r[DIGEST256_LEN];
1669 crypto_digest_t tmpenv;
1670 tor_assert(digest);
1671 tor_assert(out);
1672 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1673 memcpy(&tmpenv, digest, sizeof(crypto_digest_t));
1674 switch (digest->algorithm) {
1675 case DIGEST_SHA1:
1676 tor_assert(out_len <= DIGEST_LEN);
1677 SHA1_Final(r, &tmpenv.d.sha1);
1678 break;
1679 case DIGEST_SHA256:
1680 tor_assert(out_len <= DIGEST256_LEN);
1681 SHA256_Final(r, &tmpenv.d.sha2);
1682 break;
1683 default:
1684 log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
1685 /* If fragile_assert is not enabled, then we should at least not
1686 * leak anything. */
1687 memwipe(r, 0xff, sizeof(r));
1688 tor_fragile_assert();
1689 break;
1691 memcpy(out, r, out_len);
1692 memwipe(r, 0, sizeof(r));
1695 /** Allocate and return a new digest object with the same state as
1696 * <b>digest</b>
1698 crypto_digest_t *
1699 crypto_digest_dup(const crypto_digest_t *digest)
1701 crypto_digest_t *r;
1702 tor_assert(digest);
1703 r = tor_malloc(sizeof(crypto_digest_t));
1704 memcpy(r,digest,sizeof(crypto_digest_t));
1705 return r;
1708 /** Replace the state of the digest object <b>into</b> with the state
1709 * of the digest object <b>from</b>.
1711 void
1712 crypto_digest_assign(crypto_digest_t *into,
1713 const crypto_digest_t *from)
1715 tor_assert(into);
1716 tor_assert(from);
1717 memcpy(into,from,sizeof(crypto_digest_t));
1720 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1721 * at <b>digest_out</b> to the hash of the concatenation of those strings,
1722 * plus the optional string <b>append</b>, computed with the algorithm
1723 * <b>alg</b>.
1724 * <b>out_len</b> must be \<= DIGEST256_LEN. */
1725 void
1726 crypto_digest_smartlist(char *digest_out, size_t len_out,
1727 const smartlist_t *lst, const char *append,
1728 digest_algorithm_t alg)
1730 crypto_digest_t *d;
1731 if (alg == DIGEST_SHA1)
1732 d = crypto_digest_new();
1733 else
1734 d = crypto_digest256_new(alg);
1735 SMARTLIST_FOREACH(lst, const char *, cp,
1736 crypto_digest_add_bytes(d, cp, strlen(cp)));
1737 if (append)
1738 crypto_digest_add_bytes(d, append, strlen(append));
1739 crypto_digest_get_digest(d, digest_out, len_out);
1740 crypto_digest_free(d);
1743 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1744 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
1745 * result in <b>hmac_out</b>.
1747 void
1748 crypto_hmac_sha256(char *hmac_out,
1749 const char *key, size_t key_len,
1750 const char *msg, size_t msg_len)
1752 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1753 tor_assert(key_len < INT_MAX);
1754 tor_assert(msg_len < INT_MAX);
1755 HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1756 (unsigned char*)hmac_out, NULL);
1759 /* DH */
1761 /** Our DH 'g' parameter */
1762 #define DH_GENERATOR 2
1764 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1765 static BIGNUM *dh_param_p = NULL;
1766 /** Shared P parameter for our TLS DH key exchanges. */
1767 static BIGNUM *dh_param_p_tls = NULL;
1768 /** Shared G parameter for our DH key exchanges. */
1769 static BIGNUM *dh_param_g = NULL;
1771 /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
1772 * modulus. */
1773 void
1774 crypto_set_tls_dh_prime(void)
1776 BIGNUM *tls_prime = NULL;
1777 int r;
1779 /* If the space is occupied, free the previous TLS DH prime */
1780 if (dh_param_p_tls) {
1781 BN_clear_free(dh_param_p_tls);
1782 dh_param_p_tls = NULL;
1785 tls_prime = BN_new();
1786 tor_assert(tls_prime);
1788 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1789 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
1790 * prime.
1792 r = BN_hex2bn(&tls_prime,
1793 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1794 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1795 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1796 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1797 "B0E7393E0F24218EB3");
1798 tor_assert(r);
1800 tor_assert(tls_prime);
1802 dh_param_p_tls = tls_prime;
1805 /** Initialize dh_param_p and dh_param_g if they are not already
1806 * set. */
1807 static void
1808 init_dh_param(void)
1810 BIGNUM *circuit_dh_prime, *generator;
1811 int r;
1812 if (dh_param_p && dh_param_g)
1813 return;
1815 circuit_dh_prime = BN_new();
1816 generator = BN_new();
1817 tor_assert(circuit_dh_prime && generator);
1819 /* Set our generator for all DH parameters */
1820 r = BN_set_word(generator, DH_GENERATOR);
1821 tor_assert(r);
1823 /* This is from rfc2409, section 6.2. It's a safe prime, and
1824 supposedly it equals:
1825 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1827 r = BN_hex2bn(&circuit_dh_prime,
1828 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1829 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1830 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1831 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1832 "49286651ECE65381FFFFFFFFFFFFFFFF");
1833 tor_assert(r);
1835 /* Set the new values as the global DH parameters. */
1836 dh_param_p = circuit_dh_prime;
1837 dh_param_g = generator;
1839 if (!dh_param_p_tls) {
1840 crypto_set_tls_dh_prime();
1844 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
1845 * handshake. Since we exponentiate by this value, choosing a smaller one
1846 * lets our handhake go faster.
1848 #define DH_PRIVATE_KEY_BITS 320
1850 /** Allocate and return a new DH object for a key exchange.
1852 crypto_dh_t *
1853 crypto_dh_new(int dh_type)
1855 crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
1857 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
1858 dh_type == DH_TYPE_REND);
1860 if (!dh_param_p)
1861 init_dh_param();
1863 if (!(res->dh = DH_new()))
1864 goto err;
1866 if (dh_type == DH_TYPE_TLS) {
1867 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
1868 goto err;
1869 } else {
1870 if (!(res->dh->p = BN_dup(dh_param_p)))
1871 goto err;
1874 if (!(res->dh->g = BN_dup(dh_param_g)))
1875 goto err;
1877 res->dh->length = DH_PRIVATE_KEY_BITS;
1879 return res;
1880 err:
1881 crypto_log_errors(LOG_WARN, "creating DH object");
1882 if (res->dh) DH_free(res->dh); /* frees p and g too */
1883 tor_free(res);
1884 return NULL;
1887 /** Return a copy of <b>dh</b>, sharing its internal state. */
1888 crypto_dh_t *
1889 crypto_dh_dup(const crypto_dh_t *dh)
1891 crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
1892 dh_new->dh = dh->dh;
1893 DH_up_ref(dh->dh);
1894 return dh_new;
1897 /** Return the length of the DH key in <b>dh</b>, in bytes.
1900 crypto_dh_get_bytes(crypto_dh_t *dh)
1902 tor_assert(dh);
1903 return DH_size(dh->dh);
1906 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1907 * success, -1 on failure.
1910 crypto_dh_generate_public(crypto_dh_t *dh)
1912 again:
1913 if (!DH_generate_key(dh->dh)) {
1914 crypto_log_errors(LOG_WARN, "generating DH key");
1915 return -1;
1917 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
1918 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1919 "the-universe chances really do happen. Trying again.");
1920 /* Free and clear the keys, so OpenSSL will actually try again. */
1921 BN_clear_free(dh->dh->pub_key);
1922 BN_clear_free(dh->dh->priv_key);
1923 dh->dh->pub_key = dh->dh->priv_key = NULL;
1924 goto again;
1926 return 0;
1929 /** Generate g^x as necessary, and write the g^x for the key exchange
1930 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1931 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1934 crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
1936 int bytes;
1937 tor_assert(dh);
1938 if (!dh->dh->pub_key) {
1939 if (crypto_dh_generate_public(dh)<0)
1940 return -1;
1943 tor_assert(dh->dh->pub_key);
1944 bytes = BN_num_bytes(dh->dh->pub_key);
1945 tor_assert(bytes >= 0);
1946 if (pubkey_len < (size_t)bytes) {
1947 log_warn(LD_CRYPTO,
1948 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1949 (int) pubkey_len, bytes);
1950 return -1;
1953 memset(pubkey, 0, pubkey_len);
1954 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1956 return 0;
1959 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1960 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1961 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1963 static int
1964 tor_check_dh_key(int severity, BIGNUM *bn)
1966 BIGNUM *x;
1967 char *s;
1968 tor_assert(bn);
1969 x = BN_new();
1970 tor_assert(x);
1971 if (!dh_param_p)
1972 init_dh_param();
1973 BN_set_word(x, 1);
1974 if (BN_cmp(bn,x)<=0) {
1975 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
1976 goto err;
1978 BN_copy(x,dh_param_p);
1979 BN_sub_word(x, 1);
1980 if (BN_cmp(bn,x)>=0) {
1981 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
1982 goto err;
1984 BN_clear_free(x);
1985 return 0;
1986 err:
1987 BN_clear_free(x);
1988 s = BN_bn2hex(bn);
1989 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1990 OPENSSL_free(s);
1991 return -1;
1994 #undef MIN
1995 #define MIN(a,b) ((a)<(b)?(a):(b))
1996 /** Given a DH key exchange object, and our peer's value of g^y (as a
1997 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1998 * <b>secret_bytes_out</b> bytes of shared key material and write them
1999 * to <b>secret_out</b>. Return the number of bytes generated on success,
2000 * or -1 on failure.
2002 * (We generate key material by computing
2003 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2004 * where || is concatenation.)
2006 ssize_t
2007 crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
2008 const char *pubkey, size_t pubkey_len,
2009 char *secret_out, size_t secret_bytes_out)
2011 char *secret_tmp = NULL;
2012 BIGNUM *pubkey_bn = NULL;
2013 size_t secret_len=0, secret_tmp_len=0;
2014 int result=0;
2015 tor_assert(dh);
2016 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
2017 tor_assert(pubkey_len < INT_MAX);
2019 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
2020 (int)pubkey_len, NULL)))
2021 goto error;
2022 if (tor_check_dh_key(severity, pubkey_bn)<0) {
2023 /* Check for invalid public keys. */
2024 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
2025 goto error;
2027 secret_tmp_len = crypto_dh_get_bytes(dh);
2028 secret_tmp = tor_malloc(secret_tmp_len);
2029 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
2030 if (result < 0) {
2031 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
2032 goto error;
2034 secret_len = result;
2035 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
2036 (uint8_t*)secret_out, secret_bytes_out)<0)
2037 goto error;
2038 secret_len = secret_bytes_out;
2040 goto done;
2041 error:
2042 result = -1;
2043 done:
2044 crypto_log_errors(LOG_WARN, "completing DH handshake");
2045 if (pubkey_bn)
2046 BN_clear_free(pubkey_bn);
2047 if (secret_tmp) {
2048 memwipe(secret_tmp, 0, secret_tmp_len);
2049 tor_free(secret_tmp);
2051 if (result < 0)
2052 return result;
2053 else
2054 return secret_len;
2057 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2058 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2059 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2060 * H(K | [00]) | H(K | [01]) | ....
2062 * This is the key expansion algorithm used in the "TAP" circuit extension
2063 * mechanism; it shouldn't be used for new protocols.
2065 * Return 0 on success, -1 on failure.
2068 crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
2069 uint8_t *key_out, size_t key_out_len)
2071 int i;
2072 uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
2073 uint8_t digest[DIGEST_LEN];
2075 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2076 tor_assert(key_out_len <= DIGEST_LEN*256);
2078 memcpy(tmp, key_in, key_in_len);
2079 for (cp = key_out, i=0; cp < key_out+key_out_len;
2080 ++i, cp += DIGEST_LEN) {
2081 tmp[key_in_len] = i;
2082 if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
2083 goto err;
2084 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
2086 memwipe(tmp, 0, key_in_len+1);
2087 tor_free(tmp);
2088 memwipe(digest, 0, sizeof(digest));
2089 return 0;
2091 err:
2092 memwipe(tmp, 0, key_in_len+1);
2093 tor_free(tmp);
2094 memwipe(digest, 0, sizeof(digest));
2095 return -1;
2098 /** Expand some secret key material according to RFC5869, using SHA256 as the
2099 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2100 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2101 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2102 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2103 * bytes to <b>key_out</b> and return 0. On failure, return -1.
2106 crypto_expand_key_material_rfc5869_sha256(
2107 const uint8_t *key_in, size_t key_in_len,
2108 const uint8_t *salt_in, size_t salt_in_len,
2109 const uint8_t *info_in, size_t info_in_len,
2110 uint8_t *key_out, size_t key_out_len)
2112 uint8_t prk[DIGEST256_LEN];
2113 uint8_t tmp[DIGEST256_LEN + 128 + 1];
2114 uint8_t mac[DIGEST256_LEN];
2115 int i;
2116 uint8_t *outp;
2117 size_t tmp_len;
2119 crypto_hmac_sha256((char*)prk,
2120 (const char*)salt_in, salt_in_len,
2121 (const char*)key_in, key_in_len);
2123 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2124 tor_assert(key_out_len <= DIGEST256_LEN * 256);
2125 tor_assert(info_in_len <= 128);
2126 memset(tmp, 0, sizeof(tmp));
2127 outp = key_out;
2128 i = 1;
2130 while (key_out_len) {
2131 size_t n;
2132 if (i > 1) {
2133 memcpy(tmp, mac, DIGEST256_LEN);
2134 memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
2135 tmp[DIGEST256_LEN+info_in_len] = i;
2136 tmp_len = DIGEST256_LEN + info_in_len + 1;
2137 } else {
2138 memcpy(tmp, info_in, info_in_len);
2139 tmp[info_in_len] = i;
2140 tmp_len = info_in_len + 1;
2142 crypto_hmac_sha256((char*)mac,
2143 (const char*)prk, DIGEST256_LEN,
2144 (const char*)tmp, tmp_len);
2145 n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
2146 memcpy(outp, mac, n);
2147 key_out_len -= n;
2148 outp += n;
2149 ++i;
2152 memwipe(tmp, 0, sizeof(tmp));
2153 memwipe(mac, 0, sizeof(mac));
2154 return 0;
2157 /** Free a DH key exchange object.
2159 void
2160 crypto_dh_free(crypto_dh_t *dh)
2162 if (!dh)
2163 return;
2164 tor_assert(dh->dh);
2165 DH_free(dh->dh);
2166 tor_free(dh);
2169 /* random numbers */
2171 /** How many bytes of entropy we add at once.
2173 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2174 * work for us too. */
2175 #define ADD_ENTROPY 32
2177 /** True iff it's safe to use RAND_poll after setup.
2179 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2180 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2181 * that fd without checking whether it fit in the fd_set. Thus, if the
2182 * system has not just been started up, it is unsafe to call */
2183 #define RAND_POLL_IS_SAFE \
2184 (OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2186 /** Set the seed of the weak RNG to a random value. */
2187 void
2188 crypto_seed_weak_rng(tor_weak_rng_t *rng)
2190 unsigned seed;
2191 crypto_rand((void*)&seed, sizeof(seed));
2192 tor_init_weak_random(rng, seed);
2195 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2196 * storing it into <b>out</b>.
2199 crypto_strongest_rand(uint8_t *out, size_t out_len)
2201 #ifdef _WIN32
2202 static int provider_set = 0;
2203 static HCRYPTPROV provider;
2204 #else
2205 static const char *filenames[] = {
2206 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2208 int fd, i;
2209 size_t n;
2210 #endif
2212 #ifdef _WIN32
2213 if (!provider_set) {
2214 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2215 CRYPT_VERIFYCONTEXT)) {
2216 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2217 return -1;
2219 provider_set = 1;
2221 if (!CryptGenRandom(provider, out_len, out)) {
2222 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2223 return -1;
2226 return 0;
2227 #else
2228 for (i = 0; filenames[i]; ++i) {
2229 log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
2230 fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
2231 if (fd<0) continue;
2232 log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
2233 n = read_all(fd, (char*)out, out_len, 0);
2234 close(fd);
2235 if (n != out_len) {
2236 log_warn(LD_CRYPTO,
2237 "Error reading from entropy source (read only %lu bytes).",
2238 (unsigned long)n);
2239 return -1;
2242 return 0;
2245 log_warn(LD_CRYPTO, "Cannot get strong entropy: no entropy source found.");
2246 return -1;
2247 #endif
2250 /** Seed OpenSSL's random number generator with bytes from the operating
2251 * system. <b>startup</b> should be true iff we have just started Tor and
2252 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2255 crypto_seed_rng(int startup)
2257 int rand_poll_ok = 0, load_entropy_ok = 0;
2258 uint8_t buf[ADD_ENTROPY];
2260 /* OpenSSL has a RAND_poll function that knows about more kinds of
2261 * entropy than we do. We'll try calling that, *and* calling our own entropy
2262 * functions. If one succeeds, we'll accept the RNG as seeded. */
2263 if (startup || RAND_POLL_IS_SAFE) {
2264 rand_poll_ok = RAND_poll();
2265 if (rand_poll_ok == 0)
2266 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2269 load_entropy_ok = !crypto_strongest_rand(buf, sizeof(buf));
2270 if (load_entropy_ok) {
2271 RAND_seed(buf, sizeof(buf));
2274 memwipe(buf, 0, sizeof(buf));
2276 if (rand_poll_ok || load_entropy_ok)
2277 return 0;
2278 else
2279 return -1;
2282 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2283 * success, -1 on failure.
2285 MOCK_IMPL(int,
2286 crypto_rand, (char *to, size_t n))
2288 int r;
2289 tor_assert(n < INT_MAX);
2290 tor_assert(to);
2291 r = RAND_bytes((unsigned char*)to, (int)n);
2292 if (r == 0)
2293 crypto_log_errors(LOG_WARN, "generating random data");
2294 return (r == 1) ? 0 : -1;
2297 /** Return a pseudorandom integer, chosen uniformly from the values
2298 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2299 * INT_MAX+1, inclusive. */
2301 crypto_rand_int(unsigned int max)
2303 unsigned int val;
2304 unsigned int cutoff;
2305 tor_assert(max <= ((unsigned int)INT_MAX)+1);
2306 tor_assert(max > 0); /* don't div by 0 */
2308 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2309 * distribution with clipping at the upper end of unsigned int's
2310 * range.
2312 cutoff = UINT_MAX - (UINT_MAX%max);
2313 while (1) {
2314 crypto_rand((char*)&val, sizeof(val));
2315 if (val < cutoff)
2316 return val % max;
2320 /** Return a pseudorandom integer, chosen uniformly from the values <i>i</i>
2321 * such that <b>min</b> &lt;= <i>i</i> &lt <b>max</b>.
2323 * <b>min</b> MUST be in range [0, <b>max</b>).
2324 * <b>max</b> MUST be in range (min, INT_MAX].
2327 crypto_rand_int_range(unsigned int min, unsigned int max)
2329 tor_assert(min < max);
2330 tor_assert(max <= INT_MAX);
2332 /* The overflow is avoided here because crypto_rand_int() returns a value
2333 * between 0 and (max - min - 1) with max being <= INT_MAX and min <= max.
2334 * This is why we add 1 to the maximum value so we can actually get max as
2335 * a return value. */
2336 return min + crypto_rand_int(max - min);
2339 /** As crypto_rand_int_range, but supports uint64_t. */
2340 uint64_t
2341 crypto_rand_uint64_range(uint64_t min, uint64_t max)
2343 tor_assert(min < max);
2344 return min + crypto_rand_uint64(max - min);
2347 /** As crypto_rand_int_range, but supports time_t. */
2348 time_t
2349 crypto_rand_time_range(time_t min, time_t max)
2351 return (time_t) crypto_rand_uint64_range(min, max);
2354 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2355 * between 0 and <b>max</b>-1. */
2356 uint64_t
2357 crypto_rand_uint64(uint64_t max)
2359 uint64_t val;
2360 uint64_t cutoff;
2361 tor_assert(max < UINT64_MAX);
2362 tor_assert(max > 0); /* don't div by 0 */
2364 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2365 * distribution with clipping at the upper end of unsigned int's
2366 * range.
2368 cutoff = UINT64_MAX - (UINT64_MAX%max);
2369 while (1) {
2370 crypto_rand((char*)&val, sizeof(val));
2371 if (val < cutoff)
2372 return val % max;
2376 /** Return a pseudorandom double d, chosen uniformly from the range
2377 * 0.0 <= d < 1.0.
2379 double
2380 crypto_rand_double(void)
2382 /* We just use an unsigned int here; we don't really care about getting
2383 * more than 32 bits of resolution */
2384 unsigned int uint;
2385 crypto_rand((char*)&uint, sizeof(uint));
2386 #if SIZEOF_INT == 4
2387 #define UINT_MAX_AS_DOUBLE 4294967296.0
2388 #elif SIZEOF_INT == 8
2389 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2390 #else
2391 #error SIZEOF_INT is neither 4 nor 8
2392 #endif
2393 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2396 /** Generate and return a new random hostname starting with <b>prefix</b>,
2397 * ending with <b>suffix</b>, and containing no fewer than
2398 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2399 * characters between.
2401 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2403 char *
2404 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2405 const char *suffix)
2407 char *result, *rand_bytes;
2408 int randlen, rand_bytes_len;
2409 size_t resultlen, prefixlen;
2411 if (max_rand_len > MAX_DNS_LABEL_SIZE)
2412 max_rand_len = MAX_DNS_LABEL_SIZE;
2413 if (min_rand_len > max_rand_len)
2414 min_rand_len = max_rand_len;
2416 randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
2418 prefixlen = strlen(prefix);
2419 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2421 rand_bytes_len = ((randlen*5)+7)/8;
2422 if (rand_bytes_len % 5)
2423 rand_bytes_len += 5 - (rand_bytes_len%5);
2424 rand_bytes = tor_malloc(rand_bytes_len);
2425 crypto_rand(rand_bytes, rand_bytes_len);
2427 result = tor_malloc(resultlen);
2428 memcpy(result, prefix, prefixlen);
2429 base32_encode(result+prefixlen, resultlen-prefixlen,
2430 rand_bytes, rand_bytes_len);
2431 tor_free(rand_bytes);
2432 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2434 return result;
2437 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2438 * is empty. */
2439 void *
2440 smartlist_choose(const smartlist_t *sl)
2442 int len = smartlist_len(sl);
2443 if (len)
2444 return smartlist_get(sl,crypto_rand_int(len));
2445 return NULL; /* no elements to choose from */
2448 /** Scramble the elements of <b>sl</b> into a random order. */
2449 void
2450 smartlist_shuffle(smartlist_t *sl)
2452 int i;
2453 /* From the end of the list to the front, choose at random from the
2454 positions we haven't looked at yet, and swap that position into the
2455 current position. Remember to give "no swap" the same probability as
2456 any other swap. */
2457 for (i = smartlist_len(sl)-1; i > 0; --i) {
2458 int j = crypto_rand_int(i+1);
2459 smartlist_swap(sl, i, j);
2463 #define BASE64_OPENSSL_LINELEN 64
2465 /** Return the Base64 encoded size of <b>srclen</b> bytes of data in
2466 * bytes.
2468 * If <b>flags</b>&amp;BASE64_ENCODE_MULTILINE is true, return the size
2469 * of the encoded output as multiline output (64 character, `\n' terminated
2470 * lines).
2472 size_t
2473 base64_encode_size(size_t srclen, int flags)
2475 size_t enclen;
2476 tor_assert(srclen < INT_MAX);
2478 if (srclen == 0)
2479 return 0;
2481 enclen = ((srclen - 1) / 3) * 4 + 4;
2482 if (flags & BASE64_ENCODE_MULTILINE) {
2483 size_t remainder = enclen % BASE64_OPENSSL_LINELEN;
2484 enclen += enclen / BASE64_OPENSSL_LINELEN;
2485 if (remainder)
2486 enclen++;
2488 tor_assert(enclen < INT_MAX && enclen > srclen);
2489 return enclen;
2492 /** Internal table mapping 6 bit values to the Base64 alphabet. */
2493 static const char base64_encode_table[64] = {
2494 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
2495 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
2496 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
2497 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
2498 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
2499 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
2500 'w', 'x', 'y', 'z', '0', '1', '2', '3',
2501 '4', '5', '6', '7', '8', '9', '+', '/'
2504 /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2505 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2506 * bytes. Return the number of bytes written on success; -1 if
2507 * destlen is too short, or other failure.
2509 * If <b>flags</b>&amp;BASE64_ENCODE_MULTILINE is true, return encoded
2510 * output in multiline format (64 character, `\n' terminated lines).
2513 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen,
2514 int flags)
2516 const unsigned char *usrc = (unsigned char *)src;
2517 const unsigned char *eous = usrc + srclen;
2518 char *d = dest;
2519 uint32_t n = 0;
2520 size_t linelen = 0;
2521 size_t enclen;
2522 int n_idx = 0;
2524 if (!src || !dest)
2525 return -1;
2527 /* Ensure that there is sufficient space, including the NUL. */
2528 enclen = base64_encode_size(srclen, flags);
2529 if (destlen < enclen + 1)
2530 return -1;
2531 if (destlen > SIZE_T_CEILING)
2532 return -1;
2533 if (enclen > INT_MAX)
2534 return -1;
2536 memset(dest, 0, enclen);
2538 /* XXX/Yawning: If this ends up being too slow, this can be sped up
2539 * by separating the multiline format case and the normal case, and
2540 * processing 48 bytes of input at a time when newlines are desired.
2542 #define ENCODE_CHAR(ch) \
2543 STMT_BEGIN \
2544 *d++ = ch; \
2545 if (flags & BASE64_ENCODE_MULTILINE) { \
2546 if (++linelen % BASE64_OPENSSL_LINELEN == 0) { \
2547 linelen = 0; \
2548 *d++ = '\n'; \
2551 STMT_END
2553 #define ENCODE_N(idx) \
2554 ENCODE_CHAR(base64_encode_table[(n >> ((3 - idx) * 6)) & 0x3f])
2556 #define ENCODE_PAD() ENCODE_CHAR('=')
2558 /* Iterate over all the bytes in src. Each one will add 8 bits to the
2559 * value we're encoding. Accumulate bits in <b>n</b>, and whenever we
2560 * have 24 bits, batch them into 4 bytes and flush those bytes to dest.
2562 for ( ; usrc < eous; ++usrc) {
2563 n = (n << 8) | *usrc;
2564 if ((++n_idx) == 3) {
2565 ENCODE_N(0);
2566 ENCODE_N(1);
2567 ENCODE_N(2);
2568 ENCODE_N(3);
2569 n_idx = 0;
2570 n = 0;
2573 switch (n_idx) {
2574 case 0:
2575 /* 0 leftover bits, no pading to add. */
2576 break;
2577 case 1:
2578 /* 8 leftover bits, pad to 12 bits, write the 2 6-bit values followed
2579 * by 2 padding characters.
2581 n <<= 4;
2582 ENCODE_N(2);
2583 ENCODE_N(3);
2584 ENCODE_PAD();
2585 ENCODE_PAD();
2586 break;
2587 case 2:
2588 /* 16 leftover bits, pad to 18 bits, write the 3 6-bit values followed
2589 * by 1 padding character.
2591 n <<= 2;
2592 ENCODE_N(1);
2593 ENCODE_N(2);
2594 ENCODE_N(3);
2595 ENCODE_PAD();
2596 break;
2597 default:
2598 /* Something went catastrophically wrong. */
2599 tor_fragile_assert();
2600 return -1;
2603 #undef ENCODE_N
2604 #undef ENCODE_PAD
2605 #undef ENCODE_CHAR
2607 /* Multiline output always includes at least one newline. */
2608 if (flags & BASE64_ENCODE_MULTILINE && linelen != 0)
2609 *d++ = '\n';
2611 tor_assert(d - dest == (ptrdiff_t)enclen);
2613 *d++ = '\0'; /* NUL terminate the output. */
2615 return (int) enclen;
2618 #undef BASE64_OPENSSL_LINELEN
2620 /** @{ */
2621 /** Special values used for the base64_decode_table */
2622 #define X 255
2623 #define SP 64
2624 #define PAD 65
2625 /** @} */
2626 /** Internal table mapping byte values to what they represent in base64.
2627 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2628 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2629 * end-of-string. */
2630 static const uint8_t base64_decode_table[256] = {
2631 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2632 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2633 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2634 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2635 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2636 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2637 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2638 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2639 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2640 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2641 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2642 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2643 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2644 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2645 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2646 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2649 /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2650 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2651 * bytes. Return the number of bytes written on success; -1 if
2652 * destlen is too short, or other failure.
2654 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2655 * spaces or padding.
2657 * NOTE 2: This implementation does not check for the correct number of
2658 * padding "=" characters at the end of the string, and does not check
2659 * for internal padding characters.
2662 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2664 const char *eos = src+srclen;
2665 uint32_t n=0;
2666 int n_idx=0;
2667 char *dest_orig = dest;
2669 /* Max number of bits == srclen*6.
2670 * Number of bytes required to hold all bits == (srclen*6)/8.
2671 * Yes, we want to round down: anything that hangs over the end of a
2672 * byte is padding. */
2673 if (destlen < (srclen*3)/4)
2674 return -1;
2675 if (destlen > SIZE_T_CEILING)
2676 return -1;
2678 memset(dest, 0, destlen);
2680 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2681 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2682 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2684 for ( ; src < eos; ++src) {
2685 unsigned char c = (unsigned char) *src;
2686 uint8_t v = base64_decode_table[c];
2687 switch (v) {
2688 case X:
2689 /* This character isn't allowed in base64. */
2690 return -1;
2691 case SP:
2692 /* This character is whitespace, and has no effect. */
2693 continue;
2694 case PAD:
2695 /* We've hit an = character: the data is over. */
2696 goto end_of_loop;
2697 default:
2698 /* We have an actual 6-bit value. Append it to the bits in n. */
2699 n = (n<<6) | v;
2700 if ((++n_idx) == 4) {
2701 /* We've accumulated 24 bits in n. Flush them. */
2702 *dest++ = (n>>16);
2703 *dest++ = (n>>8) & 0xff;
2704 *dest++ = (n) & 0xff;
2705 n_idx = 0;
2706 n = 0;
2710 end_of_loop:
2711 /* If we have leftover bits, we need to cope. */
2712 switch (n_idx) {
2713 case 0:
2714 default:
2715 /* No leftover bits. We win. */
2716 break;
2717 case 1:
2718 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2719 return -1;
2720 case 2:
2721 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2722 *dest++ = n >> 4;
2723 break;
2724 case 3:
2725 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2726 *dest++ = n >> 10;
2727 *dest++ = n >> 2;
2730 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2731 tor_assert((dest-dest_orig) <= INT_MAX);
2733 return (int)(dest-dest_orig);
2735 #undef X
2736 #undef SP
2737 #undef PAD
2739 /** Base64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2740 * characters, and store the nul-terminated result in the first
2741 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2743 digest_to_base64(char *d64, const char *digest)
2745 char buf[256];
2746 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN, 0);
2747 buf[BASE64_DIGEST_LEN] = '\0';
2748 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2749 return 0;
2752 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2753 * trailing newline or = characters), decode it and store the result in the
2754 * first DIGEST_LEN bytes at <b>digest</b>. */
2756 digest_from_base64(char *digest, const char *d64)
2758 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2759 return 0;
2760 else
2761 return -1;
2764 /** Base64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2765 * trailing = characters, and store the nul-terminated result in the first
2766 * BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2768 digest256_to_base64(char *d64, const char *digest)
2770 char buf[256];
2771 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN, 0);
2772 buf[BASE64_DIGEST256_LEN] = '\0';
2773 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2774 return 0;
2777 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2778 * trailing newline or = characters), decode it and store the result in the
2779 * first DIGEST256_LEN bytes at <b>digest</b>. */
2781 digest256_from_base64(char *digest, const char *d64)
2783 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2784 return 0;
2785 else
2786 return -1;
2789 /** Implements base32 encoding as in RFC 4648. Limitation: Requires
2790 * that srclen*8 is a multiple of 5.
2792 void
2793 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2795 unsigned int i, v, u;
2796 size_t nbits = srclen * 8, bit;
2798 tor_assert(srclen < SIZE_T_CEILING/8);
2799 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2800 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2801 tor_assert(destlen < SIZE_T_CEILING);
2803 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2804 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2805 v = ((uint8_t)src[bit/8]) << 8;
2806 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2807 /* set u to the 5-bit value at the bit'th bit of src. */
2808 u = (v >> (11-(bit%8))) & 0x1F;
2809 dest[i] = BASE32_CHARS[u];
2811 dest[i] = '\0';
2814 /** Implements base32 decoding as in RFC 4648. Limitation: Requires
2815 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2818 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2820 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2821 * it ever shows up in the profile. */
2822 unsigned int i;
2823 size_t nbits, j, bit;
2824 char *tmp;
2825 nbits = srclen * 5;
2827 tor_assert(srclen < SIZE_T_CEILING / 5);
2828 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2829 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2830 tor_assert(destlen < SIZE_T_CEILING);
2832 memset(dest, 0, destlen);
2834 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2835 tmp = tor_malloc_zero(srclen);
2836 for (j = 0; j < srclen; ++j) {
2837 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2838 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2839 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2840 else {
2841 log_warn(LD_BUG, "illegal character in base32 encoded string");
2842 tor_free(tmp);
2843 return -1;
2847 /* Assemble result byte-wise by applying five possible cases. */
2848 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2849 switch (bit % 40) {
2850 case 0:
2851 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2852 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2853 break;
2854 case 8:
2855 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2856 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2857 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2858 break;
2859 case 16:
2860 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2861 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2862 break;
2863 case 24:
2864 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2865 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2866 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2867 break;
2868 case 32:
2869 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2870 ((uint8_t)tmp[(bit/5)+1]);
2871 break;
2875 memwipe(tmp, 0, srclen);
2876 tor_free(tmp);
2877 tmp = NULL;
2878 return 0;
2882 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
2883 * the value <b>byte</b>.
2885 * This function is preferable to memset, since many compilers will happily
2886 * optimize out memset() when they can convince themselves that the data being
2887 * cleared will never be read.
2889 * Right now, our convention is to use this function when we are wiping data
2890 * that's about to become inaccessible, such as stack buffers that are about
2891 * to go out of scope or structures that are about to get freed. (In
2892 * practice, it appears that the compilers we're currently using will optimize
2893 * out the memset()s for stack-allocated buffers, but not those for
2894 * about-to-be-freed structures. That could change, though, so we're being
2895 * wary.) If there are live reads for the data, then you can just use
2896 * memset().
2898 void
2899 memwipe(void *mem, uint8_t byte, size_t sz)
2901 /* Because whole-program-optimization exists, we may not be able to just
2902 * have this function call "memset". A smart compiler could inline it, then
2903 * eliminate dead memsets, and declare itself to be clever. */
2905 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
2906 * based on the pointer value, then uses that junk to update a global
2907 * variable. It's an elaborate ruse to trick the compiler into not
2908 * optimizing out the "wipe this memory" code. Read it if you like zany
2909 * programming tricks! In later versions of Tor, we should look for better
2910 * not-optimized-out memory wiping stuff. */
2911 OPENSSL_cleanse(mem, sz);
2912 /* Just in case some caller of memwipe() is relying on getting a buffer
2913 * filled with a particular value, fill the buffer.
2915 * If this function gets inlined, this memset might get eliminated, but
2916 * that's okay: We only care about this particular memset in the case where
2917 * the caller should have been using memset(), and the memset() wouldn't get
2918 * eliminated. In other words, this is here so that we won't break anything
2919 * if somebody accidentally calls memwipe() instead of memset().
2921 memset(mem, byte, sz);
2924 #ifndef OPENSSL_THREADS
2925 #error OpenSSL has been built without thread support. Tor requires an \
2926 OpenSSL library with thread support enabled.
2927 #endif
2929 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2930 static void
2931 openssl_locking_cb_(int mode, int n, const char *file, int line)
2933 (void)file;
2934 (void)line;
2935 if (!openssl_mutexes_)
2936 /* This is not a really good fix for the
2937 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2938 * it can't hurt. */
2939 return;
2940 if (mode & CRYPTO_LOCK)
2941 tor_mutex_acquire(openssl_mutexes_[n]);
2942 else
2943 tor_mutex_release(openssl_mutexes_[n]);
2946 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2947 * as a lock. */
2948 struct CRYPTO_dynlock_value {
2949 tor_mutex_t *lock;
2952 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2953 * documentation in OpenSSL's docs for more info. */
2954 static struct CRYPTO_dynlock_value *
2955 openssl_dynlock_create_cb_(const char *file, int line)
2957 struct CRYPTO_dynlock_value *v;
2958 (void)file;
2959 (void)line;
2960 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2961 v->lock = tor_mutex_new();
2962 return v;
2965 /** OpenSSL callback function to acquire or release a lock: see
2966 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2967 static void
2968 openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
2969 const char *file, int line)
2971 (void)file;
2972 (void)line;
2973 if (mode & CRYPTO_LOCK)
2974 tor_mutex_acquire(v->lock);
2975 else
2976 tor_mutex_release(v->lock);
2979 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2980 * documentation in OpenSSL's docs for more info. */
2981 static void
2982 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
2983 const char *file, int line)
2985 (void)file;
2986 (void)line;
2987 tor_mutex_free(v->lock);
2988 tor_free(v);
2991 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0)
2992 static void
2993 tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
2995 CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
2997 #endif
2999 /** @{ */
3000 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3001 * multithreaded. */
3002 static int
3003 setup_openssl_threading(void)
3005 int i;
3006 int n = CRYPTO_num_locks();
3007 n_openssl_mutexes_ = n;
3008 openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
3009 for (i=0; i < n; ++i)
3010 openssl_mutexes_[i] = tor_mutex_new();
3011 CRYPTO_set_locking_callback(openssl_locking_cb_);
3012 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,0,0)
3013 CRYPTO_set_id_callback(tor_get_thread_id);
3014 #else
3015 CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
3016 #endif
3017 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
3018 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
3019 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
3020 return 0;
3023 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3026 crypto_global_cleanup(void)
3028 EVP_cleanup();
3029 ERR_remove_state(0);
3030 ERR_free_strings();
3032 if (dh_param_p)
3033 BN_clear_free(dh_param_p);
3034 if (dh_param_p_tls)
3035 BN_clear_free(dh_param_p_tls);
3036 if (dh_param_g)
3037 BN_clear_free(dh_param_g);
3039 #ifndef DISABLE_ENGINES
3040 ENGINE_cleanup();
3041 #endif
3043 CONF_modules_unload(1);
3044 CRYPTO_cleanup_all_ex_data();
3046 if (n_openssl_mutexes_) {
3047 int n = n_openssl_mutexes_;
3048 tor_mutex_t **ms = openssl_mutexes_;
3049 int i;
3050 openssl_mutexes_ = NULL;
3051 n_openssl_mutexes_ = 0;
3052 for (i=0;i<n;++i) {
3053 tor_mutex_free(ms[i]);
3055 tor_free(ms);
3058 tor_free(crypto_openssl_version_str);
3059 tor_free(crypto_openssl_header_version_str);
3060 return 0;
3063 /** @} */