whitespace and warning fixes for bug4746
[tor.git] / src / common / crypto.c
blobe377b01d413149a33ad89ce67ecfb084f6e88f1f
1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file crypto.c
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
11 **/
13 #include "orconfig.h"
15 #ifdef MS_WINDOWS
16 #ifndef WIN32_WINNT
17 #define WIN32_WINNT 0x400
18 #endif
19 #ifndef _WIN32_WINNT
20 #define _WIN32_WINNT 0x400
21 #endif
22 #define WIN32_LEAN_AND_MEAN
23 #include <windows.h>
24 #include <wincrypt.h>
25 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
26 * use either definition. */
27 #undef OCSP_RESPONSE
28 #endif
30 #include <openssl/err.h>
31 #include <openssl/rsa.h>
32 #include <openssl/pem.h>
33 #include <openssl/evp.h>
34 #include <openssl/engine.h>
35 #include <openssl/rand.h>
36 #include <openssl/opensslv.h>
37 #include <openssl/bn.h>
38 #include <openssl/dh.h>
39 #include <openssl/conf.h>
40 #include <openssl/hmac.h>
42 #ifdef HAVE_CTYPE_H
43 #include <ctype.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef HAVE_SYS_FCNTL_H
52 #include <sys/fcntl.h>
53 #endif
55 #define CRYPTO_PRIVATE
56 #include "crypto.h"
57 #include "../common/torlog.h"
58 #include "aes.h"
59 #include "../common/util.h"
60 #include "container.h"
61 #include "compat.h"
63 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,7)
64 #error "We require OpenSSL >= 0.9.7"
65 #endif
67 #ifdef ANDROID
68 /* Android's OpenSSL seems to have removed all of its Engine support. */
69 #define DISABLE_ENGINES
70 #endif
72 /** Longest recognized */
73 #define MAX_DNS_LABEL_SIZE 63
75 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
76 /** @{ */
77 /** On OpenSSL versions before 0.9.8, there is no working SHA256
78 * implementation, so we use Tom St Denis's nice speedy one, slightly adapted
79 * to our needs. These macros make it usable by us. */
80 #define SHA256_CTX sha256_state
81 #define SHA256_Init sha256_init
82 #define SHA256_Update sha256_process
83 #define LTC_ARGCHK(x) tor_assert(x)
84 /** @} */
85 #include "sha256.c"
86 #define SHA256_Final(a,b) sha256_done(b,a)
88 static unsigned char *
89 SHA256(const unsigned char *m, size_t len, unsigned char *d)
91 SHA256_CTX ctx;
92 SHA256_Init(&ctx);
93 SHA256_Update(&ctx, m, len);
94 SHA256_Final(d, &ctx);
95 return d;
97 #endif
99 /** Macro: is k a valid RSA public or private key? */
100 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
101 /** Macro: is k a valid RSA private key? */
102 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
104 #ifdef TOR_IS_MULTITHREADED
105 /** A number of preallocated mutexes for use by OpenSSL. */
106 static tor_mutex_t **_openssl_mutexes = NULL;
107 /** How many mutexes have we allocated for use by OpenSSL? */
108 static int _n_openssl_mutexes = 0;
109 #endif
111 /** A public key, or a public/private key-pair. */
112 struct crypto_pk_env_t
114 int refs; /**< reference count, so we don't have to copy keys */
115 RSA *key; /**< The key itself */
118 /** Key and stream information for a stream cipher. */
119 struct crypto_cipher_env_t
121 char key[CIPHER_KEY_LEN]; /**< The raw key. */
122 aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
123 * encryption */
126 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
127 * while we're waiting for the second.*/
128 struct crypto_dh_env_t {
129 DH *dh; /**< The openssl DH object */
132 static int setup_openssl_threading(void);
133 static int tor_check_dh_key(int severity, BIGNUM *bn);
135 /** Return the number of bytes added by padding method <b>padding</b>.
137 static INLINE int
138 crypto_get_rsa_padding_overhead(int padding)
140 switch (padding)
142 case RSA_NO_PADDING: return 0;
143 case RSA_PKCS1_OAEP_PADDING: return 42;
144 case RSA_PKCS1_PADDING: return 11;
145 default: tor_assert(0); return -1;
149 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
151 static INLINE int
152 crypto_get_rsa_padding(int padding)
154 switch (padding)
156 case PK_NO_PADDING: return RSA_NO_PADDING;
157 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
158 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
159 default: tor_assert(0); return -1;
163 /** Boolean: has OpenSSL's crypto been initialized? */
164 static int _crypto_global_initialized = 0;
166 /** Log all pending crypto errors at level <b>severity</b>. Use
167 * <b>doing</b> to describe our current activities.
169 static void
170 crypto_log_errors(int severity, const char *doing)
172 unsigned long err;
173 const char *msg, *lib, *func;
174 while ((err = ERR_get_error()) != 0) {
175 msg = (const char*)ERR_reason_error_string(err);
176 lib = (const char*)ERR_lib_error_string(err);
177 func = (const char*)ERR_func_error_string(err);
178 if (!msg) msg = "(null)";
179 if (!lib) lib = "(null)";
180 if (!func) func = "(null)";
181 if (doing) {
182 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
183 doing, msg, lib, func);
184 } else {
185 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
190 #ifndef DISABLE_ENGINES
191 /** Log any OpenSSL engines we're using at NOTICE. */
192 static void
193 log_engine(const char *fn, ENGINE *e)
195 if (e) {
196 const char *name, *id;
197 name = ENGINE_get_name(e);
198 id = ENGINE_get_id(e);
199 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
200 name?name:"?", id?id:"?", fn);
201 } else {
202 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
205 #endif
207 #ifndef DISABLE_ENGINES
208 /** Try to load an engine in a shared library via fully qualified path.
210 static ENGINE *
211 try_load_engine(const char *path, const char *engine)
213 ENGINE *e = ENGINE_by_id("dynamic");
214 if (e) {
215 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
216 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
217 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
218 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
219 ENGINE_free(e);
220 e = NULL;
223 return e;
225 #endif
227 /** Initialize the crypto library. Return 0 on success, -1 on failure.
230 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
232 if (!_crypto_global_initialized) {
233 ERR_load_crypto_strings();
234 OpenSSL_add_all_algorithms();
235 _crypto_global_initialized = 1;
236 setup_openssl_threading();
237 if (useAccel > 0) {
238 #ifdef DISABLE_ENGINES
239 (void)accelName;
240 (void)accelDir;
241 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
242 #else
243 ENGINE *e = NULL;
245 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
246 ENGINE_load_builtin_engines();
247 ENGINE_register_all_complete();
249 if (accelName) {
250 if (accelDir) {
251 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
252 " via path \"%s\".", accelName, accelDir);
253 e = try_load_engine(accelName, accelDir);
254 } else {
255 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
256 " acceleration support.", accelName);
257 e = ENGINE_by_id(accelName);
259 if (!e) {
260 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
261 accelName);
262 } else {
263 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
264 accelName);
267 if (e) {
268 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
269 " setting default ciphers.");
270 ENGINE_set_default(e, ENGINE_METHOD_ALL);
272 log_engine("RSA", ENGINE_get_default_RSA());
273 log_engine("DH", ENGINE_get_default_DH());
274 log_engine("RAND", ENGINE_get_default_RAND());
275 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
276 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
277 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
278 #endif
279 } else {
280 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
283 evaluate_evp_for_aes(-1);
284 evaluate_ctr_for_aes();
286 return crypto_seed_rng(1);
288 return 0;
291 /** Free crypto resources held by this thread. */
292 void
293 crypto_thread_cleanup(void)
295 ERR_remove_state(0);
298 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
299 crypto_pk_env_t *
300 _crypto_new_pk_env_rsa(RSA *rsa)
302 crypto_pk_env_t *env;
303 tor_assert(rsa);
304 env = tor_malloc(sizeof(crypto_pk_env_t));
305 env->refs = 1;
306 env->key = rsa;
307 return env;
310 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
311 * crypto_pk_env_t. */
312 RSA *
313 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
315 return env->key;
318 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
319 * private is set, include the private-key portion of the key. */
320 EVP_PKEY *
321 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
323 RSA *key = NULL;
324 EVP_PKEY *pkey = NULL;
325 tor_assert(env->key);
326 if (private) {
327 if (!(key = RSAPrivateKey_dup(env->key)))
328 goto error;
329 } else {
330 if (!(key = RSAPublicKey_dup(env->key)))
331 goto error;
333 if (!(pkey = EVP_PKEY_new()))
334 goto error;
335 if (!(EVP_PKEY_assign_RSA(pkey, key)))
336 goto error;
337 return pkey;
338 error:
339 if (pkey)
340 EVP_PKEY_free(pkey);
341 if (key)
342 RSA_free(key);
343 return NULL;
346 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
348 DH *
349 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
351 return dh->dh;
354 /** Allocate and return storage for a public key. The key itself will not yet
355 * be set.
357 crypto_pk_env_t *
358 crypto_new_pk_env(void)
360 RSA *rsa;
362 rsa = RSA_new();
363 tor_assert(rsa);
364 return _crypto_new_pk_env_rsa(rsa);
367 /** Release a reference to an asymmetric key; when all the references
368 * are released, free the key.
370 void
371 crypto_free_pk_env(crypto_pk_env_t *env)
373 if (!env)
374 return;
376 if (--env->refs > 0)
377 return;
378 tor_assert(env->refs == 0);
380 if (env->key)
381 RSA_free(env->key);
383 tor_free(env);
386 /** Create a new symmetric cipher for a given key and encryption flag
387 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
388 * on failure.
390 crypto_cipher_env_t *
391 crypto_create_init_cipher(const char *key, int encrypt_mode)
393 int r;
394 crypto_cipher_env_t *crypto = NULL;
396 if (! (crypto = crypto_new_cipher_env())) {
397 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
398 return NULL;
401 crypto_cipher_set_key(crypto, key);
403 if (encrypt_mode)
404 r = crypto_cipher_encrypt_init_cipher(crypto);
405 else
406 r = crypto_cipher_decrypt_init_cipher(crypto);
408 if (r)
409 goto error;
410 return crypto;
412 error:
413 if (crypto)
414 crypto_free_cipher_env(crypto);
415 return NULL;
418 /** Allocate and return a new symmetric cipher.
420 crypto_cipher_env_t *
421 crypto_new_cipher_env(void)
423 crypto_cipher_env_t *env;
425 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
426 env->cipher = aes_new_cipher();
427 return env;
430 /** Free a symmetric cipher.
432 void
433 crypto_free_cipher_env(crypto_cipher_env_t *env)
435 if (!env)
436 return;
438 tor_assert(env->cipher);
439 aes_free_cipher(env->cipher);
440 memset(env, 0, sizeof(crypto_cipher_env_t));
441 tor_free(env);
444 /* public key crypto */
446 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
447 * Return 0 on success, -1 on failure.
450 crypto_pk_generate_key_with_bits(crypto_pk_env_t *env, int bits)
452 tor_assert(env);
454 if (env->key)
455 RSA_free(env->key);
456 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
457 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
458 env->key = RSA_generate_key(bits, 65537, NULL, NULL);
459 #else
460 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
462 BIGNUM *e = BN_new();
463 RSA *r = NULL;
464 if (!e)
465 goto done;
466 if (! BN_set_word(e, 65537))
467 goto done;
468 r = RSA_new();
469 if (!r)
470 goto done;
471 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
472 goto done;
474 env->key = r;
475 r = NULL;
476 done:
477 if (e)
478 BN_free(e);
479 if (r)
480 RSA_free(r);
482 #endif
483 if (!env->key) {
484 crypto_log_errors(LOG_WARN, "generating RSA key");
485 return -1;
488 return 0;
491 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
492 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
493 * the string is nul-terminated.
495 /* Used here, and used for testing. */
497 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
498 const char *s, ssize_t len)
500 BIO *b;
502 tor_assert(env);
503 tor_assert(s);
504 tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
506 /* Create a read-only memory BIO, backed by the string 's' */
507 b = BIO_new_mem_buf((char*)s, (int)len);
508 if (!b)
509 return -1;
511 if (env->key)
512 RSA_free(env->key);
514 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
516 BIO_free(b);
518 if (!env->key) {
519 crypto_log_errors(LOG_WARN, "Error parsing private key");
520 return -1;
522 return 0;
525 /** Read a PEM-encoded private key from the file named by
526 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
529 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
530 const char *keyfile)
532 char *contents;
533 int r;
535 /* Read the file into a string. */
536 contents = read_file_to_str(keyfile, 0, NULL);
537 if (!contents) {
538 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
539 return -1;
542 /* Try to parse it. */
543 r = crypto_pk_read_private_key_from_string(env, contents, -1);
544 memset(contents, 0, strlen(contents));
545 tor_free(contents);
546 if (r)
547 return -1; /* read_private_key_from_string already warned, so we don't.*/
549 /* Make sure it's valid. */
550 if (crypto_pk_check_key(env) <= 0)
551 return -1;
553 return 0;
556 /** Helper function to implement crypto_pk_write_*_key_to_string. */
557 static int
558 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
559 size_t *len, int is_public)
561 BUF_MEM *buf;
562 BIO *b;
563 int r;
565 tor_assert(env);
566 tor_assert(env->key);
567 tor_assert(dest);
569 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
570 if (!b)
571 return -1;
573 /* Now you can treat b as if it were a file. Just use the
574 * PEM_*_bio_* functions instead of the non-bio variants.
576 if (is_public)
577 r = PEM_write_bio_RSAPublicKey(b, env->key);
578 else
579 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
581 if (!r) {
582 crypto_log_errors(LOG_WARN, "writing RSA key to string");
583 BIO_free(b);
584 return -1;
587 BIO_get_mem_ptr(b, &buf);
588 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
589 BIO_free(b);
591 *dest = tor_malloc(buf->length+1);
592 memcpy(*dest, buf->data, buf->length);
593 (*dest)[buf->length] = 0; /* nul terminate it */
594 *len = buf->length;
595 BUF_MEM_free(buf);
597 return 0;
600 /** PEM-encode the public key portion of <b>env</b> and write it to a
601 * newly allocated string. On success, set *<b>dest</b> to the new
602 * string, *<b>len</b> to the string's length, and return 0. On
603 * failure, return -1.
606 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
607 size_t *len)
609 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
612 /** PEM-encode the private key portion of <b>env</b> and write it to a
613 * newly allocated string. On success, set *<b>dest</b> to the new
614 * string, *<b>len</b> to the string's length, and return 0. On
615 * failure, return -1.
618 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
619 size_t *len)
621 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
624 /** Read a PEM-encoded public key from the first <b>len</b> characters of
625 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
626 * failure.
629 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
630 size_t len)
632 BIO *b;
634 tor_assert(env);
635 tor_assert(src);
636 tor_assert(len<INT_MAX);
638 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
639 if (!b)
640 return -1;
642 BIO_write(b, src, (int)len);
644 if (env->key)
645 RSA_free(env->key);
646 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
647 BIO_free(b);
648 if (!env->key) {
649 crypto_log_errors(LOG_WARN, "reading public key from string");
650 return -1;
653 return 0;
656 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
657 * PEM-encoded. Return 0 on success, -1 on failure.
660 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
661 const char *fname)
663 BIO *bio;
664 char *cp;
665 long len;
666 char *s;
667 int r;
669 tor_assert(PRIVATE_KEY_OK(env));
671 if (!(bio = BIO_new(BIO_s_mem())))
672 return -1;
673 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
674 == 0) {
675 crypto_log_errors(LOG_WARN, "writing private key");
676 BIO_free(bio);
677 return -1;
679 len = BIO_get_mem_data(bio, &cp);
680 tor_assert(len >= 0);
681 s = tor_malloc(len+1);
682 memcpy(s, cp, len);
683 s[len]='\0';
684 r = write_str_to_file(fname, s, 0);
685 BIO_free(bio);
686 memset(s, 0, strlen(s));
687 tor_free(s);
688 return r;
691 /** Return true iff <b>env</b> has a valid key.
694 crypto_pk_check_key(crypto_pk_env_t *env)
696 int r;
697 tor_assert(env);
699 r = RSA_check_key(env->key);
700 if (r <= 0)
701 crypto_log_errors(LOG_WARN,"checking RSA key");
702 return r;
705 /** Return true iff <b>key</b> contains the private-key portion of the RSA
706 * key. */
708 crypto_pk_key_is_private(const crypto_pk_env_t *key)
710 tor_assert(key);
711 return PRIVATE_KEY_OK(key);
714 /** Return true iff <b>env</b> contains a public key whose public exponent
715 * equals 65537.
718 crypto_pk_public_exponent_ok(crypto_pk_env_t *env)
720 tor_assert(env);
721 tor_assert(env->key);
723 return BN_is_word(env->key->e, 65537);
726 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
727 * if a==b, and 1 if a\>b.
730 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
732 int result;
734 if (!a || !b)
735 return -1;
737 if (!a->key || !b->key)
738 return -1;
740 tor_assert(PUBLIC_KEY_OK(a));
741 tor_assert(PUBLIC_KEY_OK(b));
742 result = BN_cmp((a->key)->n, (b->key)->n);
743 if (result)
744 return result;
745 return BN_cmp((a->key)->e, (b->key)->e);
748 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
749 size_t
750 crypto_pk_keysize(crypto_pk_env_t *env)
752 tor_assert(env);
753 tor_assert(env->key);
755 return (size_t) RSA_size(env->key);
758 /** Return the size of the public key modulus of <b>env</b>, in bits. */
760 crypto_pk_num_bits(crypto_pk_env_t *env)
762 tor_assert(env);
763 tor_assert(env->key);
764 tor_assert(env->key->n);
766 return BN_num_bits(env->key->n);
769 /** Increase the reference count of <b>env</b>, and return it.
771 crypto_pk_env_t *
772 crypto_pk_dup_key(crypto_pk_env_t *env)
774 tor_assert(env);
775 tor_assert(env->key);
777 env->refs++;
778 return env;
781 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
782 crypto_pk_env_t *
783 crypto_pk_copy_full(crypto_pk_env_t *env)
785 RSA *new_key;
786 int privatekey = 0;
787 tor_assert(env);
788 tor_assert(env->key);
790 if (PRIVATE_KEY_OK(env)) {
791 new_key = RSAPrivateKey_dup(env->key);
792 privatekey = 1;
793 } else {
794 new_key = RSAPublicKey_dup(env->key);
796 if (!new_key) {
797 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
798 privatekey?"private":"public");
799 crypto_log_errors(LOG_ERR,
800 privatekey ? "Duplicating a private key" :
801 "Duplicating a public key");
802 tor_fragile_assert();
803 return NULL;
806 return _crypto_new_pk_env_rsa(new_key);
809 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
810 * in <b>env</b>, using the padding method <b>padding</b>. On success,
811 * write the result to <b>to</b>, and return the number of bytes
812 * written. On failure, return -1.
814 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
815 * at least the length of the modulus of <b>env</b>.
818 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to, size_t tolen,
819 const char *from, size_t fromlen, int padding)
821 int r;
822 tor_assert(env);
823 tor_assert(from);
824 tor_assert(to);
825 tor_assert(fromlen<INT_MAX);
826 tor_assert(tolen >= crypto_pk_keysize(env));
828 r = RSA_public_encrypt((int)fromlen,
829 (unsigned char*)from, (unsigned char*)to,
830 env->key, crypto_get_rsa_padding(padding));
831 if (r<0) {
832 crypto_log_errors(LOG_WARN, "performing RSA encryption");
833 return -1;
835 return r;
838 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
839 * in <b>env</b>, using the padding method <b>padding</b>. On success,
840 * write the result to <b>to</b>, and return the number of bytes
841 * written. On failure, return -1.
843 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
844 * at least the length of the modulus of <b>env</b>.
847 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
848 size_t tolen,
849 const char *from, size_t fromlen,
850 int padding, int warnOnFailure)
852 int r;
853 tor_assert(env);
854 tor_assert(from);
855 tor_assert(to);
856 tor_assert(env->key);
857 tor_assert(fromlen<INT_MAX);
858 tor_assert(tolen >= crypto_pk_keysize(env));
859 if (!env->key->p)
860 /* Not a private key */
861 return -1;
863 r = RSA_private_decrypt((int)fromlen,
864 (unsigned char*)from, (unsigned char*)to,
865 env->key, crypto_get_rsa_padding(padding));
867 if (r<0) {
868 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
869 "performing RSA decryption");
870 return -1;
872 return r;
875 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
876 * public key in <b>env</b>, using PKCS1 padding. On success, write the
877 * signed data to <b>to</b>, and return the number of bytes written.
878 * On failure, return -1.
880 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
881 * at least the length of the modulus of <b>env</b>.
884 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
885 size_t tolen,
886 const char *from, size_t fromlen)
888 int r;
889 tor_assert(env);
890 tor_assert(from);
891 tor_assert(to);
892 tor_assert(fromlen < INT_MAX);
893 tor_assert(tolen >= crypto_pk_keysize(env));
894 r = RSA_public_decrypt((int)fromlen,
895 (unsigned char*)from, (unsigned char*)to,
896 env->key, RSA_PKCS1_PADDING);
898 if (r<0) {
899 crypto_log_errors(LOG_WARN, "checking RSA signature");
900 return -1;
902 return r;
905 /** Check a siglen-byte long signature at <b>sig</b> against
906 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
907 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
908 * SHA1(data). Else return -1.
911 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
912 size_t datalen, const char *sig, size_t siglen)
914 char digest[DIGEST_LEN];
915 char *buf;
916 size_t buflen;
917 int r;
919 tor_assert(env);
920 tor_assert(data);
921 tor_assert(sig);
922 tor_assert(datalen < SIZE_T_CEILING);
923 tor_assert(siglen < SIZE_T_CEILING);
925 if (crypto_digest(digest,data,datalen)<0) {
926 log_warn(LD_BUG, "couldn't compute digest");
927 return -1;
929 buflen = crypto_pk_keysize(env);
930 buf = tor_malloc(buflen);
931 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
932 if (r != DIGEST_LEN) {
933 log_warn(LD_CRYPTO, "Invalid signature");
934 tor_free(buf);
935 return -1;
937 if (tor_memneq(buf, digest, DIGEST_LEN)) {
938 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
939 tor_free(buf);
940 return -1;
942 tor_free(buf);
944 return 0;
947 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
948 * <b>env</b>, using PKCS1 padding. On success, write the signature to
949 * <b>to</b>, and return the number of bytes written. On failure, return
950 * -1.
952 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
953 * at least the length of the modulus of <b>env</b>.
956 crypto_pk_private_sign(crypto_pk_env_t *env, char *to, size_t tolen,
957 const char *from, size_t fromlen)
959 int r;
960 tor_assert(env);
961 tor_assert(from);
962 tor_assert(to);
963 tor_assert(fromlen < INT_MAX);
964 tor_assert(tolen >= crypto_pk_keysize(env));
965 if (!env->key->p)
966 /* Not a private key */
967 return -1;
969 r = RSA_private_encrypt((int)fromlen,
970 (unsigned char*)from, (unsigned char*)to,
971 env->key, RSA_PKCS1_PADDING);
972 if (r<0) {
973 crypto_log_errors(LOG_WARN, "generating RSA signature");
974 return -1;
976 return r;
979 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
980 * <b>from</b>; sign the data with the private key in <b>env</b>, and
981 * store it in <b>to</b>. Return the number of bytes written on
982 * success, and -1 on failure.
984 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
985 * at least the length of the modulus of <b>env</b>.
988 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to, size_t tolen,
989 const char *from, size_t fromlen)
991 int r;
992 char digest[DIGEST_LEN];
993 if (crypto_digest(digest,from,fromlen)<0)
994 return -1;
995 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
996 memset(digest, 0, sizeof(digest));
997 return r;
1000 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1001 * bytes of data from <b>from</b>, with padding type 'padding',
1002 * storing the results on <b>to</b>.
1004 * If no padding is used, the public key must be at least as large as
1005 * <b>from</b>.
1007 * Returns the number of bytes written on success, -1 on failure.
1009 * The encrypted data consists of:
1010 * - The source data, padded and encrypted with the public key, if the
1011 * padded source data is no longer than the public key, and <b>force</b>
1012 * is false, OR
1013 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1014 * padded and encrypted with the public key; followed by the rest of
1015 * the source data encrypted in AES-CTR mode with the symmetric key.
1018 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
1019 char *to, size_t tolen,
1020 const char *from,
1021 size_t fromlen,
1022 int padding, int force)
1024 int overhead, outlen, r;
1025 size_t pkeylen, symlen;
1026 crypto_cipher_env_t *cipher = NULL;
1027 char *buf = NULL;
1029 tor_assert(env);
1030 tor_assert(from);
1031 tor_assert(to);
1032 tor_assert(fromlen < SIZE_T_CEILING);
1034 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1035 pkeylen = crypto_pk_keysize(env);
1037 if (padding == PK_NO_PADDING && fromlen < pkeylen)
1038 return -1;
1040 if (!force && fromlen+overhead <= pkeylen) {
1041 /* It all fits in a single encrypt. */
1042 return crypto_pk_public_encrypt(env,to,
1043 tolen,
1044 from,fromlen,padding);
1046 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1047 tor_assert(tolen >= pkeylen);
1049 cipher = crypto_new_cipher_env();
1050 if (!cipher) return -1;
1051 if (crypto_cipher_generate_key(cipher)<0)
1052 goto err;
1053 /* You can't just run around RSA-encrypting any bitstream: if it's
1054 * greater than the RSA key, then OpenSSL will happily encrypt, and
1055 * later decrypt to the wrong value. So we set the first bit of
1056 * 'cipher->key' to 0 if we aren't padding. This means that our
1057 * symmetric key is really only 127 bits.
1059 if (padding == PK_NO_PADDING)
1060 cipher->key[0] &= 0x7f;
1061 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
1062 goto err;
1063 buf = tor_malloc(pkeylen+1);
1064 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1065 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1067 /* Length of symmetrically encrypted data. */
1068 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1070 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1071 if (outlen!=(int)pkeylen) {
1072 goto err;
1074 r = crypto_cipher_encrypt(cipher, to+outlen,
1075 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1077 if (r<0) goto err;
1078 memset(buf, 0, pkeylen);
1079 tor_free(buf);
1080 crypto_free_cipher_env(cipher);
1081 tor_assert(outlen+symlen < INT_MAX);
1082 return (int)(outlen + symlen);
1083 err:
1084 if (buf) {
1085 memset(buf, 0, pkeylen);
1086 tor_free(buf);
1088 if (cipher) crypto_free_cipher_env(cipher);
1089 return -1;
1092 /** Invert crypto_pk_public_hybrid_encrypt. */
1094 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1095 char *to,
1096 size_t tolen,
1097 const char *from,
1098 size_t fromlen,
1099 int padding, int warnOnFailure)
1101 int outlen, r;
1102 size_t pkeylen;
1103 crypto_cipher_env_t *cipher = NULL;
1104 char *buf = NULL;
1106 tor_assert(fromlen < SIZE_T_CEILING);
1107 pkeylen = crypto_pk_keysize(env);
1109 if (fromlen <= pkeylen) {
1110 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1111 warnOnFailure);
1114 buf = tor_malloc(pkeylen);
1115 outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
1116 warnOnFailure);
1117 if (outlen<0) {
1118 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1119 "Error decrypting public-key data");
1120 goto err;
1122 if (outlen < CIPHER_KEY_LEN) {
1123 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1124 "No room for a symmetric key");
1125 goto err;
1127 cipher = crypto_create_init_cipher(buf, 0);
1128 if (!cipher) {
1129 goto err;
1131 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1132 outlen -= CIPHER_KEY_LEN;
1133 tor_assert(tolen - outlen >= fromlen - pkeylen);
1134 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1135 if (r<0)
1136 goto err;
1137 memset(buf,0,pkeylen);
1138 tor_free(buf);
1139 crypto_free_cipher_env(cipher);
1140 tor_assert(outlen + fromlen < INT_MAX);
1141 return (int)(outlen + (fromlen-pkeylen));
1142 err:
1143 memset(buf,0,pkeylen);
1144 tor_free(buf);
1145 if (cipher) crypto_free_cipher_env(cipher);
1146 return -1;
1149 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1150 * Return -1 on error, or the number of characters used on success.
1153 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1155 int len;
1156 unsigned char *buf, *cp;
1157 len = i2d_RSAPublicKey(pk->key, NULL);
1158 if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
1159 return -1;
1160 cp = buf = tor_malloc(len+1);
1161 len = i2d_RSAPublicKey(pk->key, &cp);
1162 if (len < 0) {
1163 crypto_log_errors(LOG_WARN,"encoding public key");
1164 tor_free(buf);
1165 return -1;
1167 /* We don't encode directly into 'dest', because that would be illegal
1168 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1170 memcpy(dest,buf,len);
1171 tor_free(buf);
1172 return len;
1175 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1176 * success and NULL on failure.
1178 crypto_pk_env_t *
1179 crypto_pk_asn1_decode(const char *str, size_t len)
1181 RSA *rsa;
1182 unsigned char *buf;
1183 const unsigned char *cp;
1184 cp = buf = tor_malloc(len);
1185 memcpy(buf,str,len);
1186 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1187 tor_free(buf);
1188 if (!rsa) {
1189 crypto_log_errors(LOG_WARN,"decoding public key");
1190 return NULL;
1192 return _crypto_new_pk_env_rsa(rsa);
1195 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1196 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1197 * Return 0 on success, -1 on failure.
1200 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1202 unsigned char *buf, *bufp;
1203 int len;
1205 len = i2d_RSAPublicKey(pk->key, NULL);
1206 if (len < 0)
1207 return -1;
1208 buf = bufp = tor_malloc(len+1);
1209 len = i2d_RSAPublicKey(pk->key, &bufp);
1210 if (len < 0) {
1211 crypto_log_errors(LOG_WARN,"encoding public key");
1212 tor_free(buf);
1213 return -1;
1215 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1216 tor_free(buf);
1217 return -1;
1219 tor_free(buf);
1220 return 0;
1223 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1224 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1226 crypto_pk_get_all_digests(crypto_pk_env_t *pk, digests_t *digests_out)
1228 unsigned char *buf, *bufp;
1229 int len;
1231 len = i2d_RSAPublicKey(pk->key, NULL);
1232 if (len < 0)
1233 return -1;
1234 buf = bufp = tor_malloc(len+1);
1235 len = i2d_RSAPublicKey(pk->key, &bufp);
1236 if (len < 0) {
1237 crypto_log_errors(LOG_WARN,"encoding public key");
1238 tor_free(buf);
1239 return -1;
1241 if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
1242 tor_free(buf);
1243 return -1;
1245 tor_free(buf);
1246 return 0;
1249 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1250 * every four spaces. */
1251 /* static */ void
1252 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1254 int n = 0;
1255 char *end = out+outlen;
1256 tor_assert(outlen < SIZE_T_CEILING);
1258 while (*in && out<end) {
1259 *out++ = *in++;
1260 if (++n == 4 && *in && out<end) {
1261 n = 0;
1262 *out++ = ' ';
1265 tor_assert(out<end);
1266 *out = '\0';
1269 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1270 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1271 * space). Return 0 on success, -1 on failure.
1273 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1274 * of the public key, converted to hexadecimal, in upper case, with a
1275 * space after every four digits.
1277 * If <b>add_space</b> is false, omit the spaces.
1280 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1282 char digest[DIGEST_LEN];
1283 char hexdigest[HEX_DIGEST_LEN+1];
1284 if (crypto_pk_get_digest(pk, digest)) {
1285 return -1;
1287 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1288 if (add_space) {
1289 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1290 } else {
1291 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1293 return 0;
1296 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1299 crypto_pk_check_fingerprint_syntax(const char *s)
1301 int i;
1302 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1303 if ((i%5) == 4) {
1304 if (!TOR_ISSPACE(s[i])) return 0;
1305 } else {
1306 if (!TOR_ISXDIGIT(s[i])) return 0;
1309 if (s[FINGERPRINT_LEN]) return 0;
1310 return 1;
1313 /* symmetric crypto */
1315 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1316 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1319 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1321 tor_assert(env);
1323 return crypto_rand(env->key, CIPHER_KEY_LEN);
1326 /** Set the symmetric key for the cipher in <b>env</b> to the first
1327 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1329 void
1330 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1332 tor_assert(env);
1333 tor_assert(key);
1335 memcpy(env->key, key, CIPHER_KEY_LEN);
1338 /** Generate an initialization vector for our AES-CTR cipher; store it
1339 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1340 void
1341 crypto_cipher_generate_iv(char *iv_out)
1343 crypto_rand(iv_out, CIPHER_IV_LEN);
1346 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1347 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1348 * <b>iv</b>. */
1350 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1352 tor_assert(env);
1353 tor_assert(iv);
1354 aes_set_iv(env->cipher, iv);
1355 return 0;
1358 /** Return a pointer to the key set for the cipher in <b>env</b>.
1360 const char *
1361 crypto_cipher_get_key(crypto_cipher_env_t *env)
1363 return env->key;
1366 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1367 * success, -1 on failure.
1370 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1372 tor_assert(env);
1374 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1375 return 0;
1378 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1379 * success, -1 on failure.
1382 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1384 tor_assert(env);
1386 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1387 return 0;
1390 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1391 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1392 * On failure, return -1.
1395 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1396 const char *from, size_t fromlen)
1398 tor_assert(env);
1399 tor_assert(env->cipher);
1400 tor_assert(from);
1401 tor_assert(fromlen);
1402 tor_assert(to);
1403 tor_assert(fromlen < SIZE_T_CEILING);
1405 aes_crypt(env->cipher, from, fromlen, to);
1406 return 0;
1409 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1410 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1411 * On failure, return -1.
1414 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1415 const char *from, size_t fromlen)
1417 tor_assert(env);
1418 tor_assert(from);
1419 tor_assert(to);
1420 tor_assert(fromlen < SIZE_T_CEILING);
1422 aes_crypt(env->cipher, from, fromlen, to);
1423 return 0;
1426 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1427 * on success, return 0. On failure, return -1.
1430 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1432 tor_assert(len < SIZE_T_CEILING);
1433 aes_crypt_inplace(env->cipher, buf, len);
1434 return 0;
1437 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1438 * <b>cipher</b> to the buffer in <b>to</b> of length
1439 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1440 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1441 * number of bytes written, on failure, return -1.
1443 * This function adjusts the current position of the counter in <b>cipher</b>
1444 * to immediately after the encrypted data.
1447 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1448 char *to, size_t tolen,
1449 const char *from, size_t fromlen)
1451 tor_assert(cipher);
1452 tor_assert(from);
1453 tor_assert(to);
1454 tor_assert(fromlen < INT_MAX);
1456 if (fromlen < 1)
1457 return -1;
1458 if (tolen < fromlen + CIPHER_IV_LEN)
1459 return -1;
1461 crypto_cipher_generate_iv(to);
1462 if (crypto_cipher_set_iv(cipher, to)<0)
1463 return -1;
1464 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1465 return (int)(fromlen + CIPHER_IV_LEN);
1468 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1469 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1470 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1471 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1472 * number of bytes written, on failure, return -1.
1474 * This function adjusts the current position of the counter in <b>cipher</b>
1475 * to immediately after the decrypted data.
1478 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1479 char *to, size_t tolen,
1480 const char *from, size_t fromlen)
1482 tor_assert(cipher);
1483 tor_assert(from);
1484 tor_assert(to);
1485 tor_assert(fromlen < INT_MAX);
1487 if (fromlen <= CIPHER_IV_LEN)
1488 return -1;
1489 if (tolen < fromlen - CIPHER_IV_LEN)
1490 return -1;
1492 if (crypto_cipher_set_iv(cipher, from)<0)
1493 return -1;
1494 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1495 return (int)(fromlen - CIPHER_IV_LEN);
1498 /* SHA-1 */
1500 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1501 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1502 * Return 0 on success, -1 on failure.
1505 crypto_digest(char *digest, const char *m, size_t len)
1507 tor_assert(m);
1508 tor_assert(digest);
1509 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1512 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1513 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1514 * into <b>digest</b>. Return 0 on success, -1 on failure. */
1516 crypto_digest256(char *digest, const char *m, size_t len,
1517 digest_algorithm_t algorithm)
1519 tor_assert(m);
1520 tor_assert(digest);
1521 tor_assert(algorithm == DIGEST_SHA256);
1522 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1525 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1526 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1527 * success, -1 on failure. */
1529 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1531 digest_algorithm_t i;
1532 tor_assert(ds_out);
1533 memset(ds_out, 0, sizeof(*ds_out));
1534 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1535 return -1;
1536 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1537 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1538 return -1;
1540 return 0;
1543 /** Return the name of an algorithm, as used in directory documents. */
1544 const char *
1545 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1547 switch (alg) {
1548 case DIGEST_SHA1:
1549 return "sha1";
1550 case DIGEST_SHA256:
1551 return "sha256";
1552 default:
1553 tor_fragile_assert();
1554 return "??unknown_digest??";
1558 /** Given the name of a digest algorithm, return its integer value, or -1 if
1559 * the name is not recognized. */
1561 crypto_digest_algorithm_parse_name(const char *name)
1563 if (!strcmp(name, "sha1"))
1564 return DIGEST_SHA1;
1565 else if (!strcmp(name, "sha256"))
1566 return DIGEST_SHA256;
1567 else
1568 return -1;
1571 /** Intermediate information about the digest of a stream of data. */
1572 struct crypto_digest_env_t {
1573 union {
1574 SHA_CTX sha1; /**< state for SHA1 */
1575 SHA256_CTX sha2; /**< state for SHA256 */
1576 } d; /**< State for the digest we're using. Only one member of the
1577 * union is usable, depending on the value of <b>algorithm</b>. */
1578 digest_algorithm_t algorithm : 8; /**< Which algorithm is in use? */
1581 /** Allocate and return a new digest object to compute SHA1 digests.
1583 crypto_digest_env_t *
1584 crypto_new_digest_env(void)
1586 crypto_digest_env_t *r;
1587 r = tor_malloc(sizeof(crypto_digest_env_t));
1588 SHA1_Init(&r->d.sha1);
1589 r->algorithm = DIGEST_SHA1;
1590 return r;
1593 /** Allocate and return a new digest object to compute 256-bit digests
1594 * using <b>algorithm</b>. */
1595 crypto_digest_env_t *
1596 crypto_new_digest256_env(digest_algorithm_t algorithm)
1598 crypto_digest_env_t *r;
1599 tor_assert(algorithm == DIGEST_SHA256);
1600 r = tor_malloc(sizeof(crypto_digest_env_t));
1601 SHA256_Init(&r->d.sha2);
1602 r->algorithm = algorithm;
1603 return r;
1606 /** Deallocate a digest object.
1608 void
1609 crypto_free_digest_env(crypto_digest_env_t *digest)
1611 if (!digest)
1612 return;
1613 memset(digest, 0, sizeof(crypto_digest_env_t));
1614 tor_free(digest);
1617 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1619 void
1620 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1621 size_t len)
1623 tor_assert(digest);
1624 tor_assert(data);
1625 /* Using the SHA*_*() calls directly means we don't support doing
1626 * SHA in hardware. But so far the delay of getting the question
1627 * to the hardware, and hearing the answer, is likely higher than
1628 * just doing it ourselves. Hashes are fast.
1630 switch (digest->algorithm) {
1631 case DIGEST_SHA1:
1632 SHA1_Update(&digest->d.sha1, (void*)data, len);
1633 break;
1634 case DIGEST_SHA256:
1635 SHA256_Update(&digest->d.sha2, (void*)data, len);
1636 break;
1637 default:
1638 tor_fragile_assert();
1639 break;
1643 /** Compute the hash of the data that has been passed to the digest
1644 * object; write the first out_len bytes of the result to <b>out</b>.
1645 * <b>out_len</b> must be \<= DIGEST256_LEN.
1647 void
1648 crypto_digest_get_digest(crypto_digest_env_t *digest,
1649 char *out, size_t out_len)
1651 unsigned char r[DIGEST256_LEN];
1652 crypto_digest_env_t tmpenv;
1653 tor_assert(digest);
1654 tor_assert(out);
1655 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1656 memcpy(&tmpenv, digest, sizeof(crypto_digest_env_t));
1657 switch (digest->algorithm) {
1658 case DIGEST_SHA1:
1659 tor_assert(out_len <= DIGEST_LEN);
1660 SHA1_Final(r, &tmpenv.d.sha1);
1661 break;
1662 case DIGEST_SHA256:
1663 tor_assert(out_len <= DIGEST256_LEN);
1664 SHA256_Final(r, &tmpenv.d.sha2);
1665 break;
1666 default:
1667 log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
1668 /* If fragile_assert is not enabled, then we should at least not
1669 * leak anything. */
1670 memset(r, 0xff, sizeof(r));
1671 tor_fragile_assert();
1672 break;
1674 memcpy(out, r, out_len);
1675 memset(r, 0, sizeof(r));
1678 /** Allocate and return a new digest object with the same state as
1679 * <b>digest</b>
1681 crypto_digest_env_t *
1682 crypto_digest_dup(const crypto_digest_env_t *digest)
1684 crypto_digest_env_t *r;
1685 tor_assert(digest);
1686 r = tor_malloc(sizeof(crypto_digest_env_t));
1687 memcpy(r,digest,sizeof(crypto_digest_env_t));
1688 return r;
1691 /** Replace the state of the digest object <b>into</b> with the state
1692 * of the digest object <b>from</b>.
1694 void
1695 crypto_digest_assign(crypto_digest_env_t *into,
1696 const crypto_digest_env_t *from)
1698 tor_assert(into);
1699 tor_assert(from);
1700 memcpy(into,from,sizeof(crypto_digest_env_t));
1703 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1704 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1705 * in <b>hmac_out</b>.
1707 void
1708 crypto_hmac_sha1(char *hmac_out,
1709 const char *key, size_t key_len,
1710 const char *msg, size_t msg_len)
1712 tor_assert(key_len < INT_MAX);
1713 tor_assert(msg_len < INT_MAX);
1714 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1715 (unsigned char*)hmac_out, NULL);
1718 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
1719 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1720 * in <b>hmac_out</b>.
1722 void
1723 crypto_hmac_sha256(char *hmac_out,
1724 const char *key, size_t key_len,
1725 const char *msg, size_t msg_len)
1727 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(0,9,8)
1728 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
1729 tor_assert(key_len < INT_MAX);
1730 tor_assert(msg_len < INT_MAX);
1731 HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1732 (unsigned char*)hmac_out, NULL);
1733 #else
1734 /* OpenSSL doesn't have an EVP implementation for SHA256. We'll need
1735 to do HMAC on our own.
1737 HMAC isn't so hard: To compute HMAC(key, msg):
1738 1. If len(key) > blocksize, key = H(key).
1739 2. If len(key) < blocksize, right-pad key up to blocksize with 0 bytes.
1740 3. let ipad = key xor 0x363636363636....36
1741 let opad = key xor 0x5c5c5c5c5c5c....5c
1742 The result is H(opad | H( ipad | msg ) )
1744 #define BLOCKSIZE 64
1745 #define DIGESTSIZE 32
1746 uint8_t k[BLOCKSIZE];
1747 uint8_t pad[BLOCKSIZE];
1748 uint8_t d[DIGESTSIZE];
1749 int i;
1750 SHA256_CTX st;
1752 tor_assert(key_len < INT_MAX);
1753 tor_assert(msg_len < INT_MAX);
1755 if (key_len <= BLOCKSIZE) {
1756 memset(k, 0, sizeof(k));
1757 memcpy(k, key, key_len); /* not time invariant in key_len */
1758 } else {
1759 SHA256((const uint8_t *)key, key_len, k);
1760 memset(k+DIGESTSIZE, 0, sizeof(k)-DIGESTSIZE);
1762 for (i = 0; i < BLOCKSIZE; ++i)
1763 pad[i] = k[i] ^ 0x36;
1764 SHA256_Init(&st);
1765 SHA256_Update(&st, pad, BLOCKSIZE);
1766 SHA256_Update(&st, (uint8_t*)msg, msg_len);
1767 SHA256_Final(d, &st);
1769 for (i = 0; i < BLOCKSIZE; ++i)
1770 pad[i] = k[i] ^ 0x5c;
1771 SHA256_Init(&st);
1772 SHA256_Update(&st, pad, BLOCKSIZE);
1773 SHA256_Update(&st, d, DIGESTSIZE);
1774 SHA256_Final((uint8_t*)hmac_out, &st);
1776 /* Now clear everything. */
1777 memset(k, 0, sizeof(k));
1778 memset(pad, 0, sizeof(pad));
1779 memset(d, 0, sizeof(d));
1780 memset(&st, 0, sizeof(st));
1781 #undef BLOCKSIZE
1782 #undef DIGESTSIZE
1783 #endif
1786 /* DH */
1788 /** Our DH 'g' parameter */
1789 #define DH_GENERATOR 2
1791 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1792 static BIGNUM *dh_param_p = NULL;
1793 /** Shared P parameter for our TLS DH key exchanges. */
1794 static BIGNUM *dh_param_p_tls = NULL;
1795 /** Shared G parameter for our DH key exchanges. */
1796 static BIGNUM *dh_param_g = NULL;
1798 /** Generate and return a reasonable and safe DH parameter p. */
1799 static BIGNUM *
1800 crypto_generate_dynamic_dh_modulus(void)
1802 BIGNUM *dynamic_dh_modulus;
1803 DH *dh_parameters;
1804 int r, dh_codes;
1805 char *s;
1807 dynamic_dh_modulus = BN_new();
1808 tor_assert(dynamic_dh_modulus);
1810 dh_parameters = DH_generate_parameters(DH_BYTES*8, DH_GENERATOR, NULL, NULL);
1811 tor_assert(dh_parameters);
1813 r = DH_check(dh_parameters, &dh_codes);
1814 tor_assert(r && !dh_codes);
1816 BN_copy(dynamic_dh_modulus, dh_parameters->p);
1817 tor_assert(dynamic_dh_modulus);
1819 DH_free(dh_parameters);
1821 { /* log the dynamic DH modulus: */
1822 s = BN_bn2hex(dynamic_dh_modulus);
1823 tor_assert(s);
1824 log_info(LD_OR, "Dynamic DH modulus generated: [%s]", s);
1825 OPENSSL_free(s);
1828 return dynamic_dh_modulus;
1831 /** Store our dynamic DH modulus (and its group parameters) to
1832 <b>fname</b> for future use. */
1833 static int
1834 crypto_store_dynamic_dh_modulus(const char *fname)
1836 int len, new_len;
1837 DH *dh = NULL;
1838 unsigned char *dh_string_repr = NULL, *cp = NULL;
1839 char *base64_encoded_dh = NULL;
1840 char *file_string = NULL;
1841 int retval = -1;
1842 static const char file_header[] = "# This file contains stored Diffie-"
1843 "Hellman parameters for future use.\n# You *do not* need to edit this "
1844 "file.\n\n";
1846 tor_assert(fname);
1848 if (!dh_param_p_tls) {
1849 log_info(LD_CRYPTO, "Tried to store a DH modulus that does not exist.");
1850 goto done;
1853 if (!(dh = DH_new()))
1854 goto done;
1855 if (!(dh->p = BN_dup(dh_param_p_tls)))
1856 goto done;
1857 if (!(dh->g = BN_new()))
1858 goto done;
1859 if (!BN_set_word(dh->g, DH_GENERATOR))
1860 goto done;
1862 len = i2d_DHparams(dh, NULL);
1863 if (len < 0) {
1864 log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (1).");
1865 goto done;
1868 cp = dh_string_repr = tor_malloc_zero(len+1);
1869 len = i2d_DHparams(dh, &cp);
1870 if ((len < 0) || ((cp - dh_string_repr) != len)) {
1871 log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (2).");
1872 goto done;
1875 base64_encoded_dh = tor_malloc_zero(len * 2); /* should be enough */
1876 new_len = base64_encode(base64_encoded_dh, len * 2,
1877 (char *)dh_string_repr, len);
1878 if (new_len < 0) {
1879 log_warn(LD_CRYPTO, "Error occured while base64-encoding DH modulus.");
1880 goto done;
1883 /* concatenate file header and the dh parameters blob */
1884 new_len = tor_asprintf(&file_string, "%s%s", file_header, base64_encoded_dh);
1886 /* write to file */
1887 if (write_bytes_to_new_file(fname, file_string, new_len, 0) < 0) {
1888 log_info(LD_CRYPTO, "'%s' was already occupied.", fname);
1889 goto done;
1892 retval = 0;
1894 done:
1895 if (dh)
1896 DH_free(dh);
1897 tor_free(dh_string_repr);
1898 tor_free(base64_encoded_dh);
1899 tor_free(file_string);
1901 return retval;
1904 /** Return the dynamic DH modulus stored in <b>fname</b>. If there is no
1905 dynamic DH modulus stored in <b>fname</b>, return NULL. */
1906 static BIGNUM *
1907 crypto_get_stored_dynamic_dh_modulus(const char *fname)
1909 int retval;
1910 char *contents = NULL;
1911 const char *contents_tmp = NULL;
1912 int dh_codes;
1913 char *fname_new = NULL;
1914 DH *stored_dh = NULL;
1915 BIGNUM *dynamic_dh_modulus = NULL;
1916 int length = 0;
1917 unsigned char *base64_decoded_dh = NULL;
1918 const unsigned char *cp = NULL;
1920 tor_assert(fname);
1922 contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
1923 if (!contents) {
1924 log_info(LD_CRYPTO, "Could not open file '%s'", fname);
1925 goto done; /*usually means that ENOENT. don't try to move file to broken.*/
1928 /* skip the file header */
1929 contents_tmp = eat_whitespace(contents);
1930 if (!*contents_tmp) {
1931 log_warn(LD_CRYPTO, "Stored dynamic DH modulus file "
1932 "seems corrupted (eat_whitespace).");
1933 goto err;
1936 /* 'fname' contains the DH parameters stored in base64-ed DER
1937 * format. We are only interested in the DH modulus.
1938 * NOTE: We allocate more storage here than we need. Since we're already
1939 * doing that, we can also add 1 byte extra to appease Coverity's
1940 * scanner. */
1942 cp = base64_decoded_dh = tor_malloc_zero(strlen(contents_tmp) + 1);
1943 length = base64_decode((char *)base64_decoded_dh, strlen(contents_tmp),
1944 contents_tmp, strlen(contents_tmp));
1945 if (length < 0) {
1946 log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (base64).");
1947 goto err;
1950 stored_dh = d2i_DHparams(NULL, &cp, length);
1951 if ((!stored_dh) || (cp - base64_decoded_dh != length)) {
1952 log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (d2i).");
1953 goto err;
1956 { /* check the cryptographic qualities of the stored dynamic DH modulus: */
1957 retval = DH_check(stored_dh, &dh_codes);
1958 if (!retval || dh_codes) {
1959 log_warn(LD_CRYPTO, "Stored dynamic DH modulus is not a safe prime.");
1960 goto err;
1963 retval = DH_size(stored_dh);
1964 if (retval < DH_BYTES) {
1965 log_warn(LD_CRYPTO, "Stored dynamic DH modulus is smaller "
1966 "than '%d' bits.", DH_BYTES*8);
1967 goto err;
1970 if (!BN_is_word(stored_dh->g, 2)) {
1971 log_warn(LD_CRYPTO, "Stored dynamic DH parameters do not use '2' "
1972 "as the group generator.");
1973 goto err;
1977 { /* log the dynamic DH modulus: */
1978 char *s = BN_bn2hex(stored_dh->p);
1979 tor_assert(s);
1980 log_info(LD_OR, "Found stored dynamic DH modulus: [%s]", s);
1981 OPENSSL_free(s);
1984 goto done;
1986 err:
1988 { /* move broken prime to $filename.broken */
1989 fname_new = tor_malloc(strlen(fname) + 8);
1991 /* no can do if these functions return error */
1992 strlcpy(fname_new, fname, strlen(fname) + 8);
1993 strlcat(fname_new, ".broken", strlen(fname) + 8);
1995 log_warn(LD_CRYPTO, "Moving broken dynamic DH prime to '%s'.", fname_new);
1997 if (replace_file(fname, fname_new))
1998 log_notice(LD_CRYPTO, "Error while moving '%s' to '%s'.",
1999 fname, fname_new);
2001 tor_free(fname_new);
2004 if (stored_dh) {
2005 DH_free(stored_dh);
2006 stored_dh = NULL;
2009 done:
2010 tor_free(contents);
2011 tor_free(base64_decoded_dh);
2013 if (stored_dh) {
2014 dynamic_dh_modulus = BN_dup(stored_dh->p);
2015 DH_free(stored_dh);
2018 return dynamic_dh_modulus;
2021 /** Set the global TLS Diffie-Hellman modulus.
2022 * If <b>dynamic_dh_modulus_fname</b> is set, try to read a dynamic DH modulus
2023 * off it and use it as the DH modulus. If that's not possible,
2024 * generate a new dynamic DH modulus.
2025 * If <b>dynamic_dh_modulus_fname</b> is NULL, use the Apache mod_ssl DH
2026 * modulus. */
2027 void
2028 crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname)
2030 BIGNUM *tls_prime = NULL;
2031 int store_dh_prime_afterwards = 0;
2032 int r;
2034 /* If the space is occupied, free the previous TLS DH prime */
2035 if (dh_param_p_tls) {
2036 BN_free(dh_param_p_tls);
2037 dh_param_p_tls = NULL;
2040 if (dynamic_dh_modulus_fname) { /* use dynamic DH modulus: */
2041 log_info(LD_OR, "Using stored dynamic DH modulus.");
2042 tls_prime = crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname);
2044 if (!tls_prime) {
2045 log_notice(LD_OR, "Generating fresh dynamic DH modulus. "
2046 "This might take a while...");
2047 tls_prime = crypto_generate_dynamic_dh_modulus();
2049 store_dh_prime_afterwards++;
2051 } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
2052 tls_prime = BN_new();
2053 tor_assert(tls_prime);
2055 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
2056 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
2057 * prime.
2059 r =BN_hex2bn(&tls_prime,
2060 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
2061 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
2062 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
2063 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
2064 "B0E7393E0F24218EB3");
2065 tor_assert(r);
2068 tor_assert(tls_prime);
2070 dh_param_p_tls = tls_prime;
2072 if (store_dh_prime_afterwards)
2073 /* save the new dynamic DH modulus to disk. */
2074 if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname)) {
2075 log_notice(LD_CRYPTO, "Failed while storing dynamic DH modulus. "
2076 "Make sure your data directory is sane.");
2080 /** Initialize dh_param_p and dh_param_g if they are not already
2081 * set. */
2082 static void
2083 init_dh_param(void)
2085 BIGNUM *circuit_dh_prime, *generator;
2086 int r;
2087 if (dh_param_p && dh_param_g)
2088 return;
2090 circuit_dh_prime = BN_new();
2091 generator = BN_new();
2092 tor_assert(circuit_dh_prime && generator);
2094 /* Set our generator for all DH parameters */
2095 r = BN_set_word(generator, DH_GENERATOR);
2096 tor_assert(r);
2098 /* This is from rfc2409, section 6.2. It's a safe prime, and
2099 supposedly it equals:
2100 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
2102 r = BN_hex2bn(&circuit_dh_prime,
2103 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
2104 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
2105 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
2106 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
2107 "49286651ECE65381FFFFFFFFFFFFFFFF");
2108 tor_assert(r);
2110 /* Set the new values as the global DH parameters. */
2111 dh_param_p = circuit_dh_prime;
2112 dh_param_g = generator;
2114 /* Ensure that we have TLS DH parameters set up, too, even if we're
2115 going to change them soon. */
2116 if (!dh_param_p_tls) {
2117 crypto_set_tls_dh_prime(NULL);
2121 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
2122 * handshake. Since we exponentiate by this value, choosing a smaller one
2123 * lets our handhake go faster.
2125 #define DH_PRIVATE_KEY_BITS 320
2127 /** Allocate and return a new DH object for a key exchange.
2129 crypto_dh_env_t *
2130 crypto_dh_new(int dh_type)
2132 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
2134 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
2135 dh_type == DH_TYPE_REND);
2137 if (!dh_param_p)
2138 init_dh_param();
2140 if (!(res->dh = DH_new()))
2141 goto err;
2143 if (dh_type == DH_TYPE_TLS) {
2144 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
2145 goto err;
2146 } else {
2147 if (!(res->dh->p = BN_dup(dh_param_p)))
2148 goto err;
2151 if (!(res->dh->g = BN_dup(dh_param_g)))
2152 goto err;
2154 res->dh->length = DH_PRIVATE_KEY_BITS;
2156 return res;
2157 err:
2158 crypto_log_errors(LOG_WARN, "creating DH object");
2159 if (res->dh) DH_free(res->dh); /* frees p and g too */
2160 tor_free(res);
2161 return NULL;
2164 /** Return the length of the DH key in <b>dh</b>, in bytes.
2167 crypto_dh_get_bytes(crypto_dh_env_t *dh)
2169 tor_assert(dh);
2170 return DH_size(dh->dh);
2173 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2174 * success, -1 on failure.
2177 crypto_dh_generate_public(crypto_dh_env_t *dh)
2179 again:
2180 if (!DH_generate_key(dh->dh)) {
2181 crypto_log_errors(LOG_WARN, "generating DH key");
2182 return -1;
2184 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
2185 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
2186 "the-universe chances really do happen. Trying again.");
2187 /* Free and clear the keys, so OpenSSL will actually try again. */
2188 BN_free(dh->dh->pub_key);
2189 BN_free(dh->dh->priv_key);
2190 dh->dh->pub_key = dh->dh->priv_key = NULL;
2191 goto again;
2193 return 0;
2196 /** Generate g^x as necessary, and write the g^x for the key exchange
2197 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2198 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2201 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
2203 int bytes;
2204 tor_assert(dh);
2205 if (!dh->dh->pub_key) {
2206 if (crypto_dh_generate_public(dh)<0)
2207 return -1;
2210 tor_assert(dh->dh->pub_key);
2211 bytes = BN_num_bytes(dh->dh->pub_key);
2212 tor_assert(bytes >= 0);
2213 if (pubkey_len < (size_t)bytes) {
2214 log_warn(LD_CRYPTO,
2215 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2216 (int) pubkey_len, bytes);
2217 return -1;
2220 memset(pubkey, 0, pubkey_len);
2221 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
2223 return 0;
2226 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2227 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2228 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2230 static int
2231 tor_check_dh_key(int severity, BIGNUM *bn)
2233 BIGNUM *x;
2234 char *s;
2235 tor_assert(bn);
2236 x = BN_new();
2237 tor_assert(x);
2238 if (!dh_param_p)
2239 init_dh_param();
2240 BN_set_word(x, 1);
2241 if (BN_cmp(bn,x)<=0) {
2242 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
2243 goto err;
2245 BN_copy(x,dh_param_p);
2246 BN_sub_word(x, 1);
2247 if (BN_cmp(bn,x)>=0) {
2248 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
2249 goto err;
2251 BN_free(x);
2252 return 0;
2253 err:
2254 BN_free(x);
2255 s = BN_bn2hex(bn);
2256 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
2257 OPENSSL_free(s);
2258 return -1;
2261 #undef MIN
2262 #define MIN(a,b) ((a)<(b)?(a):(b))
2263 /** Given a DH key exchange object, and our peer's value of g^y (as a
2264 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2265 * <b>secret_bytes_out</b> bytes of shared key material and write them
2266 * to <b>secret_out</b>. Return the number of bytes generated on success,
2267 * or -1 on failure.
2269 * (We generate key material by computing
2270 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2271 * where || is concatenation.)
2273 ssize_t
2274 crypto_dh_compute_secret(int severity, crypto_dh_env_t *dh,
2275 const char *pubkey, size_t pubkey_len,
2276 char *secret_out, size_t secret_bytes_out)
2278 char *secret_tmp = NULL;
2279 BIGNUM *pubkey_bn = NULL;
2280 size_t secret_len=0, secret_tmp_len=0;
2281 int result=0;
2282 tor_assert(dh);
2283 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
2284 tor_assert(pubkey_len < INT_MAX);
2286 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
2287 (int)pubkey_len, NULL)))
2288 goto error;
2289 if (tor_check_dh_key(severity, pubkey_bn)<0) {
2290 /* Check for invalid public keys. */
2291 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
2292 goto error;
2294 secret_tmp_len = crypto_dh_get_bytes(dh);
2295 secret_tmp = tor_malloc(secret_tmp_len);
2296 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
2297 if (result < 0) {
2298 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
2299 goto error;
2301 secret_len = result;
2302 if (crypto_expand_key_material(secret_tmp, secret_len,
2303 secret_out, secret_bytes_out)<0)
2304 goto error;
2305 secret_len = secret_bytes_out;
2307 goto done;
2308 error:
2309 result = -1;
2310 done:
2311 crypto_log_errors(LOG_WARN, "completing DH handshake");
2312 if (pubkey_bn)
2313 BN_free(pubkey_bn);
2314 if (secret_tmp) {
2315 memset(secret_tmp, 0, secret_tmp_len);
2316 tor_free(secret_tmp);
2318 if (result < 0)
2319 return result;
2320 else
2321 return secret_len;
2324 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2325 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2326 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2327 * H(K | [00]) | H(K | [01]) | ....
2329 * Return 0 on success, -1 on failure.
2332 crypto_expand_key_material(const char *key_in, size_t key_in_len,
2333 char *key_out, size_t key_out_len)
2335 int i;
2336 char *cp, *tmp = tor_malloc(key_in_len+1);
2337 char digest[DIGEST_LEN];
2339 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2340 tor_assert(key_out_len <= DIGEST_LEN*256);
2342 memcpy(tmp, key_in, key_in_len);
2343 for (cp = key_out, i=0; cp < key_out+key_out_len;
2344 ++i, cp += DIGEST_LEN) {
2345 tmp[key_in_len] = i;
2346 if (crypto_digest(digest, tmp, key_in_len+1))
2347 goto err;
2348 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
2350 memset(tmp, 0, key_in_len+1);
2351 tor_free(tmp);
2352 memset(digest, 0, sizeof(digest));
2353 return 0;
2355 err:
2356 memset(tmp, 0, key_in_len+1);
2357 tor_free(tmp);
2358 memset(digest, 0, sizeof(digest));
2359 return -1;
2362 /** Free a DH key exchange object.
2364 void
2365 crypto_dh_free(crypto_dh_env_t *dh)
2367 if (!dh)
2368 return;
2369 tor_assert(dh->dh);
2370 DH_free(dh->dh);
2371 tor_free(dh);
2374 /* random numbers */
2376 /** How many bytes of entropy we add at once.
2378 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2379 * work for us too. */
2380 #define ADD_ENTROPY 32
2382 /** True iff it's safe to use RAND_poll after setup.
2384 * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2385 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2386 * that fd without checking whether it fit in the fd_set. Thus, if the
2387 * system has not just been started up, it is unsafe to call */
2388 #define RAND_POLL_IS_SAFE \
2389 ((OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,7,'j') && \
2390 OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)) || \
2391 OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
2393 /** Set the seed of the weak RNG to a random value. */
2394 static void
2395 seed_weak_rng(void)
2397 unsigned seed;
2398 crypto_rand((void*)&seed, sizeof(seed));
2399 tor_init_weak_random(seed);
2402 /** Seed OpenSSL's random number generator with bytes from the operating
2403 * system. <b>startup</b> should be true iff we have just started Tor and
2404 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2407 crypto_seed_rng(int startup)
2409 int rand_poll_status = 0;
2411 /* local variables */
2412 #ifdef MS_WINDOWS
2413 unsigned char buf[ADD_ENTROPY];
2414 static int provider_set = 0;
2415 static HCRYPTPROV provider;
2416 #else
2417 char buf[ADD_ENTROPY];
2418 static const char *filenames[] = {
2419 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2421 int fd, i;
2422 size_t n;
2423 #endif
2425 /* OpenSSL has a RAND_poll function that knows about more kinds of
2426 * entropy than we do. We'll try calling that, *and* calling our own entropy
2427 * functions. If one succeeds, we'll accept the RNG as seeded. */
2428 if (startup || RAND_POLL_IS_SAFE) {
2429 rand_poll_status = RAND_poll();
2430 if (rand_poll_status == 0)
2431 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2434 #ifdef MS_WINDOWS
2435 if (!provider_set) {
2436 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2437 CRYPT_VERIFYCONTEXT)) {
2438 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
2439 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2440 return rand_poll_status ? 0 : -1;
2443 provider_set = 1;
2445 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
2446 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2447 return rand_poll_status ? 0 : -1;
2449 RAND_seed(buf, sizeof(buf));
2450 memset(buf, 0, sizeof(buf));
2451 seed_weak_rng();
2452 return 0;
2453 #else
2454 for (i = 0; filenames[i]; ++i) {
2455 fd = open(filenames[i], O_RDONLY, 0);
2456 if (fd<0) continue;
2457 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
2458 n = read_all(fd, buf, sizeof(buf), 0);
2459 close(fd);
2460 if (n != sizeof(buf)) {
2461 log_warn(LD_CRYPTO,
2462 "Error reading from entropy source (read only %lu bytes).",
2463 (unsigned long)n);
2464 return -1;
2466 RAND_seed(buf, (int)sizeof(buf));
2467 memset(buf, 0, sizeof(buf));
2468 seed_weak_rng();
2469 return 0;
2472 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
2473 return rand_poll_status ? 0 : -1;
2474 #endif
2477 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2478 * success, -1 on failure.
2481 crypto_rand(char *to, size_t n)
2483 int r;
2484 tor_assert(n < INT_MAX);
2485 tor_assert(to);
2486 r = RAND_bytes((unsigned char*)to, (int)n);
2487 if (r == 0)
2488 crypto_log_errors(LOG_WARN, "generating random data");
2489 return (r == 1) ? 0 : -1;
2492 /** Return a pseudorandom integer, chosen uniformly from the values
2493 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2494 * INT_MAX+1, inclusive. */
2496 crypto_rand_int(unsigned int max)
2498 unsigned int val;
2499 unsigned int cutoff;
2500 tor_assert(max <= ((unsigned int)INT_MAX)+1);
2501 tor_assert(max > 0); /* don't div by 0 */
2503 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2504 * distribution with clipping at the upper end of unsigned int's
2505 * range.
2507 cutoff = UINT_MAX - (UINT_MAX%max);
2508 while (1) {
2509 crypto_rand((char*)&val, sizeof(val));
2510 if (val < cutoff)
2511 return val % max;
2515 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2516 * between 0 and <b>max</b>-1. */
2517 uint64_t
2518 crypto_rand_uint64(uint64_t max)
2520 uint64_t val;
2521 uint64_t cutoff;
2522 tor_assert(max < UINT64_MAX);
2523 tor_assert(max > 0); /* don't div by 0 */
2525 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2526 * distribution with clipping at the upper end of unsigned int's
2527 * range.
2529 cutoff = UINT64_MAX - (UINT64_MAX%max);
2530 while (1) {
2531 crypto_rand((char*)&val, sizeof(val));
2532 if (val < cutoff)
2533 return val % max;
2537 /** Return a pseudorandom double d, chosen uniformly from the range
2538 * 0.0 <= d < 1.0.
2540 double
2541 crypto_rand_double(void)
2543 /* We just use an unsigned int here; we don't really care about getting
2544 * more than 32 bits of resolution */
2545 unsigned int uint;
2546 crypto_rand((char*)&uint, sizeof(uint));
2547 #if SIZEOF_INT == 4
2548 #define UINT_MAX_AS_DOUBLE 4294967296.0
2549 #elif SIZEOF_INT == 8
2550 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2551 #else
2552 #error SIZEOF_INT is neither 4 nor 8
2553 #endif
2554 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2557 /** Generate and return a new random hostname starting with <b>prefix</b>,
2558 * ending with <b>suffix</b>, and containing no fewer than
2559 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2560 * characters between.
2562 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2564 char *
2565 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2566 const char *suffix)
2568 char *result, *rand_bytes;
2569 int randlen, rand_bytes_len;
2570 size_t resultlen, prefixlen;
2572 if (max_rand_len > MAX_DNS_LABEL_SIZE)
2573 max_rand_len = MAX_DNS_LABEL_SIZE;
2574 if (min_rand_len > max_rand_len)
2575 min_rand_len = max_rand_len;
2577 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2579 prefixlen = strlen(prefix);
2580 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2582 rand_bytes_len = ((randlen*5)+7)/8;
2583 if (rand_bytes_len % 5)
2584 rand_bytes_len += 5 - (rand_bytes_len%5);
2585 rand_bytes = tor_malloc(rand_bytes_len);
2586 crypto_rand(rand_bytes, rand_bytes_len);
2588 result = tor_malloc(resultlen);
2589 memcpy(result, prefix, prefixlen);
2590 base32_encode(result+prefixlen, resultlen-prefixlen,
2591 rand_bytes, rand_bytes_len);
2592 tor_free(rand_bytes);
2593 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2595 return result;
2598 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2599 * is empty. */
2600 void *
2601 smartlist_choose(const smartlist_t *sl)
2603 int len = smartlist_len(sl);
2604 if (len)
2605 return smartlist_get(sl,crypto_rand_int(len));
2606 return NULL; /* no elements to choose from */
2609 /** Scramble the elements of <b>sl</b> into a random order. */
2610 void
2611 smartlist_shuffle(smartlist_t *sl)
2613 int i;
2614 /* From the end of the list to the front, choose at random from the
2615 positions we haven't looked at yet, and swap that position into the
2616 current position. Remember to give "no swap" the same probability as
2617 any other swap. */
2618 for (i = smartlist_len(sl)-1; i > 0; --i) {
2619 int j = crypto_rand_int(i+1);
2620 smartlist_swap(sl, i, j);
2624 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2625 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2626 * bytes. Return the number of bytes written on success; -1 if
2627 * destlen is too short, or other failure.
2630 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2632 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2633 * it ever shows up in the profile. */
2634 EVP_ENCODE_CTX ctx;
2635 int len, ret;
2636 tor_assert(srclen < INT_MAX);
2638 /* 48 bytes of input -> 64 bytes of output plus newline.
2639 Plus one more byte, in case I'm wrong.
2641 if (destlen < ((srclen/48)+1)*66)
2642 return -1;
2643 if (destlen > SIZE_T_CEILING)
2644 return -1;
2646 EVP_EncodeInit(&ctx);
2647 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2648 (unsigned char*)src, (int)srclen);
2649 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2650 ret += len;
2651 return ret;
2654 /** @{ */
2655 /** Special values used for the base64_decode_table */
2656 #define X 255
2657 #define SP 64
2658 #define PAD 65
2659 /** @} */
2660 /** Internal table mapping byte values to what they represent in base64.
2661 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2662 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2663 * end-of-string. */
2664 static const uint8_t base64_decode_table[256] = {
2665 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2666 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2667 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2668 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2669 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2670 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2671 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2672 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2673 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2674 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2675 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2676 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2677 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2678 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2679 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2680 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2683 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2684 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2685 * bytes. Return the number of bytes written on success; -1 if
2686 * destlen is too short, or other failure.
2688 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2689 * spaces or padding.
2691 * NOTE 2: This implementation does not check for the correct number of
2692 * padding "=" characters at the end of the string, and does not check
2693 * for internal padding characters.
2696 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2698 #ifdef USE_OPENSSL_BASE64
2699 EVP_ENCODE_CTX ctx;
2700 int len, ret;
2701 /* 64 bytes of input -> *up to* 48 bytes of output.
2702 Plus one more byte, in case I'm wrong.
2704 if (destlen < ((srclen/64)+1)*49)
2705 return -1;
2706 if (destlen > SIZE_T_CEILING)
2707 return -1;
2709 EVP_DecodeInit(&ctx);
2710 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2711 (unsigned char*)src, srclen);
2712 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2713 ret += len;
2714 return ret;
2715 #else
2716 const char *eos = src+srclen;
2717 uint32_t n=0;
2718 int n_idx=0;
2719 char *dest_orig = dest;
2721 /* Max number of bits == srclen*6.
2722 * Number of bytes required to hold all bits == (srclen*6)/8.
2723 * Yes, we want to round down: anything that hangs over the end of a
2724 * byte is padding. */
2725 if (destlen < (srclen*3)/4)
2726 return -1;
2727 if (destlen > SIZE_T_CEILING)
2728 return -1;
2730 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2731 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2732 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2734 for ( ; src < eos; ++src) {
2735 unsigned char c = (unsigned char) *src;
2736 uint8_t v = base64_decode_table[c];
2737 switch (v) {
2738 case X:
2739 /* This character isn't allowed in base64. */
2740 return -1;
2741 case SP:
2742 /* This character is whitespace, and has no effect. */
2743 continue;
2744 case PAD:
2745 /* We've hit an = character: the data is over. */
2746 goto end_of_loop;
2747 default:
2748 /* We have an actual 6-bit value. Append it to the bits in n. */
2749 n = (n<<6) | v;
2750 if ((++n_idx) == 4) {
2751 /* We've accumulated 24 bits in n. Flush them. */
2752 *dest++ = (n>>16);
2753 *dest++ = (n>>8) & 0xff;
2754 *dest++ = (n) & 0xff;
2755 n_idx = 0;
2756 n = 0;
2760 end_of_loop:
2761 /* If we have leftover bits, we need to cope. */
2762 switch (n_idx) {
2763 case 0:
2764 default:
2765 /* No leftover bits. We win. */
2766 break;
2767 case 1:
2768 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2769 return -1;
2770 case 2:
2771 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2772 *dest++ = n >> 4;
2773 break;
2774 case 3:
2775 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2776 *dest++ = n >> 10;
2777 *dest++ = n >> 2;
2780 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2781 tor_assert((dest-dest_orig) <= INT_MAX);
2783 return (int)(dest-dest_orig);
2784 #endif
2786 #undef X
2787 #undef SP
2788 #undef PAD
2790 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2791 * and newline characters, and store the nul-terminated result in the first
2792 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2794 digest_to_base64(char *d64, const char *digest)
2796 char buf[256];
2797 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2798 buf[BASE64_DIGEST_LEN] = '\0';
2799 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2800 return 0;
2803 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2804 * trailing newline or = characters), decode it and store the result in the
2805 * first DIGEST_LEN bytes at <b>digest</b>. */
2807 digest_from_base64(char *digest, const char *d64)
2809 #ifdef USE_OPENSSL_BASE64
2810 char buf_in[BASE64_DIGEST_LEN+3];
2811 char buf[256];
2812 if (strlen(d64) != BASE64_DIGEST_LEN)
2813 return -1;
2814 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2815 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2816 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2817 return -1;
2818 memcpy(digest, buf, DIGEST_LEN);
2819 return 0;
2820 #else
2821 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2822 return 0;
2823 else
2824 return -1;
2825 #endif
2828 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2829 * trailing = and newline characters, and store the nul-terminated result in
2830 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2832 digest256_to_base64(char *d64, const char *digest)
2834 char buf[256];
2835 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2836 buf[BASE64_DIGEST256_LEN] = '\0';
2837 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2838 return 0;
2841 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2842 * trailing newline or = characters), decode it and store the result in the
2843 * first DIGEST256_LEN bytes at <b>digest</b>. */
2845 digest256_from_base64(char *digest, const char *d64)
2847 #ifdef USE_OPENSSL_BASE64
2848 char buf_in[BASE64_DIGEST256_LEN+3];
2849 char buf[256];
2850 if (strlen(d64) != BASE64_DIGEST256_LEN)
2851 return -1;
2852 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2853 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2854 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2855 return -1;
2856 memcpy(digest, buf, DIGEST256_LEN);
2857 return 0;
2858 #else
2859 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2860 return 0;
2861 else
2862 return -1;
2863 #endif
2866 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2867 * that srclen*8 is a multiple of 5.
2869 void
2870 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2872 unsigned int i, v, u;
2873 size_t nbits = srclen * 8, bit;
2875 tor_assert(srclen < SIZE_T_CEILING/8);
2876 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2877 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2878 tor_assert(destlen < SIZE_T_CEILING);
2880 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2881 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2882 v = ((uint8_t)src[bit/8]) << 8;
2883 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2884 /* set u to the 5-bit value at the bit'th bit of src. */
2885 u = (v >> (11-(bit%8))) & 0x1F;
2886 dest[i] = BASE32_CHARS[u];
2888 dest[i] = '\0';
2891 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2892 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2895 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2897 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2898 * it ever shows up in the profile. */
2899 unsigned int i;
2900 size_t nbits, j, bit;
2901 char *tmp;
2902 nbits = srclen * 5;
2904 tor_assert(srclen < SIZE_T_CEILING / 5);
2905 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2906 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2907 tor_assert(destlen < SIZE_T_CEILING);
2909 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2910 tmp = tor_malloc_zero(srclen);
2911 for (j = 0; j < srclen; ++j) {
2912 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2913 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2914 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2915 else {
2916 log_warn(LD_BUG, "illegal character in base32 encoded string");
2917 tor_free(tmp);
2918 return -1;
2922 /* Assemble result byte-wise by applying five possible cases. */
2923 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2924 switch (bit % 40) {
2925 case 0:
2926 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2927 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2928 break;
2929 case 8:
2930 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2931 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2932 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2933 break;
2934 case 16:
2935 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2936 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2937 break;
2938 case 24:
2939 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2940 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2941 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2942 break;
2943 case 32:
2944 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2945 ((uint8_t)tmp[(bit/5)+1]);
2946 break;
2950 memset(tmp, 0, srclen);
2951 tor_free(tmp);
2952 tmp = NULL;
2953 return 0;
2956 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2957 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2958 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2959 * are a salt; the 9th byte describes how much iteration to do.
2960 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2962 void
2963 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2964 size_t secret_len, const char *s2k_specifier)
2966 crypto_digest_env_t *d;
2967 uint8_t c;
2968 size_t count, tmplen;
2969 char *tmp;
2970 tor_assert(key_out_len < SIZE_T_CEILING);
2972 #define EXPBIAS 6
2973 c = s2k_specifier[8];
2974 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2975 #undef EXPBIAS
2977 tor_assert(key_out_len <= DIGEST_LEN);
2979 d = crypto_new_digest_env();
2980 tmplen = 8+secret_len;
2981 tmp = tor_malloc(tmplen);
2982 memcpy(tmp,s2k_specifier,8);
2983 memcpy(tmp+8,secret,secret_len);
2984 secret_len += 8;
2985 while (count) {
2986 if (count >= secret_len) {
2987 crypto_digest_add_bytes(d, tmp, secret_len);
2988 count -= secret_len;
2989 } else {
2990 crypto_digest_add_bytes(d, tmp, count);
2991 count = 0;
2994 crypto_digest_get_digest(d, key_out, key_out_len);
2995 memset(tmp, 0, tmplen);
2996 tor_free(tmp);
2997 crypto_free_digest_env(d);
3000 #ifdef TOR_IS_MULTITHREADED
3001 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3002 static void
3003 _openssl_locking_cb(int mode, int n, const char *file, int line)
3005 (void)file;
3006 (void)line;
3007 if (!_openssl_mutexes)
3008 /* This is not a really good fix for the
3009 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3010 * it can't hurt. */
3011 return;
3012 if (mode & CRYPTO_LOCK)
3013 tor_mutex_acquire(_openssl_mutexes[n]);
3014 else
3015 tor_mutex_release(_openssl_mutexes[n]);
3018 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3019 * as a lock. */
3020 struct CRYPTO_dynlock_value {
3021 tor_mutex_t *lock;
3024 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3025 * documentation in OpenSSL's docs for more info. */
3026 static struct CRYPTO_dynlock_value *
3027 _openssl_dynlock_create_cb(const char *file, int line)
3029 struct CRYPTO_dynlock_value *v;
3030 (void)file;
3031 (void)line;
3032 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
3033 v->lock = tor_mutex_new();
3034 return v;
3037 /** OpenSSL callback function to acquire or release a lock: see
3038 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3039 static void
3040 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
3041 const char *file, int line)
3043 (void)file;
3044 (void)line;
3045 if (mode & CRYPTO_LOCK)
3046 tor_mutex_acquire(v->lock);
3047 else
3048 tor_mutex_release(v->lock);
3051 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3052 * documentation in OpenSSL's docs for more info. */
3053 static void
3054 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
3055 const char *file, int line)
3057 (void)file;
3058 (void)line;
3059 tor_mutex_free(v->lock);
3060 tor_free(v);
3063 /** @{ */
3064 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3065 * multithreaded. */
3066 static int
3067 setup_openssl_threading(void)
3069 int i;
3070 int n = CRYPTO_num_locks();
3071 _n_openssl_mutexes = n;
3072 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
3073 for (i=0; i < n; ++i)
3074 _openssl_mutexes[i] = tor_mutex_new();
3075 CRYPTO_set_locking_callback(_openssl_locking_cb);
3076 CRYPTO_set_id_callback(tor_get_thread_id);
3077 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
3078 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
3079 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
3080 return 0;
3082 #else
3083 static int
3084 setup_openssl_threading(void)
3086 return 0;
3088 #endif
3090 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
3093 crypto_global_cleanup(void)
3095 EVP_cleanup();
3096 ERR_remove_state(0);
3097 ERR_free_strings();
3099 if (dh_param_p)
3100 BN_free(dh_param_p);
3101 if (dh_param_p_tls)
3102 BN_free(dh_param_p_tls);
3103 if (dh_param_g)
3104 BN_free(dh_param_g);
3106 #ifndef DISABLE_ENGINES
3107 ENGINE_cleanup();
3108 #endif
3110 CONF_modules_unload(1);
3111 CRYPTO_cleanup_all_ex_data();
3112 #ifdef TOR_IS_MULTITHREADED
3113 if (_n_openssl_mutexes) {
3114 int n = _n_openssl_mutexes;
3115 tor_mutex_t **ms = _openssl_mutexes;
3116 int i;
3117 _openssl_mutexes = NULL;
3118 _n_openssl_mutexes = 0;
3119 for (i=0;i<n;++i) {
3120 tor_mutex_free(ms[i]);
3122 tor_free(ms);
3124 #endif
3125 return 0;
3128 /** @} */