Give an #error when we want threads and OpenSSL has disabled threads
[tor.git] / src / common / crypto.c
blob3d8b1ba4ff3e7afeb59c523e17b1e72740c9ecec
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"
60 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
61 #error "We require OpenSSL >= 0.9.8"
62 #endif
64 #ifdef ANDROID
65 /* Android's OpenSSL seems to have removed all of its Engine support. */
66 #define DISABLE_ENGINES
67 #endif
69 /** Longest recognized */
70 #define MAX_DNS_LABEL_SIZE 63
72 /** Macro: is k a valid RSA public or private key? */
73 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
74 /** Macro: is k a valid RSA private key? */
75 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
77 #ifdef TOR_IS_MULTITHREADED
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;
82 #endif
84 /** A public key, or a public/private key-pair. */
85 struct crypto_pk_t
87 int refs; /**< reference count, so we don't have to copy keys */
88 RSA *key; /**< The key itself */
91 /** Key and stream information for a stream cipher. */
92 struct crypto_cipher_t
94 char key[CIPHER_KEY_LEN]; /**< The raw key. */
95 char iv[CIPHER_IV_LEN]; /**< The initial IV. */
96 aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
97 * encryption */
100 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
101 * while we're waiting for the second.*/
102 struct crypto_dh_t {
103 DH *dh; /**< The openssl DH object */
106 static int setup_openssl_threading(void);
107 static int tor_check_dh_key(int severity, BIGNUM *bn);
109 /** Return the number of bytes added by padding method <b>padding</b>.
111 static INLINE int
112 crypto_get_rsa_padding_overhead(int padding)
114 switch (padding)
116 case RSA_PKCS1_OAEP_PADDING: return 42;
117 case RSA_PKCS1_PADDING: return 11;
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_PADDING: return RSA_PKCS1_PADDING;
130 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
131 default: tor_assert(0); return -1;
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, "Using OpenSSL engine %s [%s] for %s",
173 name?name:"?", id?id:"?", fn);
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 static char *crypto_openssl_version_str = NULL;
201 /* Return a human-readable version of the run-time openssl version number. */
202 const char *
203 crypto_openssl_get_version_str(void)
205 if (crypto_openssl_version_str == NULL) {
206 const char *raw_version = SSLeay_version(SSLEAY_VERSION);
207 const char *end_of_version = NULL;
208 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
209 trim that down. */
210 if (!strcmpstart(raw_version, "OpenSSL ")) {
211 raw_version += strlen("OpenSSL ");
212 end_of_version = strchr(raw_version, ' ');
215 if (end_of_version)
216 crypto_openssl_version_str = tor_strndup(raw_version,
217 end_of_version-raw_version);
218 else
219 crypto_openssl_version_str = tor_strdup(raw_version);
221 return crypto_openssl_version_str;
224 /** Initialize the crypto library. Return 0 on success, -1 on failure.
227 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
229 if (!crypto_global_initialized_) {
230 ERR_load_crypto_strings();
231 OpenSSL_add_all_algorithms();
232 crypto_global_initialized_ = 1;
233 setup_openssl_threading();
235 if (SSLeay() == OPENSSL_VERSION_NUMBER &&
236 !strcmp(SSLeay_version(SSLEAY_VERSION), OPENSSL_VERSION_TEXT)) {
237 log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
238 "(%lx: %s).", SSLeay(), SSLeay_version(SSLEAY_VERSION));
239 } else {
240 log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
241 "version we're running with. If you get weird crashes, that "
242 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
243 (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
244 SSLeay(), SSLeay_version(SSLEAY_VERSION));
247 if (SSLeay() < OPENSSL_V_SERIES(1,0,0)) {
248 log_notice(LD_CRYPTO,
249 "Your OpenSSL version seems to be %s. We recommend 1.0.0 "
250 "or later.",
251 crypto_openssl_get_version_str());
254 if (useAccel > 0) {
255 #ifdef DISABLE_ENGINES
256 (void)accelName;
257 (void)accelDir;
258 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
259 #else
260 ENGINE *e = NULL;
262 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
263 ENGINE_load_builtin_engines();
264 ENGINE_register_all_complete();
266 if (accelName) {
267 if (accelDir) {
268 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
269 " via path \"%s\".", accelName, accelDir);
270 e = try_load_engine(accelName, accelDir);
271 } else {
272 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
273 " acceleration support.", accelName);
274 e = ENGINE_by_id(accelName);
276 if (!e) {
277 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
278 accelName);
279 } else {
280 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
281 accelName);
284 if (e) {
285 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
286 " setting default ciphers.");
287 ENGINE_set_default(e, ENGINE_METHOD_ALL);
289 log_engine("RSA", ENGINE_get_default_RSA());
290 log_engine("DH", ENGINE_get_default_DH());
291 log_engine("RAND", ENGINE_get_default_RAND());
292 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
293 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
294 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
295 #endif
296 } else {
297 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
300 evaluate_evp_for_aes(-1);
301 evaluate_ctr_for_aes();
303 return crypto_seed_rng(1);
305 return 0;
308 /** Free crypto resources held by this thread. */
309 void
310 crypto_thread_cleanup(void)
312 ERR_remove_state(0);
315 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
316 crypto_pk_t *
317 crypto_new_pk_from_rsa_(RSA *rsa)
319 crypto_pk_t *env;
320 tor_assert(rsa);
321 env = tor_malloc(sizeof(crypto_pk_t));
322 env->refs = 1;
323 env->key = rsa;
324 return env;
327 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
328 * crypto_pk_t. */
329 RSA *
330 crypto_pk_get_rsa_(crypto_pk_t *env)
332 return env->key;
335 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
336 * private is set, include the private-key portion of the key. */
337 EVP_PKEY *
338 crypto_pk_get_evp_pkey_(crypto_pk_t *env, int private)
340 RSA *key = NULL;
341 EVP_PKEY *pkey = NULL;
342 tor_assert(env->key);
343 if (private) {
344 if (!(key = RSAPrivateKey_dup(env->key)))
345 goto error;
346 } else {
347 if (!(key = RSAPublicKey_dup(env->key)))
348 goto error;
350 if (!(pkey = EVP_PKEY_new()))
351 goto error;
352 if (!(EVP_PKEY_assign_RSA(pkey, key)))
353 goto error;
354 return pkey;
355 error:
356 if (pkey)
357 EVP_PKEY_free(pkey);
358 if (key)
359 RSA_free(key);
360 return NULL;
363 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
365 DH *
366 crypto_dh_get_dh_(crypto_dh_t *dh)
368 return dh->dh;
371 /** Allocate and return storage for a public key. The key itself will not yet
372 * be set.
374 crypto_pk_t *
375 crypto_pk_new(void)
377 RSA *rsa;
379 rsa = RSA_new();
380 tor_assert(rsa);
381 return crypto_new_pk_from_rsa_(rsa);
384 /** Release a reference to an asymmetric key; when all the references
385 * are released, free the key.
387 void
388 crypto_pk_free(crypto_pk_t *env)
390 if (!env)
391 return;
393 if (--env->refs > 0)
394 return;
395 tor_assert(env->refs == 0);
397 if (env->key)
398 RSA_free(env->key);
400 tor_free(env);
403 /** Allocate and return a new symmetric cipher using the provided key and iv.
404 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
405 * provide NULL in place of either one, it is generated at random.
407 crypto_cipher_t *
408 crypto_cipher_new_with_iv(const char *key, const char *iv)
410 crypto_cipher_t *env;
412 env = tor_malloc_zero(sizeof(crypto_cipher_t));
414 if (key == NULL)
415 crypto_rand(env->key, CIPHER_KEY_LEN);
416 else
417 memcpy(env->key, key, CIPHER_KEY_LEN);
418 if (iv == NULL)
419 crypto_rand(env->iv, CIPHER_IV_LEN);
420 else
421 memcpy(env->iv, iv, CIPHER_IV_LEN);
423 env->cipher = aes_new_cipher(env->key, env->iv);
425 return env;
428 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
429 * zero bytes. */
430 crypto_cipher_t *
431 crypto_cipher_new(const char *key)
433 char zeroiv[CIPHER_IV_LEN];
434 memset(zeroiv, 0, sizeof(zeroiv));
435 return crypto_cipher_new_with_iv(key, zeroiv);
438 /** Free a symmetric cipher.
440 void
441 crypto_cipher_free(crypto_cipher_t *env)
443 if (!env)
444 return;
446 tor_assert(env->cipher);
447 aes_cipher_free(env->cipher);
448 memwipe(env, 0, sizeof(crypto_cipher_t));
449 tor_free(env);
452 /* public key crypto */
454 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
455 * Return 0 on success, -1 on failure.
458 crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
460 tor_assert(env);
462 if (env->key)
463 RSA_free(env->key);
466 BIGNUM *e = BN_new();
467 RSA *r = NULL;
468 if (!e)
469 goto done;
470 if (! BN_set_word(e, 65537))
471 goto done;
472 r = RSA_new();
473 if (!r)
474 goto done;
475 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
476 goto done;
478 env->key = r;
479 r = NULL;
480 done:
481 if (e)
482 BN_free(e);
483 if (r)
484 RSA_free(r);
487 if (!env->key) {
488 crypto_log_errors(LOG_WARN, "generating RSA key");
489 return -1;
492 return 0;
495 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
496 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
497 * the string is nul-terminated.
499 /* Used here, and used for testing. */
501 crypto_pk_read_private_key_from_string(crypto_pk_t *env,
502 const char *s, ssize_t len)
504 BIO *b;
506 tor_assert(env);
507 tor_assert(s);
508 tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
510 /* Create a read-only memory BIO, backed by the string 's' */
511 b = BIO_new_mem_buf((char*)s, (int)len);
512 if (!b)
513 return -1;
515 if (env->key)
516 RSA_free(env->key);
518 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
520 BIO_free(b);
522 if (!env->key) {
523 crypto_log_errors(LOG_WARN, "Error parsing private key");
524 return -1;
526 return 0;
529 /** Read a PEM-encoded private key from the file named by
530 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
533 crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
534 const char *keyfile)
536 char *contents;
537 int r;
539 /* Read the file into a string. */
540 contents = read_file_to_str(keyfile, 0, NULL);
541 if (!contents) {
542 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
543 return -1;
546 /* Try to parse it. */
547 r = crypto_pk_read_private_key_from_string(env, contents, -1);
548 memwipe(contents, 0, strlen(contents));
549 tor_free(contents);
550 if (r)
551 return -1; /* read_private_key_from_string already warned, so we don't.*/
553 /* Make sure it's valid. */
554 if (crypto_pk_check_key(env) <= 0)
555 return -1;
557 return 0;
560 /** Helper function to implement crypto_pk_write_*_key_to_string. */
561 static int
562 crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
563 size_t *len, int is_public)
565 BUF_MEM *buf;
566 BIO *b;
567 int r;
569 tor_assert(env);
570 tor_assert(env->key);
571 tor_assert(dest);
573 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
574 if (!b)
575 return -1;
577 /* Now you can treat b as if it were a file. Just use the
578 * PEM_*_bio_* functions instead of the non-bio variants.
580 if (is_public)
581 r = PEM_write_bio_RSAPublicKey(b, env->key);
582 else
583 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
585 if (!r) {
586 crypto_log_errors(LOG_WARN, "writing RSA key to string");
587 BIO_free(b);
588 return -1;
591 BIO_get_mem_ptr(b, &buf);
592 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
593 BIO_free(b);
595 *dest = tor_malloc(buf->length+1);
596 memcpy(*dest, buf->data, buf->length);
597 (*dest)[buf->length] = 0; /* nul terminate it */
598 *len = buf->length;
599 BUF_MEM_free(buf);
601 return 0;
604 /** PEM-encode the public key portion of <b>env</b> and write it to a
605 * newly allocated string. On success, set *<b>dest</b> to the new
606 * string, *<b>len</b> to the string's length, and return 0. On
607 * failure, return -1.
610 crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
611 size_t *len)
613 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
616 /** PEM-encode the private key portion of <b>env</b> and write it to a
617 * newly allocated string. On success, set *<b>dest</b> to the new
618 * string, *<b>len</b> to the string's length, and return 0. On
619 * failure, return -1.
622 crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
623 size_t *len)
625 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
628 /** Read a PEM-encoded public key from the first <b>len</b> characters of
629 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
630 * failure.
633 crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
634 size_t len)
636 BIO *b;
638 tor_assert(env);
639 tor_assert(src);
640 tor_assert(len<INT_MAX);
642 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
643 if (!b)
644 return -1;
646 BIO_write(b, src, (int)len);
648 if (env->key)
649 RSA_free(env->key);
650 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
651 BIO_free(b);
652 if (!env->key) {
653 crypto_log_errors(LOG_WARN, "reading public key from string");
654 return -1;
657 return 0;
660 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
661 * PEM-encoded. Return 0 on success, -1 on failure.
664 crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
665 const char *fname)
667 BIO *bio;
668 char *cp;
669 long len;
670 char *s;
671 int r;
673 tor_assert(PRIVATE_KEY_OK(env));
675 if (!(bio = BIO_new(BIO_s_mem())))
676 return -1;
677 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
678 == 0) {
679 crypto_log_errors(LOG_WARN, "writing private key");
680 BIO_free(bio);
681 return -1;
683 len = BIO_get_mem_data(bio, &cp);
684 tor_assert(len >= 0);
685 s = tor_malloc(len+1);
686 memcpy(s, cp, len);
687 s[len]='\0';
688 r = write_str_to_file(fname, s, 0);
689 BIO_free(bio);
690 memwipe(s, 0, strlen(s));
691 tor_free(s);
692 return r;
695 /** Return true iff <b>env</b> has a valid key.
698 crypto_pk_check_key(crypto_pk_t *env)
700 int r;
701 tor_assert(env);
703 r = RSA_check_key(env->key);
704 if (r <= 0)
705 crypto_log_errors(LOG_WARN,"checking RSA key");
706 return r;
709 /** Return true iff <b>key</b> contains the private-key portion of the RSA
710 * key. */
712 crypto_pk_key_is_private(const crypto_pk_t *key)
714 tor_assert(key);
715 return PRIVATE_KEY_OK(key);
718 /** Return true iff <b>env</b> contains a public key whose public exponent
719 * equals 65537.
722 crypto_pk_public_exponent_ok(crypto_pk_t *env)
724 tor_assert(env);
725 tor_assert(env->key);
727 return BN_is_word(env->key->e, 65537);
730 /** Compare the public-key components of a and b. Return less than 0
731 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
732 * considered to be less than all non-NULL keys, and equal to itself.
734 * Note that this may leak information about the keys through timing.
737 crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
739 int result;
740 char a_is_non_null = (a != NULL) && (a->key != NULL);
741 char b_is_non_null = (b != NULL) && (b->key != NULL);
742 char an_argument_is_null = !a_is_non_null | !b_is_non_null;
744 result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
745 if (an_argument_is_null)
746 return result;
748 tor_assert(PUBLIC_KEY_OK(a));
749 tor_assert(PUBLIC_KEY_OK(b));
750 result = BN_cmp((a->key)->n, (b->key)->n);
751 if (result)
752 return result;
753 return BN_cmp((a->key)->e, (b->key)->e);
756 /** Compare the public-key components of a and b. Return non-zero iff
757 * a==b. A NULL key is considered to be distinct from all non-NULL
758 * keys, and equal to itself.
760 * Note that this may leak information about the keys through timing.
763 crypto_pk_eq_keys(crypto_pk_t *a, crypto_pk_t *b)
765 return (crypto_pk_cmp_keys(a, b) == 0);
768 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
769 size_t
770 crypto_pk_keysize(crypto_pk_t *env)
772 tor_assert(env);
773 tor_assert(env->key);
775 return (size_t) RSA_size(env->key);
778 /** Return the size of the public key modulus of <b>env</b>, in bits. */
780 crypto_pk_num_bits(crypto_pk_t *env)
782 tor_assert(env);
783 tor_assert(env->key);
784 tor_assert(env->key->n);
786 return BN_num_bits(env->key->n);
789 /** Increase the reference count of <b>env</b>, and return it.
791 crypto_pk_t *
792 crypto_pk_dup_key(crypto_pk_t *env)
794 tor_assert(env);
795 tor_assert(env->key);
797 env->refs++;
798 return env;
801 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
802 crypto_pk_t *
803 crypto_pk_copy_full(crypto_pk_t *env)
805 RSA *new_key;
806 int privatekey = 0;
807 tor_assert(env);
808 tor_assert(env->key);
810 if (PRIVATE_KEY_OK(env)) {
811 new_key = RSAPrivateKey_dup(env->key);
812 privatekey = 1;
813 } else {
814 new_key = RSAPublicKey_dup(env->key);
816 if (!new_key) {
817 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
818 privatekey?"private":"public");
819 crypto_log_errors(LOG_ERR,
820 privatekey ? "Duplicating a private key" :
821 "Duplicating a public key");
822 tor_fragile_assert();
823 return NULL;
826 return crypto_new_pk_from_rsa_(new_key);
829 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
830 * in <b>env</b>, using the padding method <b>padding</b>. On success,
831 * write the result to <b>to</b>, and return the number of bytes
832 * written. On failure, return -1.
834 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
835 * at least the length of the modulus of <b>env</b>.
838 crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
839 const char *from, size_t fromlen, int padding)
841 int r;
842 tor_assert(env);
843 tor_assert(from);
844 tor_assert(to);
845 tor_assert(fromlen<INT_MAX);
846 tor_assert(tolen >= crypto_pk_keysize(env));
848 r = RSA_public_encrypt((int)fromlen,
849 (unsigned char*)from, (unsigned char*)to,
850 env->key, crypto_get_rsa_padding(padding));
851 if (r<0) {
852 crypto_log_errors(LOG_WARN, "performing RSA encryption");
853 return -1;
855 return r;
858 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
859 * in <b>env</b>, using the padding method <b>padding</b>. On success,
860 * write the result to <b>to</b>, and return the number of bytes
861 * written. On failure, return -1.
863 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
864 * at least the length of the modulus of <b>env</b>.
867 crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
868 size_t tolen,
869 const char *from, size_t fromlen,
870 int padding, int warnOnFailure)
872 int r;
873 tor_assert(env);
874 tor_assert(from);
875 tor_assert(to);
876 tor_assert(env->key);
877 tor_assert(fromlen<INT_MAX);
878 tor_assert(tolen >= crypto_pk_keysize(env));
879 if (!env->key->p)
880 /* Not a private key */
881 return -1;
883 r = RSA_private_decrypt((int)fromlen,
884 (unsigned char*)from, (unsigned char*)to,
885 env->key, crypto_get_rsa_padding(padding));
887 if (r<0) {
888 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
889 "performing RSA decryption");
890 return -1;
892 return r;
895 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
896 * public key in <b>env</b>, using PKCS1 padding. On success, write the
897 * signed data to <b>to</b>, and return the number of bytes written.
898 * On failure, return -1.
900 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
901 * at least the length of the modulus of <b>env</b>.
904 crypto_pk_public_checksig(crypto_pk_t *env, char *to,
905 size_t tolen,
906 const char *from, size_t fromlen)
908 int r;
909 tor_assert(env);
910 tor_assert(from);
911 tor_assert(to);
912 tor_assert(fromlen < INT_MAX);
913 tor_assert(tolen >= crypto_pk_keysize(env));
914 r = RSA_public_decrypt((int)fromlen,
915 (unsigned char*)from, (unsigned char*)to,
916 env->key, RSA_PKCS1_PADDING);
918 if (r<0) {
919 crypto_log_errors(LOG_WARN, "checking RSA signature");
920 return -1;
922 return r;
925 /** Check a siglen-byte long signature at <b>sig</b> against
926 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
927 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
928 * SHA1(data). Else return -1.
931 crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
932 size_t datalen, const char *sig, size_t siglen)
934 char digest[DIGEST_LEN];
935 char *buf;
936 size_t buflen;
937 int r;
939 tor_assert(env);
940 tor_assert(data);
941 tor_assert(sig);
942 tor_assert(datalen < SIZE_T_CEILING);
943 tor_assert(siglen < SIZE_T_CEILING);
945 if (crypto_digest(digest,data,datalen)<0) {
946 log_warn(LD_BUG, "couldn't compute digest");
947 return -1;
949 buflen = crypto_pk_keysize(env);
950 buf = tor_malloc(buflen);
951 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
952 if (r != DIGEST_LEN) {
953 log_warn(LD_CRYPTO, "Invalid signature");
954 tor_free(buf);
955 return -1;
957 if (tor_memneq(buf, digest, DIGEST_LEN)) {
958 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
959 tor_free(buf);
960 return -1;
962 tor_free(buf);
964 return 0;
967 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
968 * <b>env</b>, using PKCS1 padding. On success, write the signature to
969 * <b>to</b>, and return the number of bytes written. On failure, return
970 * -1.
972 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
973 * at least the length of the modulus of <b>env</b>.
976 crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
977 const char *from, size_t fromlen)
979 int r;
980 tor_assert(env);
981 tor_assert(from);
982 tor_assert(to);
983 tor_assert(fromlen < INT_MAX);
984 tor_assert(tolen >= crypto_pk_keysize(env));
985 if (!env->key->p)
986 /* Not a private key */
987 return -1;
989 r = RSA_private_encrypt((int)fromlen,
990 (unsigned char*)from, (unsigned char*)to,
991 env->key, RSA_PKCS1_PADDING);
992 if (r<0) {
993 crypto_log_errors(LOG_WARN, "generating RSA signature");
994 return -1;
996 return r;
999 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1000 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1001 * store it in <b>to</b>. Return the number of bytes written on
1002 * success, and -1 on failure.
1004 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1005 * at least the length of the modulus of <b>env</b>.
1008 crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
1009 const char *from, size_t fromlen)
1011 int r;
1012 char digest[DIGEST_LEN];
1013 if (crypto_digest(digest,from,fromlen)<0)
1014 return -1;
1015 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
1016 memwipe(digest, 0, sizeof(digest));
1017 return r;
1020 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1021 * bytes of data from <b>from</b>, with padding type 'padding',
1022 * storing the results on <b>to</b>.
1024 * Returns the number of bytes written on success, -1 on failure.
1026 * The encrypted data consists of:
1027 * - The source data, padded and encrypted with the public key, if the
1028 * padded source data is no longer than the public key, and <b>force</b>
1029 * is false, OR
1030 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1031 * padded and encrypted with the public key; followed by the rest of
1032 * the source data encrypted in AES-CTR mode with the symmetric key.
1035 crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
1036 char *to, size_t tolen,
1037 const char *from,
1038 size_t fromlen,
1039 int padding, int force)
1041 int overhead, outlen, r;
1042 size_t pkeylen, symlen;
1043 crypto_cipher_t *cipher = NULL;
1044 char *buf = NULL;
1046 tor_assert(env);
1047 tor_assert(from);
1048 tor_assert(to);
1049 tor_assert(fromlen < SIZE_T_CEILING);
1051 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1052 pkeylen = crypto_pk_keysize(env);
1054 if (!force && fromlen+overhead <= pkeylen) {
1055 /* It all fits in a single encrypt. */
1056 return crypto_pk_public_encrypt(env,to,
1057 tolen,
1058 from,fromlen,padding);
1060 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1061 tor_assert(tolen >= pkeylen);
1063 cipher = crypto_cipher_new(NULL); /* generate a new key. */
1065 buf = tor_malloc(pkeylen+1);
1066 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1067 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1069 /* Length of symmetrically encrypted data. */
1070 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1072 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1073 if (outlen!=(int)pkeylen) {
1074 goto err;
1076 r = crypto_cipher_encrypt(cipher, to+outlen,
1077 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1079 if (r<0) goto err;
1080 memwipe(buf, 0, pkeylen);
1081 tor_free(buf);
1082 crypto_cipher_free(cipher);
1083 tor_assert(outlen+symlen < INT_MAX);
1084 return (int)(outlen + symlen);
1085 err:
1087 memwipe(buf, 0, pkeylen);
1088 tor_free(buf);
1089 crypto_cipher_free(cipher);
1090 return -1;
1093 /** Invert crypto_pk_public_hybrid_encrypt. */
1095 crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
1096 char *to,
1097 size_t tolen,
1098 const char *from,
1099 size_t fromlen,
1100 int padding, int warnOnFailure)
1102 int outlen, r;
1103 size_t pkeylen;
1104 crypto_cipher_t *cipher = NULL;
1105 char *buf = NULL;
1107 tor_assert(fromlen < SIZE_T_CEILING);
1108 pkeylen = crypto_pk_keysize(env);
1110 if (fromlen <= pkeylen) {
1111 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1112 warnOnFailure);
1115 buf = tor_malloc(pkeylen);
1116 outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
1117 warnOnFailure);
1118 if (outlen<0) {
1119 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1120 "Error decrypting public-key data");
1121 goto err;
1123 if (outlen < CIPHER_KEY_LEN) {
1124 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1125 "No room for a symmetric key");
1126 goto err;
1128 cipher = crypto_cipher_new(buf);
1129 if (!cipher) {
1130 goto err;
1132 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1133 outlen -= CIPHER_KEY_LEN;
1134 tor_assert(tolen - outlen >= fromlen - pkeylen);
1135 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1136 if (r<0)
1137 goto err;
1138 memwipe(buf,0,pkeylen);
1139 tor_free(buf);
1140 crypto_cipher_free(cipher);
1141 tor_assert(outlen + fromlen < INT_MAX);
1142 return (int)(outlen + (fromlen-pkeylen));
1143 err:
1144 memwipe(buf,0,pkeylen);
1145 tor_free(buf);
1146 crypto_cipher_free(cipher);
1147 return -1;
1150 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1151 * Return -1 on error, or the number of characters used on success.
1154 crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
1156 int len;
1157 unsigned char *buf, *cp;
1158 len = i2d_RSAPublicKey(pk->key, NULL);
1159 if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
1160 return -1;
1161 cp = buf = tor_malloc(len+1);
1162 len = i2d_RSAPublicKey(pk->key, &cp);
1163 if (len < 0) {
1164 crypto_log_errors(LOG_WARN,"encoding public key");
1165 tor_free(buf);
1166 return -1;
1168 /* We don't encode directly into 'dest', because that would be illegal
1169 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1171 memcpy(dest,buf,len);
1172 tor_free(buf);
1173 return len;
1176 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1177 * success and NULL on failure.
1179 crypto_pk_t *
1180 crypto_pk_asn1_decode(const char *str, size_t len)
1182 RSA *rsa;
1183 unsigned char *buf;
1184 const unsigned char *cp;
1185 cp = buf = tor_malloc(len);
1186 memcpy(buf,str,len);
1187 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1188 tor_free(buf);
1189 if (!rsa) {
1190 crypto_log_errors(LOG_WARN,"decoding public key");
1191 return NULL;
1193 return crypto_new_pk_from_rsa_(rsa);
1196 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1197 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1198 * Return 0 on success, -1 on failure.
1201 crypto_pk_get_digest(crypto_pk_t *pk, char *digest_out)
1203 unsigned char *buf, *bufp;
1204 int len;
1206 len = i2d_RSAPublicKey(pk->key, NULL);
1207 if (len < 0)
1208 return -1;
1209 buf = bufp = tor_malloc(len+1);
1210 len = i2d_RSAPublicKey(pk->key, &bufp);
1211 if (len < 0) {
1212 crypto_log_errors(LOG_WARN,"encoding public key");
1213 tor_free(buf);
1214 return -1;
1216 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1217 tor_free(buf);
1218 return -1;
1220 tor_free(buf);
1221 return 0;
1224 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1225 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1227 crypto_pk_get_all_digests(crypto_pk_t *pk, digests_t *digests_out)
1229 unsigned char *buf, *bufp;
1230 int len;
1232 len = i2d_RSAPublicKey(pk->key, NULL);
1233 if (len < 0)
1234 return -1;
1235 buf = bufp = tor_malloc(len+1);
1236 len = i2d_RSAPublicKey(pk->key, &bufp);
1237 if (len < 0) {
1238 crypto_log_errors(LOG_WARN,"encoding public key");
1239 tor_free(buf);
1240 return -1;
1242 if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
1243 tor_free(buf);
1244 return -1;
1246 tor_free(buf);
1247 return 0;
1250 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1251 * every four spaces. */
1252 /* static */ void
1253 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1255 int n = 0;
1256 char *end = out+outlen;
1257 tor_assert(outlen < SIZE_T_CEILING);
1259 while (*in && out<end) {
1260 *out++ = *in++;
1261 if (++n == 4 && *in && out<end) {
1262 n = 0;
1263 *out++ = ' ';
1266 tor_assert(out<end);
1267 *out = '\0';
1270 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1271 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1272 * space). Return 0 on success, -1 on failure.
1274 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1275 * of the public key, converted to hexadecimal, in upper case, with a
1276 * space after every four digits.
1278 * If <b>add_space</b> is false, omit the spaces.
1281 crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
1283 char digest[DIGEST_LEN];
1284 char hexdigest[HEX_DIGEST_LEN+1];
1285 if (crypto_pk_get_digest(pk, digest)) {
1286 return -1;
1288 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1289 if (add_space) {
1290 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1291 } else {
1292 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1294 return 0;
1297 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1300 crypto_pk_check_fingerprint_syntax(const char *s)
1302 int i;
1303 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1304 if ((i%5) == 4) {
1305 if (!TOR_ISSPACE(s[i])) return 0;
1306 } else {
1307 if (!TOR_ISXDIGIT(s[i])) return 0;
1310 if (s[FINGERPRINT_LEN]) return 0;
1311 return 1;
1314 /* symmetric crypto */
1316 /** Return a pointer to the key set for the cipher in <b>env</b>.
1318 const char *
1319 crypto_cipher_get_key(crypto_cipher_t *env)
1321 return env->key;
1324 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1325 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1326 * On failure, return -1.
1329 crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
1330 const char *from, size_t fromlen)
1332 tor_assert(env);
1333 tor_assert(env->cipher);
1334 tor_assert(from);
1335 tor_assert(fromlen);
1336 tor_assert(to);
1337 tor_assert(fromlen < SIZE_T_CEILING);
1339 aes_crypt(env->cipher, from, fromlen, to);
1340 return 0;
1343 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1344 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1345 * On failure, return -1.
1348 crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
1349 const char *from, size_t fromlen)
1351 tor_assert(env);
1352 tor_assert(from);
1353 tor_assert(to);
1354 tor_assert(fromlen < SIZE_T_CEILING);
1356 aes_crypt(env->cipher, from, fromlen, to);
1357 return 0;
1360 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1361 * on success, return 0. On failure, return -1.
1364 crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
1366 tor_assert(len < SIZE_T_CEILING);
1367 aes_crypt_inplace(env->cipher, buf, len);
1368 return 0;
1371 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1372 * <b>key</b> to the buffer in <b>to</b> of length
1373 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1374 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1375 * number of bytes written, on failure, return -1.
1378 crypto_cipher_encrypt_with_iv(const char *key,
1379 char *to, size_t tolen,
1380 const char *from, size_t fromlen)
1382 crypto_cipher_t *cipher;
1383 tor_assert(from);
1384 tor_assert(to);
1385 tor_assert(fromlen < INT_MAX);
1387 if (fromlen < 1)
1388 return -1;
1389 if (tolen < fromlen + CIPHER_IV_LEN)
1390 return -1;
1392 cipher = crypto_cipher_new_with_iv(key, NULL);
1394 memcpy(to, cipher->iv, CIPHER_IV_LEN);
1395 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1396 crypto_cipher_free(cipher);
1397 return (int)(fromlen + CIPHER_IV_LEN);
1400 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1401 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1402 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1403 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1404 * number of bytes written, on failure, return -1.
1407 crypto_cipher_decrypt_with_iv(const char *key,
1408 char *to, size_t tolen,
1409 const char *from, size_t fromlen)
1411 crypto_cipher_t *cipher;
1412 tor_assert(key);
1413 tor_assert(from);
1414 tor_assert(to);
1415 tor_assert(fromlen < INT_MAX);
1417 if (fromlen <= CIPHER_IV_LEN)
1418 return -1;
1419 if (tolen < fromlen - CIPHER_IV_LEN)
1420 return -1;
1422 cipher = crypto_cipher_new_with_iv(key, from);
1424 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1425 crypto_cipher_free(cipher);
1426 return (int)(fromlen - CIPHER_IV_LEN);
1429 /* SHA-1 */
1431 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1432 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1433 * Return 0 on success, -1 on failure.
1436 crypto_digest(char *digest, const char *m, size_t len)
1438 tor_assert(m);
1439 tor_assert(digest);
1440 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1443 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1444 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1445 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1447 crypto_digest256(char *digest, const char *m, size_t len,
1448 digest_algorithm_t algorithm)
1450 tor_assert(m);
1451 tor_assert(digest);
1452 tor_assert(algorithm == DIGEST_SHA256);
1453 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1456 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1457 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1458 * success, -1 on failure. */
1460 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1462 int i;
1463 tor_assert(ds_out);
1464 memset(ds_out, 0, sizeof(*ds_out));
1465 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1466 return -1;
1467 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1468 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1469 return -1;
1471 return 0;
1474 /** Return the name of an algorithm, as used in directory documents. */
1475 const char *
1476 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1478 switch (alg) {
1479 case DIGEST_SHA1:
1480 return "sha1";
1481 case DIGEST_SHA256:
1482 return "sha256";
1483 default:
1484 tor_fragile_assert();
1485 return "??unknown_digest??";
1489 /** Given the name of a digest algorithm, return its integer value, or -1 if
1490 * the name is not recognized. */
1492 crypto_digest_algorithm_parse_name(const char *name)
1494 if (!strcmp(name, "sha1"))
1495 return DIGEST_SHA1;
1496 else if (!strcmp(name, "sha256"))
1497 return DIGEST_SHA256;
1498 else
1499 return -1;
1502 /** Intermediate information about the digest of a stream of data. */
1503 struct crypto_digest_t {
1504 union {
1505 SHA_CTX sha1; /**< state for SHA1 */
1506 SHA256_CTX sha2; /**< state for SHA256 */
1507 } d; /**< State for the digest we're using. Only one member of the
1508 * union is usable, depending on the value of <b>algorithm</b>. */
1509 ENUM_BF(digest_algorithm_t) algorithm : 8; /**< Which algorithm is in use? */
1512 /** Allocate and return a new digest object to compute SHA1 digests.
1514 crypto_digest_t *
1515 crypto_digest_new(void)
1517 crypto_digest_t *r;
1518 r = tor_malloc(sizeof(crypto_digest_t));
1519 SHA1_Init(&r->d.sha1);
1520 r->algorithm = DIGEST_SHA1;
1521 return r;
1524 /** Allocate and return a new digest object to compute 256-bit digests
1525 * using <b>algorithm</b>. */
1526 crypto_digest_t *
1527 crypto_digest256_new(digest_algorithm_t algorithm)
1529 crypto_digest_t *r;
1530 tor_assert(algorithm == DIGEST_SHA256);
1531 r = tor_malloc(sizeof(crypto_digest_t));
1532 SHA256_Init(&r->d.sha2);
1533 r->algorithm = algorithm;
1534 return r;
1537 /** Deallocate a digest object.
1539 void
1540 crypto_digest_free(crypto_digest_t *digest)
1542 if (!digest)
1543 return;
1544 memwipe(digest, 0, sizeof(crypto_digest_t));
1545 tor_free(digest);
1548 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1550 void
1551 crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
1552 size_t len)
1554 tor_assert(digest);
1555 tor_assert(data);
1556 /* Using the SHA*_*() calls directly means we don't support doing
1557 * SHA in hardware. But so far the delay of getting the question
1558 * to the hardware, and hearing the answer, is likely higher than
1559 * just doing it ourselves. Hashes are fast.
1561 switch (digest->algorithm) {
1562 case DIGEST_SHA1:
1563 SHA1_Update(&digest->d.sha1, (void*)data, len);
1564 break;
1565 case DIGEST_SHA256:
1566 SHA256_Update(&digest->d.sha2, (void*)data, len);
1567 break;
1568 default:
1569 tor_fragile_assert();
1570 break;
1574 /** Compute the hash of the data that has been passed to the digest
1575 * object; write the first out_len bytes of the result to <b>out</b>.
1576 * <b>out_len</b> must be \<= DIGEST256_LEN.
1578 void
1579 crypto_digest_get_digest(crypto_digest_t *digest,
1580 char *out, size_t out_len)
1582 unsigned char r[DIGEST256_LEN];
1583 crypto_digest_t tmpenv;
1584 tor_assert(digest);
1585 tor_assert(out);
1586 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1587 memcpy(&tmpenv, digest, sizeof(crypto_digest_t));
1588 switch (digest->algorithm) {
1589 case DIGEST_SHA1:
1590 tor_assert(out_len <= DIGEST_LEN);
1591 SHA1_Final(r, &tmpenv.d.sha1);
1592 break;
1593 case DIGEST_SHA256:
1594 tor_assert(out_len <= DIGEST256_LEN);
1595 SHA256_Final(r, &tmpenv.d.sha2);
1596 break;
1597 default:
1598 log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
1599 /* If fragile_assert is not enabled, then we should at least not
1600 * leak anything. */
1601 memset(r, 0xff, sizeof(r));
1602 tor_fragile_assert();
1603 break;
1605 memcpy(out, r, out_len);
1606 memwipe(r, 0, sizeof(r));
1609 /** Allocate and return a new digest object with the same state as
1610 * <b>digest</b>
1612 crypto_digest_t *
1613 crypto_digest_dup(const crypto_digest_t *digest)
1615 crypto_digest_t *r;
1616 tor_assert(digest);
1617 r = tor_malloc(sizeof(crypto_digest_t));
1618 memcpy(r,digest,sizeof(crypto_digest_t));
1619 return r;
1622 /** Replace the state of the digest object <b>into</b> with the state
1623 * of the digest object <b>from</b>.
1625 void
1626 crypto_digest_assign(crypto_digest_t *into,
1627 const crypto_digest_t *from)
1629 tor_assert(into);
1630 tor_assert(from);
1631 memcpy(into,from,sizeof(crypto_digest_t));
1634 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1635 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1636 * in <b>hmac_out</b>.
1638 void
1639 crypto_hmac_sha1(char *hmac_out,
1640 const char *key, size_t key_len,
1641 const char *msg, size_t msg_len)
1643 tor_assert(key_len < INT_MAX);
1644 tor_assert(msg_len < INT_MAX);
1645 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1646 (unsigned char*)hmac_out, NULL);
1649 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1650 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
1651 * result in <b>hmac_out</b>.
1653 void
1654 crypto_hmac_sha256(char *hmac_out,
1655 const char *key, size_t key_len,
1656 const char *msg, size_t msg_len)
1658 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1659 tor_assert(key_len < INT_MAX);
1660 tor_assert(msg_len < INT_MAX);
1661 HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1662 (unsigned char*)hmac_out, NULL);
1665 /* DH */
1667 /** Our DH 'g' parameter */
1668 #define DH_GENERATOR 2
1670 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1671 static BIGNUM *dh_param_p = NULL;
1672 /** Shared P parameter for our TLS DH key exchanges. */
1673 static BIGNUM *dh_param_p_tls = NULL;
1674 /** Shared G parameter for our DH key exchanges. */
1675 static BIGNUM *dh_param_g = NULL;
1677 /** Generate and return a reasonable and safe DH parameter p. */
1678 static BIGNUM *
1679 crypto_generate_dynamic_dh_modulus(void)
1681 BIGNUM *dynamic_dh_modulus;
1682 DH *dh_parameters;
1683 int r, dh_codes;
1684 char *s;
1686 dynamic_dh_modulus = BN_new();
1687 tor_assert(dynamic_dh_modulus);
1689 dh_parameters = DH_generate_parameters(DH_BYTES*8, DH_GENERATOR, NULL, NULL);
1690 tor_assert(dh_parameters);
1692 r = DH_check(dh_parameters, &dh_codes);
1693 tor_assert(r && !dh_codes);
1695 BN_copy(dynamic_dh_modulus, dh_parameters->p);
1696 tor_assert(dynamic_dh_modulus);
1698 DH_free(dh_parameters);
1700 { /* log the dynamic DH modulus: */
1701 s = BN_bn2hex(dynamic_dh_modulus);
1702 tor_assert(s);
1703 log_info(LD_OR, "Dynamic DH modulus generated: [%s]", s);
1704 OPENSSL_free(s);
1707 return dynamic_dh_modulus;
1710 /** Store our dynamic DH modulus (and its group parameters) to
1711 <b>fname</b> for future use. */
1712 static int
1713 crypto_store_dynamic_dh_modulus(const char *fname)
1715 int len, new_len;
1716 DH *dh = NULL;
1717 unsigned char *dh_string_repr = NULL, *cp = NULL;
1718 char *base64_encoded_dh = NULL;
1719 char *file_string = NULL;
1720 int retval = -1;
1721 static const char file_header[] = "# This file contains stored Diffie-"
1722 "Hellman parameters for future use.\n# You *do not* need to edit this "
1723 "file.\n\n";
1725 tor_assert(fname);
1727 if (!dh_param_p_tls) {
1728 log_info(LD_CRYPTO, "Tried to store a DH modulus that does not exist.");
1729 goto done;
1732 if (!(dh = DH_new()))
1733 goto done;
1734 if (!(dh->p = BN_dup(dh_param_p_tls)))
1735 goto done;
1736 if (!(dh->g = BN_new()))
1737 goto done;
1738 if (!BN_set_word(dh->g, DH_GENERATOR))
1739 goto done;
1741 len = i2d_DHparams(dh, NULL);
1742 if (len < 0) {
1743 log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (1).");
1744 goto done;
1747 cp = dh_string_repr = tor_malloc_zero(len+1);
1748 len = i2d_DHparams(dh, &cp);
1749 if ((len < 0) || ((cp - dh_string_repr) != len)) {
1750 log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (2).");
1751 goto done;
1754 base64_encoded_dh = tor_malloc_zero(len * 2); /* should be enough */
1755 new_len = base64_encode(base64_encoded_dh, len * 2,
1756 (char *)dh_string_repr, len);
1757 if (new_len < 0) {
1758 log_warn(LD_CRYPTO, "Error occured while base64-encoding DH modulus.");
1759 goto done;
1762 /* concatenate file header and the dh parameters blob */
1763 new_len = tor_asprintf(&file_string, "%s%s", file_header, base64_encoded_dh);
1765 /* write to file */
1766 if (write_bytes_to_new_file(fname, file_string, new_len, 0) < 0) {
1767 log_info(LD_CRYPTO, "'%s' was already occupied.", fname);
1768 goto done;
1771 retval = 0;
1773 done:
1774 if (dh)
1775 DH_free(dh);
1776 tor_free(dh_string_repr);
1777 tor_free(base64_encoded_dh);
1778 tor_free(file_string);
1780 return retval;
1783 /** Return the dynamic DH modulus stored in <b>fname</b>. If there is no
1784 dynamic DH modulus stored in <b>fname</b>, return NULL. */
1785 static BIGNUM *
1786 crypto_get_stored_dynamic_dh_modulus(const char *fname)
1788 int retval;
1789 char *contents = NULL;
1790 const char *contents_tmp = NULL;
1791 int dh_codes;
1792 DH *stored_dh = NULL;
1793 BIGNUM *dynamic_dh_modulus = NULL;
1794 int length = 0;
1795 unsigned char *base64_decoded_dh = NULL;
1796 const unsigned char *cp = NULL;
1798 tor_assert(fname);
1800 contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
1801 if (!contents) {
1802 log_info(LD_CRYPTO, "Could not open file '%s'", fname);
1803 goto done; /*usually means that ENOENT. don't try to move file to broken.*/
1806 /* skip the file header */
1807 contents_tmp = eat_whitespace(contents);
1808 if (!*contents_tmp) {
1809 log_warn(LD_CRYPTO, "Stored dynamic DH modulus file "
1810 "seems corrupted (eat_whitespace).");
1811 goto err;
1814 /* 'fname' contains the DH parameters stored in base64-ed DER
1815 * format. We are only interested in the DH modulus.
1816 * NOTE: We allocate more storage here than we need. Since we're already
1817 * doing that, we can also add 1 byte extra to appease Coverity's
1818 * scanner. */
1820 cp = base64_decoded_dh = tor_malloc_zero(strlen(contents_tmp) + 1);
1821 length = base64_decode((char *)base64_decoded_dh, strlen(contents_tmp),
1822 contents_tmp, strlen(contents_tmp));
1823 if (length < 0) {
1824 log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (base64).");
1825 goto err;
1828 stored_dh = d2i_DHparams(NULL, &cp, length);
1829 if ((!stored_dh) || (cp - base64_decoded_dh != length)) {
1830 log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (d2i).");
1831 goto err;
1834 { /* check the cryptographic qualities of the stored dynamic DH modulus: */
1835 retval = DH_check(stored_dh, &dh_codes);
1836 if (!retval || dh_codes) {
1837 log_warn(LD_CRYPTO, "Stored dynamic DH modulus is not a safe prime.");
1838 goto err;
1841 retval = DH_size(stored_dh);
1842 if (retval < DH_BYTES) {
1843 log_warn(LD_CRYPTO, "Stored dynamic DH modulus is smaller "
1844 "than '%d' bits.", DH_BYTES*8);
1845 goto err;
1848 if (!BN_is_word(stored_dh->g, 2)) {
1849 log_warn(LD_CRYPTO, "Stored dynamic DH parameters do not use '2' "
1850 "as the group generator.");
1851 goto err;
1855 { /* log the dynamic DH modulus: */
1856 char *s = BN_bn2hex(stored_dh->p);
1857 tor_assert(s);
1858 log_info(LD_OR, "Found stored dynamic DH modulus: [%s]", s);
1859 OPENSSL_free(s);
1862 goto done;
1864 err:
1867 /* move broken prime to $filename.broken */
1868 char *fname_new=NULL;
1869 tor_asprintf(&fname_new, "%s.broken", fname);
1871 log_warn(LD_CRYPTO, "Moving broken dynamic DH prime to '%s'.", fname_new);
1873 if (replace_file(fname, fname_new))
1874 log_notice(LD_CRYPTO, "Error while moving '%s' to '%s'.",
1875 fname, fname_new);
1877 tor_free(fname_new);
1880 if (stored_dh) {
1881 DH_free(stored_dh);
1882 stored_dh = NULL;
1885 done:
1886 tor_free(contents);
1887 tor_free(base64_decoded_dh);
1889 if (stored_dh) {
1890 dynamic_dh_modulus = BN_dup(stored_dh->p);
1891 DH_free(stored_dh);
1894 return dynamic_dh_modulus;
1897 /** Set the global TLS Diffie-Hellman modulus.
1898 * If <b>dynamic_dh_modulus_fname</b> is set, try to read a dynamic DH modulus
1899 * off it and use it as the DH modulus. If that's not possible,
1900 * generate a new dynamic DH modulus.
1901 * If <b>dynamic_dh_modulus_fname</b> is NULL, use the Apache mod_ssl DH
1902 * modulus. */
1903 void
1904 crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname)
1906 BIGNUM *tls_prime = NULL;
1907 int store_dh_prime_afterwards = 0;
1908 int r;
1910 /* If the space is occupied, free the previous TLS DH prime */
1911 if (dh_param_p_tls) {
1912 BN_free(dh_param_p_tls);
1913 dh_param_p_tls = NULL;
1916 if (dynamic_dh_modulus_fname) { /* use dynamic DH modulus: */
1917 log_info(LD_OR, "Using stored dynamic DH modulus.");
1918 tls_prime = crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname);
1920 if (!tls_prime) {
1921 log_notice(LD_OR, "Generating fresh dynamic DH modulus. "
1922 "This might take a while...");
1923 tls_prime = crypto_generate_dynamic_dh_modulus();
1925 store_dh_prime_afterwards++;
1927 } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
1928 tls_prime = BN_new();
1929 tor_assert(tls_prime);
1931 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1932 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
1933 * prime.
1935 r =BN_hex2bn(&tls_prime,
1936 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1937 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1938 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1939 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1940 "B0E7393E0F24218EB3");
1941 tor_assert(r);
1944 tor_assert(tls_prime);
1946 dh_param_p_tls = tls_prime;
1948 if (store_dh_prime_afterwards)
1949 /* save the new dynamic DH modulus to disk. */
1950 if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname)) {
1951 log_notice(LD_CRYPTO, "Failed while storing dynamic DH modulus. "
1952 "Make sure your data directory is sane.");
1956 /** Initialize dh_param_p and dh_param_g if they are not already
1957 * set. */
1958 static void
1959 init_dh_param(void)
1961 BIGNUM *circuit_dh_prime, *generator;
1962 int r;
1963 if (dh_param_p && dh_param_g)
1964 return;
1966 circuit_dh_prime = BN_new();
1967 generator = BN_new();
1968 tor_assert(circuit_dh_prime && generator);
1970 /* Set our generator for all DH parameters */
1971 r = BN_set_word(generator, DH_GENERATOR);
1972 tor_assert(r);
1974 /* This is from rfc2409, section 6.2. It's a safe prime, and
1975 supposedly it equals:
1976 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1978 r = BN_hex2bn(&circuit_dh_prime,
1979 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1980 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1981 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1982 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1983 "49286651ECE65381FFFFFFFFFFFFFFFF");
1984 tor_assert(r);
1986 /* Set the new values as the global DH parameters. */
1987 dh_param_p = circuit_dh_prime;
1988 dh_param_g = generator;
1990 /* Ensure that we have TLS DH parameters set up, too, even if we're
1991 going to change them soon. */
1992 if (!dh_param_p_tls) {
1993 crypto_set_tls_dh_prime(NULL);
1997 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
1998 * handshake. Since we exponentiate by this value, choosing a smaller one
1999 * lets our handhake go faster.
2001 #define DH_PRIVATE_KEY_BITS 320
2003 /** Allocate and return a new DH object for a key exchange.
2005 crypto_dh_t *
2006 crypto_dh_new(int dh_type)
2008 crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
2010 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
2011 dh_type == DH_TYPE_REND);
2013 if (!dh_param_p)
2014 init_dh_param();
2016 if (!(res->dh = DH_new()))
2017 goto err;
2019 if (dh_type == DH_TYPE_TLS) {
2020 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
2021 goto err;
2022 } else {
2023 if (!(res->dh->p = BN_dup(dh_param_p)))
2024 goto err;
2027 if (!(res->dh->g = BN_dup(dh_param_g)))
2028 goto err;
2030 res->dh->length = DH_PRIVATE_KEY_BITS;
2032 return res;
2033 err:
2034 crypto_log_errors(LOG_WARN, "creating DH object");
2035 if (res->dh) DH_free(res->dh); /* frees p and g too */
2036 tor_free(res);
2037 return NULL;
2040 /** Return a copy of <b>dh</b>, sharing its internal state. */
2041 crypto_dh_t *
2042 crypto_dh_dup(const crypto_dh_t *dh)
2044 crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
2045 dh_new->dh = dh->dh;
2046 DH_up_ref(dh->dh);
2047 return dh_new;
2050 /** Return the length of the DH key in <b>dh</b>, in bytes.
2053 crypto_dh_get_bytes(crypto_dh_t *dh)
2055 tor_assert(dh);
2056 return DH_size(dh->dh);
2059 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2060 * success, -1 on failure.
2063 crypto_dh_generate_public(crypto_dh_t *dh)
2065 again:
2066 if (!DH_generate_key(dh->dh)) {
2067 crypto_log_errors(LOG_WARN, "generating DH key");
2068 return -1;
2070 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
2071 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
2072 "the-universe chances really do happen. Trying again.");
2073 /* Free and clear the keys, so OpenSSL will actually try again. */
2074 BN_free(dh->dh->pub_key);
2075 BN_free(dh->dh->priv_key);
2076 dh->dh->pub_key = dh->dh->priv_key = NULL;
2077 goto again;
2079 return 0;
2082 /** Generate g^x as necessary, and write the g^x for the key exchange
2083 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2084 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2087 crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
2089 int bytes;
2090 tor_assert(dh);
2091 if (!dh->dh->pub_key) {
2092 if (crypto_dh_generate_public(dh)<0)
2093 return -1;
2096 tor_assert(dh->dh->pub_key);
2097 bytes = BN_num_bytes(dh->dh->pub_key);
2098 tor_assert(bytes >= 0);
2099 if (pubkey_len < (size_t)bytes) {
2100 log_warn(LD_CRYPTO,
2101 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2102 (int) pubkey_len, bytes);
2103 return -1;
2106 memset(pubkey, 0, pubkey_len);
2107 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
2109 return 0;
2112 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2113 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2114 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2116 static int
2117 tor_check_dh_key(int severity, BIGNUM *bn)
2119 BIGNUM *x;
2120 char *s;
2121 tor_assert(bn);
2122 x = BN_new();
2123 tor_assert(x);
2124 if (!dh_param_p)
2125 init_dh_param();
2126 BN_set_word(x, 1);
2127 if (BN_cmp(bn,x)<=0) {
2128 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
2129 goto err;
2131 BN_copy(x,dh_param_p);
2132 BN_sub_word(x, 1);
2133 if (BN_cmp(bn,x)>=0) {
2134 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
2135 goto err;
2137 BN_free(x);
2138 return 0;
2139 err:
2140 BN_free(x);
2141 s = BN_bn2hex(bn);
2142 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
2143 OPENSSL_free(s);
2144 return -1;
2147 #undef MIN
2148 #define MIN(a,b) ((a)<(b)?(a):(b))
2149 /** Given a DH key exchange object, and our peer's value of g^y (as a
2150 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2151 * <b>secret_bytes_out</b> bytes of shared key material and write them
2152 * to <b>secret_out</b>. Return the number of bytes generated on success,
2153 * or -1 on failure.
2155 * (We generate key material by computing
2156 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2157 * where || is concatenation.)
2159 ssize_t
2160 crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
2161 const char *pubkey, size_t pubkey_len,
2162 char *secret_out, size_t secret_bytes_out)
2164 char *secret_tmp = NULL;
2165 BIGNUM *pubkey_bn = NULL;
2166 size_t secret_len=0, secret_tmp_len=0;
2167 int result=0;
2168 tor_assert(dh);
2169 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
2170 tor_assert(pubkey_len < INT_MAX);
2172 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
2173 (int)pubkey_len, NULL)))
2174 goto error;
2175 if (tor_check_dh_key(severity, pubkey_bn)<0) {
2176 /* Check for invalid public keys. */
2177 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
2178 goto error;
2180 secret_tmp_len = crypto_dh_get_bytes(dh);
2181 secret_tmp = tor_malloc(secret_tmp_len);
2182 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
2183 if (result < 0) {
2184 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
2185 goto error;
2187 secret_len = result;
2188 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
2189 (uint8_t*)secret_out, secret_bytes_out)<0)
2190 goto error;
2191 secret_len = secret_bytes_out;
2193 goto done;
2194 error:
2195 result = -1;
2196 done:
2197 crypto_log_errors(LOG_WARN, "completing DH handshake");
2198 if (pubkey_bn)
2199 BN_free(pubkey_bn);
2200 if (secret_tmp) {
2201 memwipe(secret_tmp, 0, secret_tmp_len);
2202 tor_free(secret_tmp);
2204 if (result < 0)
2205 return result;
2206 else
2207 return secret_len;
2210 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2211 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2212 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2213 * H(K | [00]) | H(K | [01]) | ....
2215 * This is the key expansion algorithm used in the "TAP" circuit extension
2216 * mechanism; it shouldn't be used for new protocols.
2218 * Return 0 on success, -1 on failure.
2221 crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
2222 uint8_t *key_out, size_t key_out_len)
2224 int i;
2225 uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
2226 uint8_t digest[DIGEST_LEN];
2228 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2229 tor_assert(key_out_len <= DIGEST_LEN*256);
2231 memcpy(tmp, key_in, key_in_len);
2232 for (cp = key_out, i=0; cp < key_out+key_out_len;
2233 ++i, cp += DIGEST_LEN) {
2234 tmp[key_in_len] = i;
2235 if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
2236 goto err;
2237 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
2239 memwipe(tmp, 0, key_in_len+1);
2240 tor_free(tmp);
2241 memwipe(digest, 0, sizeof(digest));
2242 return 0;
2244 err:
2245 memwipe(tmp, 0, key_in_len+1);
2246 tor_free(tmp);
2247 memwipe(digest, 0, sizeof(digest));
2248 return -1;
2251 /** Expand some secret key material according to RFC5869, using SHA256 as the
2252 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2253 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2254 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2255 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2256 * bytes to <b>key_out</b> and return 0. On failure, return -1.
2259 crypto_expand_key_material_rfc5869_sha256(
2260 const uint8_t *key_in, size_t key_in_len,
2261 const uint8_t *salt_in, size_t salt_in_len,
2262 const uint8_t *info_in, size_t info_in_len,
2263 uint8_t *key_out, size_t key_out_len)
2265 uint8_t prk[DIGEST256_LEN];
2266 uint8_t tmp[DIGEST256_LEN + 128 + 1];
2267 uint8_t mac[DIGEST256_LEN];
2268 int i;
2269 uint8_t *outp;
2270 size_t tmp_len;
2272 crypto_hmac_sha256((char*)prk,
2273 (const char*)salt_in, salt_in_len,
2274 (const char*)key_in, key_in_len);
2276 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2277 tor_assert(key_out_len <= DIGEST256_LEN * 256);
2278 tor_assert(info_in_len <= 128);
2279 memset(tmp, 0, sizeof(tmp));
2280 outp = key_out;
2281 i = 1;
2283 while (key_out_len) {
2284 size_t n;
2285 if (i > 1) {
2286 memcpy(tmp, mac, DIGEST256_LEN);
2287 memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
2288 tmp[DIGEST256_LEN+info_in_len] = i;
2289 tmp_len = DIGEST256_LEN + info_in_len + 1;
2290 } else {
2291 memcpy(tmp, info_in, info_in_len);
2292 tmp[info_in_len] = i;
2293 tmp_len = info_in_len + 1;
2295 crypto_hmac_sha256((char*)mac,
2296 (const char*)prk, DIGEST256_LEN,
2297 (const char*)tmp, tmp_len);
2298 n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
2299 memcpy(outp, mac, n);
2300 key_out_len -= n;
2301 outp += n;
2302 ++i;
2305 memwipe(tmp, 0, sizeof(tmp));
2306 memwipe(mac, 0, sizeof(mac));
2307 return 0;
2310 /** Free a DH key exchange object.
2312 void
2313 crypto_dh_free(crypto_dh_t *dh)
2315 if (!dh)
2316 return;
2317 tor_assert(dh->dh);
2318 DH_free(dh->dh);
2319 tor_free(dh);
2322 /* random numbers */
2324 /** How many bytes of entropy we add at once.
2326 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2327 * work for us too. */
2328 #define ADD_ENTROPY 32
2330 /** True iff it's safe to use RAND_poll after setup.
2332 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2333 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2334 * that fd without checking whether it fit in the fd_set. Thus, if the
2335 * system has not just been started up, it is unsafe to call */
2336 #define RAND_POLL_IS_SAFE \
2337 (OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2339 /** Set the seed of the weak RNG to a random value. */
2340 void
2341 crypto_seed_weak_rng(tor_weak_rng_t *rng)
2343 unsigned seed;
2344 crypto_rand((void*)&seed, sizeof(seed));
2345 tor_init_weak_random(rng, seed);
2348 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2349 * storing it into <b>out</b>.
2352 crypto_strongest_rand(uint8_t *out, size_t out_len)
2354 #ifdef _WIN32
2355 static int provider_set = 0;
2356 static HCRYPTPROV provider;
2357 #else
2358 static const char *filenames[] = {
2359 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2361 int fd, i;
2362 size_t n;
2363 #endif
2365 #ifdef _WIN32
2366 if (!provider_set) {
2367 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2368 CRYPT_VERIFYCONTEXT)) {
2369 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
2370 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2371 return -1;
2374 provider_set = 1;
2376 if (!CryptGenRandom(provider, out_len, out)) {
2377 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2378 return -1;
2381 return 0;
2382 #else
2383 for (i = 0; filenames[i]; ++i) {
2384 fd = open(filenames[i], O_RDONLY, 0);
2385 if (fd<0) continue;
2386 log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
2387 n = read_all(fd, (char*)out, out_len, 0);
2388 close(fd);
2389 if (n != out_len) {
2390 log_warn(LD_CRYPTO,
2391 "Error reading from entropy source (read only %lu bytes).",
2392 (unsigned long)n);
2393 return -1;
2396 return 0;
2399 log_warn(LD_CRYPTO, "Cannot get strong entropy: no entropy source found.");
2400 return -1;
2401 #endif
2404 /** Seed OpenSSL's random number generator with bytes from the operating
2405 * system. <b>startup</b> should be true iff we have just started Tor and
2406 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2409 crypto_seed_rng(int startup)
2411 int rand_poll_ok = 0, load_entropy_ok = 0;
2412 uint8_t buf[ADD_ENTROPY];
2414 /* OpenSSL has a RAND_poll function that knows about more kinds of
2415 * entropy than we do. We'll try calling that, *and* calling our own entropy
2416 * functions. If one succeeds, we'll accept the RNG as seeded. */
2417 if (startup || RAND_POLL_IS_SAFE) {
2418 rand_poll_ok = RAND_poll();
2419 if (rand_poll_ok == 0)
2420 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2423 load_entropy_ok = !crypto_strongest_rand(buf, sizeof(buf));
2424 if (load_entropy_ok) {
2425 RAND_seed(buf, sizeof(buf));
2428 memwipe(buf, 0, sizeof(buf));
2430 if (rand_poll_ok || load_entropy_ok)
2431 return 0;
2432 else
2433 return -1;
2436 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2437 * success, -1 on failure.
2440 crypto_rand(char *to, size_t n)
2442 int r;
2443 tor_assert(n < INT_MAX);
2444 tor_assert(to);
2445 r = RAND_bytes((unsigned char*)to, (int)n);
2446 if (r == 0)
2447 crypto_log_errors(LOG_WARN, "generating random data");
2448 return (r == 1) ? 0 : -1;
2451 /** Return a pseudorandom integer, chosen uniformly from the values
2452 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2453 * INT_MAX+1, inclusive. */
2455 crypto_rand_int(unsigned int max)
2457 unsigned int val;
2458 unsigned int cutoff;
2459 tor_assert(max <= ((unsigned int)INT_MAX)+1);
2460 tor_assert(max > 0); /* don't div by 0 */
2462 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2463 * distribution with clipping at the upper end of unsigned int's
2464 * range.
2466 cutoff = UINT_MAX - (UINT_MAX%max);
2467 while (1) {
2468 crypto_rand((char*)&val, sizeof(val));
2469 if (val < cutoff)
2470 return val % max;
2474 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2475 * between 0 and <b>max</b>-1. */
2476 uint64_t
2477 crypto_rand_uint64(uint64_t max)
2479 uint64_t val;
2480 uint64_t cutoff;
2481 tor_assert(max < UINT64_MAX);
2482 tor_assert(max > 0); /* don't div by 0 */
2484 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2485 * distribution with clipping at the upper end of unsigned int's
2486 * range.
2488 cutoff = UINT64_MAX - (UINT64_MAX%max);
2489 while (1) {
2490 crypto_rand((char*)&val, sizeof(val));
2491 if (val < cutoff)
2492 return val % max;
2496 /** Return a pseudorandom double d, chosen uniformly from the range
2497 * 0.0 <= d < 1.0.
2499 double
2500 crypto_rand_double(void)
2502 /* We just use an unsigned int here; we don't really care about getting
2503 * more than 32 bits of resolution */
2504 unsigned int uint;
2505 crypto_rand((char*)&uint, sizeof(uint));
2506 #if SIZEOF_INT == 4
2507 #define UINT_MAX_AS_DOUBLE 4294967296.0
2508 #elif SIZEOF_INT == 8
2509 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2510 #else
2511 #error SIZEOF_INT is neither 4 nor 8
2512 #endif
2513 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2516 /** Generate and return a new random hostname starting with <b>prefix</b>,
2517 * ending with <b>suffix</b>, and containing no fewer than
2518 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2519 * characters between.
2521 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2523 char *
2524 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2525 const char *suffix)
2527 char *result, *rand_bytes;
2528 int randlen, rand_bytes_len;
2529 size_t resultlen, prefixlen;
2531 if (max_rand_len > MAX_DNS_LABEL_SIZE)
2532 max_rand_len = MAX_DNS_LABEL_SIZE;
2533 if (min_rand_len > max_rand_len)
2534 min_rand_len = max_rand_len;
2536 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2538 prefixlen = strlen(prefix);
2539 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2541 rand_bytes_len = ((randlen*5)+7)/8;
2542 if (rand_bytes_len % 5)
2543 rand_bytes_len += 5 - (rand_bytes_len%5);
2544 rand_bytes = tor_malloc(rand_bytes_len);
2545 crypto_rand(rand_bytes, rand_bytes_len);
2547 result = tor_malloc(resultlen);
2548 memcpy(result, prefix, prefixlen);
2549 base32_encode(result+prefixlen, resultlen-prefixlen,
2550 rand_bytes, rand_bytes_len);
2551 tor_free(rand_bytes);
2552 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2554 return result;
2557 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2558 * is empty. */
2559 void *
2560 smartlist_choose(const smartlist_t *sl)
2562 int len = smartlist_len(sl);
2563 if (len)
2564 return smartlist_get(sl,crypto_rand_int(len));
2565 return NULL; /* no elements to choose from */
2568 /** Scramble the elements of <b>sl</b> into a random order. */
2569 void
2570 smartlist_shuffle(smartlist_t *sl)
2572 int i;
2573 /* From the end of the list to the front, choose at random from the
2574 positions we haven't looked at yet, and swap that position into the
2575 current position. Remember to give "no swap" the same probability as
2576 any other swap. */
2577 for (i = smartlist_len(sl)-1; i > 0; --i) {
2578 int j = crypto_rand_int(i+1);
2579 smartlist_swap(sl, i, j);
2583 /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2584 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2585 * bytes. Return the number of bytes written on success; -1 if
2586 * destlen is too short, or other failure.
2589 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2591 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2592 * it ever shows up in the profile. */
2593 EVP_ENCODE_CTX ctx;
2594 int len, ret;
2595 tor_assert(srclen < INT_MAX);
2597 /* 48 bytes of input -> 64 bytes of output plus newline.
2598 Plus one more byte, in case I'm wrong.
2600 if (destlen < ((srclen/48)+1)*66)
2601 return -1;
2602 if (destlen > SIZE_T_CEILING)
2603 return -1;
2605 EVP_EncodeInit(&ctx);
2606 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2607 (unsigned char*)src, (int)srclen);
2608 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2609 ret += len;
2610 return ret;
2613 /** @{ */
2614 /** Special values used for the base64_decode_table */
2615 #define X 255
2616 #define SP 64
2617 #define PAD 65
2618 /** @} */
2619 /** Internal table mapping byte values to what they represent in base64.
2620 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2621 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2622 * end-of-string. */
2623 static const uint8_t base64_decode_table[256] = {
2624 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2625 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2626 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2627 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2628 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2629 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2630 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2631 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2632 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2633 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2634 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2635 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2636 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2637 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2638 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2639 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2642 /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2643 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2644 * bytes. Return the number of bytes written on success; -1 if
2645 * destlen is too short, or other failure.
2647 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2648 * spaces or padding.
2650 * NOTE 2: This implementation does not check for the correct number of
2651 * padding "=" characters at the end of the string, and does not check
2652 * for internal padding characters.
2655 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2657 #ifdef USE_OPENSSL_BASE64
2658 EVP_ENCODE_CTX ctx;
2659 int len, ret;
2660 /* 64 bytes of input -> *up to* 48 bytes of output.
2661 Plus one more byte, in case I'm wrong.
2663 if (destlen < ((srclen/64)+1)*49)
2664 return -1;
2665 if (destlen > SIZE_T_CEILING)
2666 return -1;
2668 EVP_DecodeInit(&ctx);
2669 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2670 (unsigned char*)src, srclen);
2671 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2672 ret += len;
2673 return ret;
2674 #else
2675 const char *eos = src+srclen;
2676 uint32_t n=0;
2677 int n_idx=0;
2678 char *dest_orig = dest;
2680 /* Max number of bits == srclen*6.
2681 * Number of bytes required to hold all bits == (srclen*6)/8.
2682 * Yes, we want to round down: anything that hangs over the end of a
2683 * byte is padding. */
2684 if (destlen < (srclen*3)/4)
2685 return -1;
2686 if (destlen > SIZE_T_CEILING)
2687 return -1;
2689 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2690 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2691 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2693 for ( ; src < eos; ++src) {
2694 unsigned char c = (unsigned char) *src;
2695 uint8_t v = base64_decode_table[c];
2696 switch (v) {
2697 case X:
2698 /* This character isn't allowed in base64. */
2699 return -1;
2700 case SP:
2701 /* This character is whitespace, and has no effect. */
2702 continue;
2703 case PAD:
2704 /* We've hit an = character: the data is over. */
2705 goto end_of_loop;
2706 default:
2707 /* We have an actual 6-bit value. Append it to the bits in n. */
2708 n = (n<<6) | v;
2709 if ((++n_idx) == 4) {
2710 /* We've accumulated 24 bits in n. Flush them. */
2711 *dest++ = (n>>16);
2712 *dest++ = (n>>8) & 0xff;
2713 *dest++ = (n) & 0xff;
2714 n_idx = 0;
2715 n = 0;
2719 end_of_loop:
2720 /* If we have leftover bits, we need to cope. */
2721 switch (n_idx) {
2722 case 0:
2723 default:
2724 /* No leftover bits. We win. */
2725 break;
2726 case 1:
2727 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2728 return -1;
2729 case 2:
2730 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2731 *dest++ = n >> 4;
2732 break;
2733 case 3:
2734 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2735 *dest++ = n >> 10;
2736 *dest++ = n >> 2;
2739 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2740 tor_assert((dest-dest_orig) <= INT_MAX);
2742 return (int)(dest-dest_orig);
2743 #endif
2745 #undef X
2746 #undef SP
2747 #undef PAD
2749 /** Base64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2750 * and newline characters, and store the nul-terminated result in the first
2751 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2753 digest_to_base64(char *d64, const char *digest)
2755 char buf[256];
2756 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2757 buf[BASE64_DIGEST_LEN] = '\0';
2758 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2759 return 0;
2762 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2763 * trailing newline or = characters), decode it and store the result in the
2764 * first DIGEST_LEN bytes at <b>digest</b>. */
2766 digest_from_base64(char *digest, const char *d64)
2768 #ifdef USE_OPENSSL_BASE64
2769 char buf_in[BASE64_DIGEST_LEN+3];
2770 char buf[256];
2771 if (strlen(d64) != BASE64_DIGEST_LEN)
2772 return -1;
2773 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2774 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2775 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2776 return -1;
2777 memcpy(digest, buf, DIGEST_LEN);
2778 return 0;
2779 #else
2780 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2781 return 0;
2782 else
2783 return -1;
2784 #endif
2787 /** Base64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2788 * trailing = and newline characters, and store the nul-terminated result in
2789 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2791 digest256_to_base64(char *d64, const char *digest)
2793 char buf[256];
2794 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2795 buf[BASE64_DIGEST256_LEN] = '\0';
2796 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2797 return 0;
2800 /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
2801 * trailing newline or = characters), decode it and store the result in the
2802 * first DIGEST256_LEN bytes at <b>digest</b>. */
2804 digest256_from_base64(char *digest, const char *d64)
2806 #ifdef USE_OPENSSL_BASE64
2807 char buf_in[BASE64_DIGEST256_LEN+3];
2808 char buf[256];
2809 if (strlen(d64) != BASE64_DIGEST256_LEN)
2810 return -1;
2811 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2812 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2813 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2814 return -1;
2815 memcpy(digest, buf, DIGEST256_LEN);
2816 return 0;
2817 #else
2818 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2819 return 0;
2820 else
2821 return -1;
2822 #endif
2825 /** Implements base32 encoding as in RFC 4648. Limitation: Requires
2826 * that srclen*8 is a multiple of 5.
2828 void
2829 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2831 unsigned int i, v, u;
2832 size_t nbits = srclen * 8, bit;
2834 tor_assert(srclen < SIZE_T_CEILING/8);
2835 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2836 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2837 tor_assert(destlen < SIZE_T_CEILING);
2839 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2840 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2841 v = ((uint8_t)src[bit/8]) << 8;
2842 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2843 /* set u to the 5-bit value at the bit'th bit of src. */
2844 u = (v >> (11-(bit%8))) & 0x1F;
2845 dest[i] = BASE32_CHARS[u];
2847 dest[i] = '\0';
2850 /** Implements base32 decoding as in RFC 4648. Limitation: Requires
2851 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2854 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2856 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2857 * it ever shows up in the profile. */
2858 unsigned int i;
2859 size_t nbits, j, bit;
2860 char *tmp;
2861 nbits = srclen * 5;
2863 tor_assert(srclen < SIZE_T_CEILING / 5);
2864 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2865 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2866 tor_assert(destlen < SIZE_T_CEILING);
2868 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2869 tmp = tor_malloc_zero(srclen);
2870 for (j = 0; j < srclen; ++j) {
2871 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2872 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2873 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2874 else {
2875 log_warn(LD_BUG, "illegal character in base32 encoded string");
2876 tor_free(tmp);
2877 return -1;
2881 /* Assemble result byte-wise by applying five possible cases. */
2882 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2883 switch (bit % 40) {
2884 case 0:
2885 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2886 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2887 break;
2888 case 8:
2889 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2890 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2891 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2892 break;
2893 case 16:
2894 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2895 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2896 break;
2897 case 24:
2898 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2899 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2900 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2901 break;
2902 case 32:
2903 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2904 ((uint8_t)tmp[(bit/5)+1]);
2905 break;
2909 memwipe(tmp, 0, srclen);
2910 tor_free(tmp);
2911 tmp = NULL;
2912 return 0;
2915 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2916 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2917 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2918 * are a salt; the 9th byte describes how much iteration to do.
2919 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2921 void
2922 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2923 size_t secret_len, const char *s2k_specifier)
2925 crypto_digest_t *d;
2926 uint8_t c;
2927 size_t count, tmplen;
2928 char *tmp;
2929 tor_assert(key_out_len < SIZE_T_CEILING);
2931 #define EXPBIAS 6
2932 c = s2k_specifier[8];
2933 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2934 #undef EXPBIAS
2936 tor_assert(key_out_len <= DIGEST_LEN);
2938 d = crypto_digest_new();
2939 tmplen = 8+secret_len;
2940 tmp = tor_malloc(tmplen);
2941 memcpy(tmp,s2k_specifier,8);
2942 memcpy(tmp+8,secret,secret_len);
2943 secret_len += 8;
2944 while (count) {
2945 if (count >= secret_len) {
2946 crypto_digest_add_bytes(d, tmp, secret_len);
2947 count -= secret_len;
2948 } else {
2949 crypto_digest_add_bytes(d, tmp, count);
2950 count = 0;
2953 crypto_digest_get_digest(d, key_out, key_out_len);
2954 memwipe(tmp, 0, tmplen);
2955 tor_free(tmp);
2956 crypto_digest_free(d);
2960 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
2961 * the value <b>byte</b>.
2963 * This function is preferable to memset, since many compilers will happily
2964 * optimize out memset() when they can convince themselves that the data being
2965 * cleared will never be read.
2967 * Right now, our convention is to use this function when we are wiping data
2968 * that's about to become inaccessible, such as stack buffers that are about
2969 * to go out of scope or structures that are about to get freed. (In
2970 * practice, it appears that the compilers we're currently using will optimize
2971 * out the memset()s for stack-allocated buffers, but not those for
2972 * about-to-be-freed structures. That could change, though, so we're being
2973 * wary.) If there are live reads for the data, then you can just use
2974 * memset().
2976 void
2977 memwipe(void *mem, uint8_t byte, size_t sz)
2979 /* Because whole-program-optimization exists, we may not be able to just
2980 * have this function call "memset". A smart compiler could inline it, then
2981 * eliminate dead memsets, and declare itself to be clever. */
2983 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
2984 * based on the pointer value, then uses that junk to update a global
2985 * variable. It's an elaborate ruse to trick the compiler into not
2986 * optimizing out the "wipe this memory" code. Read it if you like zany
2987 * programming tricks! In later versions of Tor, we should look for better
2988 * not-optimized-out memory wiping stuff. */
2989 OPENSSL_cleanse(mem, sz);
2990 /* Just in case some caller of memwipe() is relying on getting a buffer
2991 * filled with a particular value, fill the buffer.
2993 * If this function gets inlined, this memset might get eliminated, but
2994 * that's okay: We only care about this particular memset in the case where
2995 * the caller should have been using memset(), and the memset() wouldn't get
2996 * eliminated. In other words, this is here so that we won't break anything
2997 * if somebody accidentally calls memwipe() instead of memset().
2999 memset(mem, byte, sz);
3002 #ifdef TOR_IS_MULTITHREADED
3004 #ifndef OPENSSL_THREADS
3005 #error OpenSSL has been built without thread support. Tor requires an \
3006 OpenSSL library with thread support enabled.
3007 #endif
3009 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3010 static void
3011 openssl_locking_cb_(int mode, int n, const char *file, int line)
3013 (void)file;
3014 (void)line;
3015 if (!openssl_mutexes_)
3016 /* This is not a really good fix for the
3017 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3018 * it can't hurt. */
3019 return;
3020 if (mode & CRYPTO_LOCK)
3021 tor_mutex_acquire(openssl_mutexes_[n]);
3022 else
3023 tor_mutex_release(openssl_mutexes_[n]);
3026 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3027 * as a lock. */
3028 struct CRYPTO_dynlock_value {
3029 tor_mutex_t *lock;
3032 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3033 * documentation in OpenSSL's docs for more info. */
3034 static struct CRYPTO_dynlock_value *
3035 openssl_dynlock_create_cb_(const char *file, int line)
3037 struct CRYPTO_dynlock_value *v;
3038 (void)file;
3039 (void)line;
3040 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
3041 v->lock = tor_mutex_new();
3042 return v;
3045 /** OpenSSL callback function to acquire or release a lock: see
3046 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3047 static void
3048 openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
3049 const char *file, int line)
3051 (void)file;
3052 (void)line;
3053 if (mode & CRYPTO_LOCK)
3054 tor_mutex_acquire(v->lock);
3055 else
3056 tor_mutex_release(v->lock);
3059 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3060 * documentation in OpenSSL's docs for more info. */
3061 static void
3062 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
3063 const char *file, int line)
3065 (void)file;
3066 (void)line;
3067 tor_mutex_free(v->lock);
3068 tor_free(v);
3071 /** @{ */
3072 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3073 * multithreaded. */
3074 static int
3075 setup_openssl_threading(void)
3077 int i;
3078 int n = CRYPTO_num_locks();
3079 n_openssl_mutexes_ = n;
3080 openssl_mutexes_ = tor_malloc(n*sizeof(tor_mutex_t *));
3081 for (i=0; i < n; ++i)
3082 openssl_mutexes_[i] = tor_mutex_new();
3083 CRYPTO_set_locking_callback(openssl_locking_cb_);
3084 CRYPTO_set_id_callback(tor_get_thread_id);
3085 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
3086 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
3087 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
3088 return 0;
3090 #else
3091 static int
3092 setup_openssl_threading(void)
3094 return 0;
3096 #endif
3098 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3101 crypto_global_cleanup(void)
3103 EVP_cleanup();
3104 ERR_remove_state(0);
3105 ERR_free_strings();
3107 if (dh_param_p)
3108 BN_free(dh_param_p);
3109 if (dh_param_p_tls)
3110 BN_free(dh_param_p_tls);
3111 if (dh_param_g)
3112 BN_free(dh_param_g);
3114 #ifndef DISABLE_ENGINES
3115 ENGINE_cleanup();
3116 #endif
3118 CONF_modules_unload(1);
3119 CRYPTO_cleanup_all_ex_data();
3120 #ifdef TOR_IS_MULTITHREADED
3121 if (n_openssl_mutexes_) {
3122 int n = n_openssl_mutexes_;
3123 tor_mutex_t **ms = openssl_mutexes_;
3124 int i;
3125 openssl_mutexes_ = NULL;
3126 n_openssl_mutexes_ = 0;
3127 for (i=0;i<n;++i) {
3128 tor_mutex_free(ms[i]);
3130 tor_free(ms);
3132 #endif
3133 tor_free(crypto_openssl_version_str);
3134 return 0;
3137 /** @} */