Make the DH parameter we use for TLS match the one from Apache's mod_ssl
[tor/rransom.git] / src / common / crypto.c
blob5264fd808544259af5e69cad302211d7a6bbb52c
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 #define WIN32_WINNT 0x400
17 #define _WIN32_WINNT 0x400
18 #define WIN32_LEAN_AND_MEAN
19 #include <windows.h>
20 #include <wincrypt.h>
21 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
22 * use either definition. */
23 #undef OCSP_RESPONSE
24 #endif
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/engine.h>
31 #include <openssl/rand.h>
32 #include <openssl/opensslv.h>
33 #include <openssl/bn.h>
34 #include <openssl/dh.h>
35 #include <openssl/conf.h>
36 #include <openssl/hmac.h>
38 #ifdef HAVE_CTYPE_H
39 #include <ctype.h>
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 #ifdef HAVE_SYS_FCNTL_H
48 #include <sys/fcntl.h>
49 #endif
51 #define CRYPTO_PRIVATE
52 #include "crypto.h"
53 #include "../common/torlog.h"
54 #include "aes.h"
55 #include "../common/util.h"
56 #include "container.h"
57 #include "compat.h"
59 #if OPENSSL_VERSION_NUMBER < 0x00907000l
60 #error "We require OpenSSL >= 0.9.7"
61 #endif
63 #include <openssl/engine.h>
65 #ifdef ANDROID
66 /* Android's OpenSSL seems to have removed all of its Engine support. */
67 #define DISABLE_ENGINES
68 #endif
70 #if OPENSSL_VERSION_NUMBER < 0x00908000l
71 /* On OpenSSL versions before 0.9.8, there is no working SHA256
72 * implementation, so we use Tom St Denis's nice speedy one, slightly adapted
73 * to our needs */
74 #define SHA256_CTX sha256_state
75 #define SHA256_Init sha256_init
76 #define SHA256_Update sha256_process
77 #define LTC_ARGCHK(x) tor_assert(x)
78 #include "sha256.c"
79 #define SHA256_Final(a,b) sha256_done(b,a)
81 static unsigned char *
82 SHA256(const unsigned char *m, size_t len, unsigned char *d)
84 SHA256_CTX ctx;
85 SHA256_Init(&ctx);
86 SHA256_Update(&ctx, m, len);
87 SHA256_Final(d, &ctx);
88 return d;
90 #endif
92 /** Macro: is k a valid RSA public or private key? */
93 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
94 /** Macro: is k a valid RSA private key? */
95 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
97 #ifdef TOR_IS_MULTITHREADED
98 /** A number of preallocated mutexes for use by OpenSSL. */
99 static tor_mutex_t **_openssl_mutexes = NULL;
100 /** How many mutexes have we allocated for use by OpenSSL? */
101 static int _n_openssl_mutexes = 0;
102 #endif
104 /** A public key, or a public/private key-pair. */
105 struct crypto_pk_env_t
107 int refs; /* reference counting so we don't have to copy keys */
108 RSA *key;
111 /** Key and stream information for a stream cipher. */
112 struct crypto_cipher_env_t
114 char key[CIPHER_KEY_LEN];
115 aes_cnt_cipher_t *cipher;
118 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
119 * while we're waiting for the second.*/
120 struct crypto_dh_env_t {
121 DH *dh;
124 static int setup_openssl_threading(void);
125 static int tor_check_dh_key(int severity, BIGNUM *bn);
127 /** Return the number of bytes added by padding method <b>padding</b>.
129 static INLINE int
130 crypto_get_rsa_padding_overhead(int padding)
132 switch (padding)
134 case RSA_NO_PADDING: return 0;
135 case RSA_PKCS1_OAEP_PADDING: return 42;
136 case RSA_PKCS1_PADDING: return 11;
137 default: tor_assert(0); return -1;
141 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
143 static INLINE int
144 crypto_get_rsa_padding(int padding)
146 switch (padding)
148 case PK_NO_PADDING: return RSA_NO_PADDING;
149 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
150 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
151 default: tor_assert(0); return -1;
155 /** Boolean: has OpenSSL's crypto been initialized? */
156 static int _crypto_global_initialized = 0;
158 /** Log all pending crypto errors at level <b>severity</b>. Use
159 * <b>doing</b> to describe our current activities.
161 static void
162 crypto_log_errors(int severity, const char *doing)
164 unsigned long err;
165 const char *msg, *lib, *func;
166 while ((err = ERR_get_error()) != 0) {
167 msg = (const char*)ERR_reason_error_string(err);
168 lib = (const char*)ERR_lib_error_string(err);
169 func = (const char*)ERR_func_error_string(err);
170 if (!msg) msg = "(null)";
171 if (!lib) lib = "(null)";
172 if (!func) func = "(null)";
173 if (doing) {
174 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
175 doing, msg, lib, func);
176 } else {
177 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
182 #ifndef DISABLE_ENGINES
183 /** Log any OpenSSL engines we're using at NOTICE. */
184 static void
185 log_engine(const char *fn, ENGINE *e)
187 if (e) {
188 const char *name, *id;
189 name = ENGINE_get_name(e);
190 id = ENGINE_get_id(e);
191 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
192 name?name:"?", id?id:"?", fn);
193 } else {
194 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
197 #endif
199 #ifndef DISABLE_ENGINES
200 /** Try to load an engine in a shared library via fully qualified path.
202 static ENGINE *
203 try_load_engine(const char *path, const char *engine)
205 ENGINE *e = ENGINE_by_id("dynamic");
206 if (e) {
207 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
208 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
209 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
210 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
211 ENGINE_free(e);
212 e = NULL;
215 return e;
217 #endif
219 /** Initialize the crypto library. Return 0 on success, -1 on failure.
222 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
224 if (!_crypto_global_initialized) {
225 ERR_load_crypto_strings();
226 OpenSSL_add_all_algorithms();
227 _crypto_global_initialized = 1;
228 setup_openssl_threading();
229 if (useAccel > 0) {
230 #ifdef DISABLE_ENGINES
231 (void)accelName;
232 (void)accelDir;
233 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
234 #else
235 ENGINE *e = NULL;
237 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
238 ENGINE_load_builtin_engines();
239 ENGINE_register_all_complete();
241 if (accelName) {
242 if (accelDir) {
243 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
244 " via path \"%s\".", accelName, accelDir);
245 e = try_load_engine(accelName, accelDir);
246 } else {
247 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
248 " acceleration support.", accelName);
249 e = ENGINE_by_id(accelName);
251 if (!e) {
252 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
253 accelName);
254 } else {
255 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
256 accelName);
259 if (e) {
260 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
261 " setting default ciphers.");
262 ENGINE_set_default(e, ENGINE_METHOD_ALL);
264 log_engine("RSA", ENGINE_get_default_RSA());
265 log_engine("DH", ENGINE_get_default_DH());
266 log_engine("RAND", ENGINE_get_default_RAND());
267 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
268 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
269 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
270 #endif
271 } else {
272 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
274 return crypto_seed_rng(1);
276 return 0;
279 /** Free crypto resources held by this thread. */
280 void
281 crypto_thread_cleanup(void)
283 ERR_remove_state(0);
286 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
289 crypto_global_cleanup(void)
291 EVP_cleanup();
292 ERR_remove_state(0);
293 ERR_free_strings();
295 #ifndef DISABLE_ENGINES
296 ENGINE_cleanup();
297 #endif
299 CONF_modules_unload(1);
300 CRYPTO_cleanup_all_ex_data();
301 #ifdef TOR_IS_MULTITHREADED
302 if (_n_openssl_mutexes) {
303 int n = _n_openssl_mutexes;
304 tor_mutex_t **ms = _openssl_mutexes;
305 int i;
306 _openssl_mutexes = NULL;
307 _n_openssl_mutexes = 0;
308 for (i=0;i<n;++i) {
309 tor_mutex_free(ms[i]);
311 tor_free(ms);
313 #endif
314 return 0;
317 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
318 crypto_pk_env_t *
319 _crypto_new_pk_env_rsa(RSA *rsa)
321 crypto_pk_env_t *env;
322 tor_assert(rsa);
323 env = tor_malloc(sizeof(crypto_pk_env_t));
324 env->refs = 1;
325 env->key = rsa;
326 return env;
329 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
330 * returns NULL if this isn't an RSA key. */
331 crypto_pk_env_t *
332 _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
334 RSA *rsa;
335 if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
336 return NULL;
337 return _crypto_new_pk_env_rsa(rsa);
340 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
341 * crypto_pk_env_t. */
342 RSA *
343 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
345 return env->key;
348 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
349 * private is set, include the private-key portion of the key. */
350 EVP_PKEY *
351 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
353 RSA *key = NULL;
354 EVP_PKEY *pkey = NULL;
355 tor_assert(env->key);
356 if (private) {
357 if (!(key = RSAPrivateKey_dup(env->key)))
358 goto error;
359 } else {
360 if (!(key = RSAPublicKey_dup(env->key)))
361 goto error;
363 if (!(pkey = EVP_PKEY_new()))
364 goto error;
365 if (!(EVP_PKEY_assign_RSA(pkey, key)))
366 goto error;
367 return pkey;
368 error:
369 if (pkey)
370 EVP_PKEY_free(pkey);
371 if (key)
372 RSA_free(key);
373 return NULL;
376 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
378 DH *
379 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
381 return dh->dh;
384 /** Allocate and return storage for a public key. The key itself will not yet
385 * be set.
387 crypto_pk_env_t *
388 crypto_new_pk_env(void)
390 RSA *rsa;
392 rsa = RSA_new();
393 if (!rsa) return NULL;
394 return _crypto_new_pk_env_rsa(rsa);
397 /** Release a reference to an asymmetric key; when all the references
398 * are released, free the key.
400 void
401 crypto_free_pk_env(crypto_pk_env_t *env)
403 if (!env)
404 return;
406 if (--env->refs > 0)
407 return;
408 tor_assert(env->refs == 0);
410 if (env->key)
411 RSA_free(env->key);
413 tor_free(env);
416 /** Create a new symmetric cipher for a given key and encryption flag
417 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
418 * on failure.
420 crypto_cipher_env_t *
421 crypto_create_init_cipher(const char *key, int encrypt_mode)
423 int r;
424 crypto_cipher_env_t *crypto = NULL;
426 if (! (crypto = crypto_new_cipher_env())) {
427 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
428 return NULL;
431 crypto_cipher_set_key(crypto, key);
433 if (encrypt_mode)
434 r = crypto_cipher_encrypt_init_cipher(crypto);
435 else
436 r = crypto_cipher_decrypt_init_cipher(crypto);
438 if (r)
439 goto error;
440 return crypto;
442 error:
443 if (crypto)
444 crypto_free_cipher_env(crypto);
445 return NULL;
448 /** Allocate and return a new symmetric cipher.
450 crypto_cipher_env_t *
451 crypto_new_cipher_env(void)
453 crypto_cipher_env_t *env;
455 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
456 env->cipher = aes_new_cipher();
457 return env;
460 /** Free a symmetric cipher.
462 void
463 crypto_free_cipher_env(crypto_cipher_env_t *env)
465 if (!env)
466 return;
468 tor_assert(env->cipher);
469 aes_free_cipher(env->cipher);
470 memset(env, 0, sizeof(crypto_cipher_env_t));
471 tor_free(env);
474 /* public key crypto */
476 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
477 * Return 0 on success, -1 on failure.
480 crypto_pk_generate_key_with_bits(crypto_pk_env_t *env, int bits)
482 tor_assert(env);
484 if (env->key)
485 RSA_free(env->key);
486 #if OPENSSL_VERSION_NUMBER < 0x00908000l
487 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
488 env->key = RSA_generate_key(bits, 65537, NULL, NULL);
489 #else
490 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
492 BIGNUM *e = BN_new();
493 RSA *r = NULL;
494 if (!e)
495 goto done;
496 if (! BN_set_word(e, 65537))
497 goto done;
498 r = RSA_new();
499 if (!r)
500 goto done;
501 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
502 goto done;
504 env->key = r;
505 r = NULL;
506 done:
507 if (e)
508 BN_free(e);
509 if (r)
510 RSA_free(r);
512 #endif
513 if (!env->key) {
514 crypto_log_errors(LOG_WARN, "generating RSA key");
515 return -1;
518 return 0;
521 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
522 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
523 * the string is nul-terminated.
525 /* Used here, and used for testing. */
527 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
528 const char *s, ssize_t len)
530 BIO *b;
532 tor_assert(env);
533 tor_assert(s);
534 tor_assert(len < INT_MAX && len < SIZE_T_CEILING);
536 /* Create a read-only memory BIO, backed by the string 's' */
537 b = BIO_new_mem_buf((char*)s, (int)len);
539 if (env->key)
540 RSA_free(env->key);
542 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
544 BIO_free(b);
546 if (!env->key) {
547 crypto_log_errors(LOG_WARN, "Error parsing private key");
548 return -1;
550 return 0;
553 /** Read a PEM-encoded private key from the file named by
554 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
557 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
558 const char *keyfile)
560 char *contents;
561 int r;
563 /* Read the file into a string. */
564 contents = read_file_to_str(keyfile, 0, NULL);
565 if (!contents) {
566 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
567 return -1;
570 /* Try to parse it. */
571 r = crypto_pk_read_private_key_from_string(env, contents, -1);
572 memset(contents, 0, strlen(contents));
573 tor_free(contents);
574 if (r)
575 return -1; /* read_private_key_from_string already warned, so we don't.*/
577 /* Make sure it's valid. */
578 if (crypto_pk_check_key(env) <= 0)
579 return -1;
581 return 0;
584 /** Helper function to implement crypto_pk_write_*_key_to_string. */
585 static int
586 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
587 size_t *len, int is_public)
589 BUF_MEM *buf;
590 BIO *b;
591 int r;
593 tor_assert(env);
594 tor_assert(env->key);
595 tor_assert(dest);
597 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
599 /* Now you can treat b as if it were a file. Just use the
600 * PEM_*_bio_* functions instead of the non-bio variants.
602 if (is_public)
603 r = PEM_write_bio_RSAPublicKey(b, env->key);
604 else
605 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
607 if (!r) {
608 crypto_log_errors(LOG_WARN, "writing RSA key to string");
609 BIO_free(b);
610 return -1;
613 BIO_get_mem_ptr(b, &buf);
614 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
615 BIO_free(b);
617 *dest = tor_malloc(buf->length+1);
618 memcpy(*dest, buf->data, buf->length);
619 (*dest)[buf->length] = 0; /* nul terminate it */
620 *len = buf->length;
621 BUF_MEM_free(buf);
623 return 0;
626 /** PEM-encode the public key portion of <b>env</b> and write it to a
627 * newly allocated string. On success, set *<b>dest</b> to the new
628 * string, *<b>len</b> to the string's length, and return 0. On
629 * failure, return -1.
632 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
633 size_t *len)
635 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
638 /** PEM-encode the private key portion of <b>env</b> and write it to a
639 * newly allocated string. On success, set *<b>dest</b> to the new
640 * string, *<b>len</b> to the string's length, and return 0. On
641 * failure, return -1.
644 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
645 size_t *len)
647 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
650 /** Read a PEM-encoded public key from the first <b>len</b> characters of
651 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
652 * failure.
655 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
656 size_t len)
658 BIO *b;
660 tor_assert(env);
661 tor_assert(src);
662 tor_assert(len<INT_MAX);
664 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
666 BIO_write(b, src, (int)len);
668 if (env->key)
669 RSA_free(env->key);
670 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
671 BIO_free(b);
672 if (!env->key) {
673 crypto_log_errors(LOG_WARN, "reading public key from string");
674 return -1;
677 return 0;
680 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
681 * PEM-encoded. Return 0 on success, -1 on failure.
684 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
685 const char *fname)
687 BIO *bio;
688 char *cp;
689 long len;
690 char *s;
691 int r;
693 tor_assert(PRIVATE_KEY_OK(env));
695 if (!(bio = BIO_new(BIO_s_mem())))
696 return -1;
697 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
698 == 0) {
699 crypto_log_errors(LOG_WARN, "writing private key");
700 BIO_free(bio);
701 return -1;
703 len = BIO_get_mem_data(bio, &cp);
704 tor_assert(len >= 0);
705 s = tor_malloc(len+1);
706 memcpy(s, cp, len);
707 s[len]='\0';
708 r = write_str_to_file(fname, s, 0);
709 BIO_free(bio);
710 memset(s, 0, strlen(s));
711 tor_free(s);
712 return r;
715 /** Return true iff <b>env</b> has a valid key.
718 crypto_pk_check_key(crypto_pk_env_t *env)
720 int r;
721 tor_assert(env);
723 r = RSA_check_key(env->key);
724 if (r <= 0)
725 crypto_log_errors(LOG_WARN,"checking RSA key");
726 return r;
729 /** Return true iff <b>key</b> contains the private-key portion of the RSA
730 * key. */
732 crypto_pk_key_is_private(const crypto_pk_env_t *key)
734 tor_assert(key);
735 return PRIVATE_KEY_OK(key);
738 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
739 * if a==b, and 1 if a\>b.
742 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
744 int result;
746 if (!a || !b)
747 return -1;
749 if (!a->key || !b->key)
750 return -1;
752 tor_assert(PUBLIC_KEY_OK(a));
753 tor_assert(PUBLIC_KEY_OK(b));
754 result = BN_cmp((a->key)->n, (b->key)->n);
755 if (result)
756 return result;
757 return BN_cmp((a->key)->e, (b->key)->e);
760 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
761 size_t
762 crypto_pk_keysize(crypto_pk_env_t *env)
764 tor_assert(env);
765 tor_assert(env->key);
767 return (size_t) RSA_size(env->key);
770 /** Increase the reference count of <b>env</b>, and return it.
772 crypto_pk_env_t *
773 crypto_pk_dup_key(crypto_pk_env_t *env)
775 tor_assert(env);
776 tor_assert(env->key);
778 env->refs++;
779 return env;
782 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
783 crypto_pk_env_t *
784 crypto_pk_copy_full(crypto_pk_env_t *env)
786 RSA *new_key;
787 int privatekey = 0;
788 tor_assert(env);
789 tor_assert(env->key);
791 if (PRIVATE_KEY_OK(env)) {
792 new_key = RSAPrivateKey_dup(env->key);
793 privatekey = 1;
794 } else {
795 new_key = RSAPublicKey_dup(env->key);
797 if (!new_key) {
798 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
799 privatekey?"private":"public");
800 crypto_log_errors(LOG_ERR,
801 privatekey ? "Duplicating a private key" :
802 "Duplicating a public key");
803 tor_fragile_assert();
804 return NULL;
807 return _crypto_new_pk_env_rsa(new_key);
810 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
811 * in <b>env</b>, using the padding method <b>padding</b>. On success,
812 * write the result to <b>to</b>, and return the number of bytes
813 * written. On failure, return -1.
815 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
816 * at least the length of the modulus of <b>env</b>.
819 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to, size_t tolen,
820 const char *from, size_t fromlen, int padding)
822 int r;
823 tor_assert(env);
824 tor_assert(from);
825 tor_assert(to);
826 tor_assert(fromlen<INT_MAX);
827 tor_assert(tolen >= crypto_pk_keysize(env));
829 r = RSA_public_encrypt((int)fromlen,
830 (unsigned char*)from, (unsigned char*)to,
831 env->key, crypto_get_rsa_padding(padding));
832 if (r<0) {
833 crypto_log_errors(LOG_WARN, "performing RSA encryption");
834 return -1;
836 return r;
839 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
840 * in <b>env</b>, using the padding method <b>padding</b>. On success,
841 * write the result to <b>to</b>, and return the number of bytes
842 * written. On failure, return -1.
844 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
845 * at least the length of the modulus of <b>env</b>.
848 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
849 size_t tolen,
850 const char *from, size_t fromlen,
851 int padding, int warnOnFailure)
853 int r;
854 tor_assert(env);
855 tor_assert(from);
856 tor_assert(to);
857 tor_assert(env->key);
858 tor_assert(fromlen<INT_MAX);
859 tor_assert(tolen >= crypto_pk_keysize(env));
860 if (!env->key->p)
861 /* Not a private key */
862 return -1;
864 r = RSA_private_decrypt((int)fromlen,
865 (unsigned char*)from, (unsigned char*)to,
866 env->key, crypto_get_rsa_padding(padding));
868 if (r<0) {
869 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
870 "performing RSA decryption");
871 return -1;
873 return r;
876 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
877 * public key in <b>env</b>, using PKCS1 padding. On success, write the
878 * signed data to <b>to</b>, and return the number of bytes written.
879 * On failure, return -1.
881 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
882 * at least the length of the modulus of <b>env</b>.
885 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
886 size_t tolen,
887 const char *from, size_t fromlen)
889 int r;
890 tor_assert(env);
891 tor_assert(from);
892 tor_assert(to);
893 tor_assert(fromlen < INT_MAX);
894 tor_assert(tolen >= crypto_pk_keysize(env));
895 r = RSA_public_decrypt((int)fromlen,
896 (unsigned char*)from, (unsigned char*)to,
897 env->key, RSA_PKCS1_PADDING);
899 if (r<0) {
900 crypto_log_errors(LOG_WARN, "checking RSA signature");
901 return -1;
903 return r;
906 /** Check a siglen-byte long signature at <b>sig</b> against
907 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
908 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
909 * SHA1(data). Else return -1.
912 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
913 size_t datalen, const char *sig, size_t siglen)
915 char digest[DIGEST_LEN];
916 char *buf;
917 size_t buflen;
918 int r;
920 tor_assert(env);
921 tor_assert(data);
922 tor_assert(sig);
923 tor_assert(datalen < SIZE_T_CEILING);
924 tor_assert(siglen < SIZE_T_CEILING);
926 if (crypto_digest(digest,data,datalen)<0) {
927 log_warn(LD_BUG, "couldn't compute digest");
928 return -1;
930 buflen = crypto_pk_keysize(env)+1;
931 buf = tor_malloc(buflen);
932 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
933 if (r != DIGEST_LEN) {
934 log_warn(LD_CRYPTO, "Invalid signature");
935 tor_free(buf);
936 return -1;
938 if (memcmp(buf, digest, DIGEST_LEN)) {
939 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
940 tor_free(buf);
941 return -1;
943 tor_free(buf);
945 return 0;
948 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
949 * <b>env</b>, using PKCS1 padding. On success, write the signature to
950 * <b>to</b>, and return the number of bytes written. On failure, return
951 * -1.
953 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
954 * at least the length of the modulus of <b>env</b>.
957 crypto_pk_private_sign(crypto_pk_env_t *env, char *to, size_t tolen,
958 const char *from, size_t fromlen)
960 int r;
961 tor_assert(env);
962 tor_assert(from);
963 tor_assert(to);
964 tor_assert(fromlen < INT_MAX);
965 tor_assert(tolen >= crypto_pk_keysize(env));
966 if (!env->key->p)
967 /* Not a private key */
968 return -1;
970 r = RSA_private_encrypt((int)fromlen,
971 (unsigned char*)from, (unsigned char*)to,
972 env->key, RSA_PKCS1_PADDING);
973 if (r<0) {
974 crypto_log_errors(LOG_WARN, "generating RSA signature");
975 return -1;
977 return r;
980 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
981 * <b>from</b>; sign the data with the private key in <b>env</b>, and
982 * store it in <b>to</b>. Return the number of bytes written on
983 * success, and -1 on failure.
985 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
986 * at least the length of the modulus of <b>env</b>.
989 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to, size_t tolen,
990 const char *from, size_t fromlen)
992 int r;
993 char digest[DIGEST_LEN];
994 if (crypto_digest(digest,from,fromlen)<0)
995 return -1;
996 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
997 memset(digest, 0, sizeof(digest));
998 return r;
1001 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1002 * bytes of data from <b>from</b>, with padding type 'padding',
1003 * storing the results on <b>to</b>.
1005 * If no padding is used, the public key must be at least as large as
1006 * <b>from</b>.
1008 * Returns the number of bytes written on success, -1 on failure.
1010 * The encrypted data consists of:
1011 * - The source data, padded and encrypted with the public key, if the
1012 * padded source data is no longer than the public key, and <b>force</b>
1013 * is false, OR
1014 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1015 * padded and encrypted with the public key; followed by the rest of
1016 * the source data encrypted in AES-CTR mode with the symmetric key.
1019 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
1020 char *to, size_t tolen,
1021 const char *from,
1022 size_t fromlen,
1023 int padding, int force)
1025 int overhead, outlen, r;
1026 size_t pkeylen, symlen;
1027 crypto_cipher_env_t *cipher = NULL;
1028 char *buf = NULL;
1030 tor_assert(env);
1031 tor_assert(from);
1032 tor_assert(to);
1033 tor_assert(fromlen < SIZE_T_CEILING);
1035 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1036 pkeylen = crypto_pk_keysize(env);
1038 if (padding == PK_NO_PADDING && fromlen < pkeylen)
1039 return -1;
1041 if (!force && fromlen+overhead <= pkeylen) {
1042 /* It all fits in a single encrypt. */
1043 return crypto_pk_public_encrypt(env,to,
1044 tolen,
1045 from,fromlen,padding);
1047 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1048 tor_assert(tolen >= pkeylen);
1050 cipher = crypto_new_cipher_env();
1051 if (!cipher) return -1;
1052 if (crypto_cipher_generate_key(cipher)<0)
1053 goto err;
1054 /* You can't just run around RSA-encrypting any bitstream: if it's
1055 * greater than the RSA key, then OpenSSL will happily encrypt, and
1056 * later decrypt to the wrong value. So we set the first bit of
1057 * 'cipher->key' to 0 if we aren't padding. This means that our
1058 * symmetric key is really only 127 bits.
1060 if (padding == PK_NO_PADDING)
1061 cipher->key[0] &= 0x7f;
1062 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
1063 goto err;
1064 buf = tor_malloc(pkeylen+1);
1065 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1066 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1068 /* Length of symmetrically encrypted data. */
1069 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1071 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1072 if (outlen!=(int)pkeylen) {
1073 goto err;
1075 r = crypto_cipher_encrypt(cipher, to+outlen,
1076 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1078 if (r<0) goto err;
1079 memset(buf, 0, pkeylen);
1080 tor_free(buf);
1081 crypto_free_cipher_env(cipher);
1082 tor_assert(outlen+symlen < INT_MAX);
1083 return (int)(outlen + symlen);
1084 err:
1085 if (buf) {
1086 memset(buf, 0, pkeylen);
1087 tor_free(buf);
1089 if (cipher) crypto_free_cipher_env(cipher);
1090 return -1;
1093 /** Invert crypto_pk_public_hybrid_encrypt. */
1095 crypto_pk_private_hybrid_decrypt(crypto_pk_env_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_env_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+1);
1116 outlen = crypto_pk_private_decrypt(env,buf,pkeylen+1,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_create_init_cipher(buf, 0);
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 memset(buf,0,pkeylen);
1139 tor_free(buf);
1140 crypto_free_cipher_env(cipher);
1141 tor_assert(outlen + fromlen < INT_MAX);
1142 return (int)(outlen + (fromlen-pkeylen));
1143 err:
1144 memset(buf,0,pkeylen);
1145 tor_free(buf);
1146 if (cipher) crypto_free_cipher_env(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_env_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_env_t *
1180 crypto_pk_asn1_decode(const char *str, size_t len)
1182 RSA *rsa;
1183 unsigned char *buf;
1184 /* This ifdef suppresses a type warning. Take out the first case once
1185 * everybody is using OpenSSL 0.9.7 or later.
1187 const unsigned char *cp;
1188 cp = buf = tor_malloc(len);
1189 memcpy(buf,str,len);
1190 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1191 tor_free(buf);
1192 if (!rsa) {
1193 crypto_log_errors(LOG_WARN,"decoding public key");
1194 return NULL;
1196 return _crypto_new_pk_env_rsa(rsa);
1199 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1200 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1201 * Return 0 on success, -1 on failure.
1204 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1206 unsigned char *buf, *bufp;
1207 int len;
1209 len = i2d_RSAPublicKey(pk->key, NULL);
1210 if (len < 0)
1211 return -1;
1212 buf = bufp = tor_malloc(len+1);
1213 len = i2d_RSAPublicKey(pk->key, &bufp);
1214 if (len < 0) {
1215 crypto_log_errors(LOG_WARN,"encoding public key");
1216 tor_free(buf);
1217 return -1;
1219 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1220 tor_free(buf);
1221 return -1;
1223 tor_free(buf);
1224 return 0;
1227 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1228 * every four spaces. */
1229 /* static */ void
1230 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1232 int n = 0;
1233 char *end = out+outlen;
1234 tor_assert(outlen < SIZE_T_CEILING);
1236 while (*in && out<end) {
1237 *out++ = *in++;
1238 if (++n == 4 && *in && out<end) {
1239 n = 0;
1240 *out++ = ' ';
1243 tor_assert(out<end);
1244 *out = '\0';
1247 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1248 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1249 * space). Return 0 on success, -1 on failure.
1251 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1252 * of the public key, converted to hexadecimal, in upper case, with a
1253 * space after every four digits.
1255 * If <b>add_space</b> is false, omit the spaces.
1258 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1260 char digest[DIGEST_LEN];
1261 char hexdigest[HEX_DIGEST_LEN+1];
1262 if (crypto_pk_get_digest(pk, digest)) {
1263 return -1;
1265 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1266 if (add_space) {
1267 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1268 } else {
1269 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1271 return 0;
1274 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1277 crypto_pk_check_fingerprint_syntax(const char *s)
1279 int i;
1280 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1281 if ((i%5) == 4) {
1282 if (!TOR_ISSPACE(s[i])) return 0;
1283 } else {
1284 if (!TOR_ISXDIGIT(s[i])) return 0;
1287 if (s[FINGERPRINT_LEN]) return 0;
1288 return 1;
1291 /* symmetric crypto */
1293 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1294 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1297 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1299 tor_assert(env);
1301 return crypto_rand(env->key, CIPHER_KEY_LEN);
1304 /** Set the symmetric key for the cipher in <b>env</b> to the first
1305 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1307 void
1308 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1310 tor_assert(env);
1311 tor_assert(key);
1313 memcpy(env->key, key, CIPHER_KEY_LEN);
1316 /** Generate an initialization vector for our AES-CTR cipher; store it
1317 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1318 void
1319 crypto_cipher_generate_iv(char *iv_out)
1321 crypto_rand(iv_out, CIPHER_IV_LEN);
1324 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1325 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1326 * <b>iv</b>. */
1328 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1330 tor_assert(env);
1331 tor_assert(iv);
1332 aes_set_iv(env->cipher, iv);
1333 return 0;
1336 /** Return a pointer to the key set for the cipher in <b>env</b>.
1338 const char *
1339 crypto_cipher_get_key(crypto_cipher_env_t *env)
1341 return env->key;
1344 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1345 * success, -1 on failure.
1348 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1350 tor_assert(env);
1352 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1353 return 0;
1356 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1357 * success, -1 on failure.
1360 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1362 tor_assert(env);
1364 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1365 return 0;
1368 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1369 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1370 * On failure, return -1.
1373 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1374 const char *from, size_t fromlen)
1376 tor_assert(env);
1377 tor_assert(env->cipher);
1378 tor_assert(from);
1379 tor_assert(fromlen);
1380 tor_assert(to);
1381 tor_assert(fromlen < SIZE_T_CEILING);
1383 aes_crypt(env->cipher, from, fromlen, to);
1384 return 0;
1387 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1388 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1389 * On failure, return -1.
1392 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1393 const char *from, size_t fromlen)
1395 tor_assert(env);
1396 tor_assert(from);
1397 tor_assert(to);
1398 tor_assert(fromlen < SIZE_T_CEILING);
1400 aes_crypt(env->cipher, from, fromlen, to);
1401 return 0;
1404 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1405 * on success, return 0. On failure, return -1.
1408 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1410 tor_assert(len < SIZE_T_CEILING);
1411 aes_crypt_inplace(env->cipher, buf, len);
1412 return 0;
1415 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1416 * <b>cipher</b> to the buffer in <b>to</b> of length
1417 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1418 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1419 * number of bytes written, on failure, return -1.
1421 * This function adjusts the current position of the counter in <b>cipher</b>
1422 * to immediately after the encrypted data.
1425 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1426 char *to, size_t tolen,
1427 const char *from, size_t fromlen)
1429 tor_assert(cipher);
1430 tor_assert(from);
1431 tor_assert(to);
1432 tor_assert(fromlen < INT_MAX);
1434 if (fromlen < 1)
1435 return -1;
1436 if (tolen < fromlen + CIPHER_IV_LEN)
1437 return -1;
1439 crypto_cipher_generate_iv(to);
1440 if (crypto_cipher_set_iv(cipher, to)<0)
1441 return -1;
1442 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1443 return (int)(fromlen + CIPHER_IV_LEN);
1446 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1447 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1448 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1449 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1450 * number of bytes written, on failure, return -1.
1452 * This function adjusts the current position of the counter in <b>cipher</b>
1453 * to immediately after the decrypted data.
1456 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1457 char *to, size_t tolen,
1458 const char *from, size_t fromlen)
1460 tor_assert(cipher);
1461 tor_assert(from);
1462 tor_assert(to);
1463 tor_assert(fromlen < INT_MAX);
1465 if (fromlen <= CIPHER_IV_LEN)
1466 return -1;
1467 if (tolen < fromlen - CIPHER_IV_LEN)
1468 return -1;
1470 if (crypto_cipher_set_iv(cipher, from)<0)
1471 return -1;
1472 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1473 return (int)(fromlen - CIPHER_IV_LEN);
1476 /* SHA-1 */
1478 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1479 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1480 * Return 0 on success, -1 on failure.
1483 crypto_digest(char *digest, const char *m, size_t len)
1485 tor_assert(m);
1486 tor_assert(digest);
1487 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1491 crypto_digest256(char *digest, const char *m, size_t len,
1492 digest_algorithm_t algorithm)
1494 tor_assert(m);
1495 tor_assert(digest);
1496 tor_assert(algorithm == DIGEST_SHA256);
1497 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1500 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1501 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1502 * success, -1 on failure. */
1504 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1506 digest_algorithm_t i;
1507 tor_assert(ds_out);
1508 memset(ds_out, 0, sizeof(*ds_out));
1509 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1510 return -1;
1511 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1512 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1513 return -1;
1515 return 0;
1518 /** Return the name of an algorithm, as used in directory documents. */
1519 const char *
1520 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1522 switch (alg) {
1523 case DIGEST_SHA1:
1524 return "sha1";
1525 case DIGEST_SHA256:
1526 return "sha256";
1527 default:
1528 tor_fragile_assert();
1529 return "??unknown_digest??";
1533 /** Given the name of a digest algorithm, return its integer value, or -1 if
1534 * the name is not recognized. */
1536 crypto_digest_algorithm_parse_name(const char *name)
1538 if (!strcmp(name, "sha1"))
1539 return DIGEST_SHA1;
1540 else if (!strcmp(name, "sha256"))
1541 return DIGEST_SHA256;
1542 else
1543 return -1;
1546 /** Intermediate information about the digest of a stream of data. */
1547 struct crypto_digest_env_t {
1548 union {
1549 SHA_CTX sha1;
1550 SHA256_CTX sha2;
1551 } d;
1552 digest_algorithm_t algorithm : 8;
1555 /** Allocate and return a new digest object.
1557 crypto_digest_env_t *
1558 crypto_new_digest_env(void)
1560 crypto_digest_env_t *r;
1561 r = tor_malloc(sizeof(crypto_digest_env_t));
1562 SHA1_Init(&r->d.sha1);
1563 r->algorithm = DIGEST_SHA1;
1564 return r;
1567 crypto_digest_env_t *
1568 crypto_new_digest256_env(digest_algorithm_t algorithm)
1570 crypto_digest_env_t *r;
1571 tor_assert(algorithm == DIGEST_SHA256);
1572 r = tor_malloc(sizeof(crypto_digest_env_t));
1573 SHA256_Init(&r->d.sha2);
1574 r->algorithm = algorithm;
1575 return r;
1578 /** Deallocate a digest object.
1580 void
1581 crypto_free_digest_env(crypto_digest_env_t *digest)
1583 if (!digest)
1584 return;
1585 memset(digest, 0, sizeof(crypto_digest_env_t));
1586 tor_free(digest);
1589 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1591 void
1592 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1593 size_t len)
1595 tor_assert(digest);
1596 tor_assert(data);
1597 /* Using the SHA*_*() calls directly means we don't support doing
1598 * SHA in hardware. But so far the delay of getting the question
1599 * to the hardware, and hearing the answer, is likely higher than
1600 * just doing it ourselves. Hashes are fast.
1602 switch (digest->algorithm) {
1603 case DIGEST_SHA1:
1604 SHA1_Update(&digest->d.sha1, (void*)data, len);
1605 break;
1606 case DIGEST_SHA256:
1607 SHA256_Update(&digest->d.sha2, (void*)data, len);
1608 break;
1609 default:
1610 tor_fragile_assert();
1611 break;
1615 /** Compute the hash of the data that has been passed to the digest
1616 * object; write the first out_len bytes of the result to <b>out</b>.
1617 * <b>out_len</b> must be \<= DIGEST256_LEN.
1619 void
1620 crypto_digest_get_digest(crypto_digest_env_t *digest,
1621 char *out, size_t out_len)
1623 unsigned char r[DIGEST256_LEN];
1624 crypto_digest_env_t tmpenv;
1625 tor_assert(digest);
1626 tor_assert(out);
1627 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1628 memcpy(&tmpenv, digest, sizeof(crypto_digest_env_t));
1629 switch (digest->algorithm) {
1630 case DIGEST_SHA1:
1631 tor_assert(out_len <= DIGEST_LEN);
1632 SHA1_Final(r, &tmpenv.d.sha1);
1633 break;
1634 case DIGEST_SHA256:
1635 tor_assert(out_len <= DIGEST256_LEN);
1636 SHA256_Final(r, &tmpenv.d.sha2);
1637 break;
1638 default:
1639 tor_fragile_assert();
1640 break;
1642 memcpy(out, r, out_len);
1643 memset(r, 0, sizeof(r));
1646 /** Allocate and return a new digest object with the same state as
1647 * <b>digest</b>
1649 crypto_digest_env_t *
1650 crypto_digest_dup(const crypto_digest_env_t *digest)
1652 crypto_digest_env_t *r;
1653 tor_assert(digest);
1654 r = tor_malloc(sizeof(crypto_digest_env_t));
1655 memcpy(r,digest,sizeof(crypto_digest_env_t));
1656 return r;
1659 /** Replace the state of the digest object <b>into</b> with the state
1660 * of the digest object <b>from</b>.
1662 void
1663 crypto_digest_assign(crypto_digest_env_t *into,
1664 const crypto_digest_env_t *from)
1666 tor_assert(into);
1667 tor_assert(from);
1668 memcpy(into,from,sizeof(crypto_digest_env_t));
1671 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1672 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1673 * in <b>hmac_out</b>.
1675 void
1676 crypto_hmac_sha1(char *hmac_out,
1677 const char *key, size_t key_len,
1678 const char *msg, size_t msg_len)
1680 tor_assert(key_len < INT_MAX);
1681 tor_assert(msg_len < INT_MAX);
1682 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1683 (unsigned char*)hmac_out, NULL);
1686 /* DH */
1688 /** Shared P parameter for our circuit-crypto DH key exchanges. */
1689 static BIGNUM *dh_param_p = NULL;
1690 /** Shared P parameter for our TLS DH key exchanges. */
1691 static BIGNUM *dh_param_p_tls = NULL;
1692 /** Shared G parameter for our DH key exchanges. */
1693 static BIGNUM *dh_param_g = NULL;
1695 /** Initialize dh_param_p and dh_param_g if they are not already
1696 * set. */
1697 static void
1698 init_dh_param(void)
1700 BIGNUM *p, *p2, *g;
1701 int r;
1702 if (dh_param_p && dh_param_g && dh_param_p_tls)
1703 return;
1705 p = BN_new();
1706 p2 = BN_new();
1707 g = BN_new();
1708 tor_assert(p);
1709 tor_assert(p2);
1710 tor_assert(g);
1712 /* This is from rfc2409, section 6.2. It's a safe prime, and
1713 supposedly it equals:
1714 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1716 r = BN_hex2bn(&p,
1717 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1718 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1719 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1720 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1721 "49286651ECE65381FFFFFFFFFFFFFFFF");
1722 tor_assert(r);
1723 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
1724 * modules/ssl/ssl_engine_dh.c */
1725 r = BN_hex2bn(&p2,
1726 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
1727 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
1728 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
1729 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
1730 "B0E7393E0F24218EB3");
1731 tor_assert(r);
1733 r = BN_set_word(g, 2);
1734 tor_assert(r);
1735 dh_param_p = p;
1736 dh_param_p_tls = p2;
1737 dh_param_g = g;
1740 #define DH_PRIVATE_KEY_BITS 320
1742 /** Allocate and return a new DH object for a key exchange.
1744 crypto_dh_env_t *
1745 crypto_dh_new(int dh_type)
1747 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1749 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
1750 dh_type == DH_TYPE_REND);
1752 if (!dh_param_p)
1753 init_dh_param();
1755 if (!(res->dh = DH_new()))
1756 goto err;
1758 if (dh_type == DH_TYPE_TLS) {
1759 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
1760 goto err;
1761 } else {
1762 if (!(res->dh->p = BN_dup(dh_param_p)))
1763 goto err;
1766 if (!(res->dh->g = BN_dup(dh_param_g)))
1767 goto err;
1769 res->dh->length = DH_PRIVATE_KEY_BITS;
1771 return res;
1772 err:
1773 crypto_log_errors(LOG_WARN, "creating DH object");
1774 if (res->dh) DH_free(res->dh); /* frees p and g too */
1775 tor_free(res);
1776 return NULL;
1779 /** Return the length of the DH key in <b>dh</b>, in bytes.
1782 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1784 tor_assert(dh);
1785 return DH_size(dh->dh);
1788 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1789 * success, -1 on failure.
1792 crypto_dh_generate_public(crypto_dh_env_t *dh)
1794 again:
1795 if (!DH_generate_key(dh->dh)) {
1796 crypto_log_errors(LOG_WARN, "generating DH key");
1797 return -1;
1799 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
1800 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1801 "the-universe chances really do happen. Trying again.");
1802 /* Free and clear the keys, so OpenSSL will actually try again. */
1803 BN_free(dh->dh->pub_key);
1804 BN_free(dh->dh->priv_key);
1805 dh->dh->pub_key = dh->dh->priv_key = NULL;
1806 goto again;
1808 return 0;
1811 /** Generate g^x as necessary, and write the g^x for the key exchange
1812 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1813 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1816 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1818 int bytes;
1819 tor_assert(dh);
1820 if (!dh->dh->pub_key) {
1821 if (crypto_dh_generate_public(dh)<0)
1822 return -1;
1825 tor_assert(dh->dh->pub_key);
1826 bytes = BN_num_bytes(dh->dh->pub_key);
1827 tor_assert(bytes >= 0);
1828 if (pubkey_len < (size_t)bytes) {
1829 log_warn(LD_CRYPTO,
1830 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1831 (int) pubkey_len, bytes);
1832 return -1;
1835 memset(pubkey, 0, pubkey_len);
1836 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1838 return 0;
1841 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1842 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1843 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1845 static int
1846 tor_check_dh_key(int severity, BIGNUM *bn)
1848 BIGNUM *x;
1849 char *s;
1850 tor_assert(bn);
1851 x = BN_new();
1852 tor_assert(x);
1853 if (!dh_param_p)
1854 init_dh_param();
1855 BN_set_word(x, 1);
1856 if (BN_cmp(bn,x)<=0) {
1857 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
1858 goto err;
1860 BN_copy(x,dh_param_p);
1861 BN_sub_word(x, 1);
1862 if (BN_cmp(bn,x)>=0) {
1863 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
1864 goto err;
1866 BN_free(x);
1867 return 0;
1868 err:
1869 BN_free(x);
1870 s = BN_bn2hex(bn);
1871 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1872 OPENSSL_free(s);
1873 return -1;
1876 #undef MIN
1877 #define MIN(a,b) ((a)<(b)?(a):(b))
1878 /** Given a DH key exchange object, and our peer's value of g^y (as a
1879 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1880 * <b>secret_bytes_out</b> bytes of shared key material and write them
1881 * to <b>secret_out</b>. Return the number of bytes generated on success,
1882 * or -1 on failure.
1884 * (We generate key material by computing
1885 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1886 * where || is concatenation.)
1888 ssize_t
1889 crypto_dh_compute_secret(int severity, crypto_dh_env_t *dh,
1890 const char *pubkey, size_t pubkey_len,
1891 char *secret_out, size_t secret_bytes_out)
1893 char *secret_tmp = NULL;
1894 BIGNUM *pubkey_bn = NULL;
1895 size_t secret_len=0, secret_tmp_len=0;
1896 int result=0;
1897 tor_assert(dh);
1898 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1899 tor_assert(pubkey_len < INT_MAX);
1901 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1902 (int)pubkey_len, NULL)))
1903 goto error;
1904 if (tor_check_dh_key(severity, pubkey_bn)<0) {
1905 /* Check for invalid public keys. */
1906 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
1907 goto error;
1909 secret_tmp_len = crypto_dh_get_bytes(dh);
1910 secret_tmp = tor_malloc(secret_tmp_len);
1911 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1912 if (result < 0) {
1913 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1914 goto error;
1916 secret_len = result;
1917 if (crypto_expand_key_material(secret_tmp, secret_len,
1918 secret_out, secret_bytes_out)<0)
1919 goto error;
1920 secret_len = secret_bytes_out;
1922 goto done;
1923 error:
1924 result = -1;
1925 done:
1926 crypto_log_errors(LOG_WARN, "completing DH handshake");
1927 if (pubkey_bn)
1928 BN_free(pubkey_bn);
1929 if (secret_tmp) {
1930 memset(secret_tmp, 0, secret_tmp_len);
1931 tor_free(secret_tmp);
1933 if (result < 0)
1934 return result;
1935 else
1936 return secret_len;
1939 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1940 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1941 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1942 * H(K | [00]) | H(K | [01]) | ....
1944 * Return 0 on success, -1 on failure.
1947 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1948 char *key_out, size_t key_out_len)
1950 int i;
1951 char *cp, *tmp = tor_malloc(key_in_len+1);
1952 char digest[DIGEST_LEN];
1954 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1955 tor_assert(key_out_len <= DIGEST_LEN*256);
1957 memcpy(tmp, key_in, key_in_len);
1958 for (cp = key_out, i=0; cp < key_out+key_out_len;
1959 ++i, cp += DIGEST_LEN) {
1960 tmp[key_in_len] = i;
1961 if (crypto_digest(digest, tmp, key_in_len+1))
1962 goto err;
1963 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1965 memset(tmp, 0, key_in_len+1);
1966 tor_free(tmp);
1967 memset(digest, 0, sizeof(digest));
1968 return 0;
1970 err:
1971 memset(tmp, 0, key_in_len+1);
1972 tor_free(tmp);
1973 memset(digest, 0, sizeof(digest));
1974 return -1;
1977 /** Free a DH key exchange object.
1979 void
1980 crypto_dh_free(crypto_dh_env_t *dh)
1982 if (!dh)
1983 return;
1984 tor_assert(dh->dh);
1985 DH_free(dh->dh);
1986 tor_free(dh);
1989 /* random numbers */
1991 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1992 * work for us too. */
1993 #define ADD_ENTROPY 32
1995 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1996 "release".) */
1997 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1999 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
2000 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
2001 * that fd without checking whether it fit in the fd_set. Thus, if the
2002 * system has not just been started up, it is unsafe to call */
2003 #define RAND_POLL_IS_SAFE \
2004 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
2005 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
2006 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
2008 static void
2009 seed_weak_rng(void)
2011 unsigned seed;
2012 crypto_rand((void*)&seed, sizeof(seed));
2013 tor_init_weak_random(seed);
2016 /** Seed OpenSSL's random number generator with bytes from the operating
2017 * system. <b>startup</b> should be true iff we have just started Tor and
2018 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
2021 crypto_seed_rng(int startup)
2023 int rand_poll_status = 0;
2025 /* local variables */
2026 #ifdef MS_WINDOWS
2027 unsigned char buf[ADD_ENTROPY];
2028 static int provider_set = 0;
2029 static HCRYPTPROV provider;
2030 #else
2031 char buf[ADD_ENTROPY];
2032 static const char *filenames[] = {
2033 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2035 int fd, i;
2036 size_t n;
2037 #endif
2039 #if HAVE_RAND_POLL
2040 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
2041 * entropy than we do. We'll try calling that, *and* calling our own entropy
2042 * functions. If one succeeds, we'll accept the RNG as seeded. */
2043 if (startup || RAND_POLL_IS_SAFE) {
2044 rand_poll_status = RAND_poll();
2045 if (rand_poll_status == 0)
2046 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2048 #endif
2050 #ifdef MS_WINDOWS
2051 if (!provider_set) {
2052 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2053 CRYPT_VERIFYCONTEXT)) {
2054 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
2055 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2056 return rand_poll_status ? 0 : -1;
2059 provider_set = 1;
2061 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
2062 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2063 return rand_poll_status ? 0 : -1;
2065 RAND_seed(buf, sizeof(buf));
2066 memset(buf, 0, sizeof(buf));
2067 seed_weak_rng();
2068 return 0;
2069 #else
2070 for (i = 0; filenames[i]; ++i) {
2071 fd = open(filenames[i], O_RDONLY, 0);
2072 if (fd<0) continue;
2073 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
2074 n = read_all(fd, buf, sizeof(buf), 0);
2075 close(fd);
2076 if (n != sizeof(buf)) {
2077 log_warn(LD_CRYPTO,
2078 "Error reading from entropy source (read only %lu bytes).",
2079 (unsigned long)n);
2080 return -1;
2082 RAND_seed(buf, (int)sizeof(buf));
2083 memset(buf, 0, sizeof(buf));
2084 seed_weak_rng();
2085 return 0;
2088 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
2089 return rand_poll_status ? 0 : -1;
2090 #endif
2093 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2094 * success, -1 on failure.
2097 crypto_rand(char *to, size_t n)
2099 int r;
2100 tor_assert(n < INT_MAX);
2101 tor_assert(to);
2102 r = RAND_bytes((unsigned char*)to, (int)n);
2103 if (r == 0)
2104 crypto_log_errors(LOG_WARN, "generating random data");
2105 return (r == 1) ? 0 : -1;
2108 /** Return a pseudorandom integer, chosen uniformly from the values
2109 * between 0 and <b>max</b>-1. */
2111 crypto_rand_int(unsigned int max)
2113 unsigned int val;
2114 unsigned int cutoff;
2115 tor_assert(max < UINT_MAX);
2116 tor_assert(max > 0); /* don't div by 0 */
2118 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2119 * distribution with clipping at the upper end of unsigned int's
2120 * range.
2122 cutoff = UINT_MAX - (UINT_MAX%max);
2123 while (1) {
2124 crypto_rand((char*)&val, sizeof(val));
2125 if (val < cutoff)
2126 return val % max;
2130 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2131 * between 0 and <b>max</b>-1. */
2132 uint64_t
2133 crypto_rand_uint64(uint64_t max)
2135 uint64_t val;
2136 uint64_t cutoff;
2137 tor_assert(max < UINT64_MAX);
2138 tor_assert(max > 0); /* don't div by 0 */
2140 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2141 * distribution with clipping at the upper end of unsigned int's
2142 * range.
2144 cutoff = UINT64_MAX - (UINT64_MAX%max);
2145 while (1) {
2146 crypto_rand((char*)&val, sizeof(val));
2147 if (val < cutoff)
2148 return val % max;
2152 /** Return a pseudorandom double d, chosen uniformly from the range
2153 * 0.0 <= d < 1.0.
2155 double
2156 crypto_rand_double(void)
2158 /* We just use an unsigned int here; we don't really care about getting
2159 * more than 32 bits of resolution */
2160 unsigned int uint;
2161 crypto_rand((char*)&uint, sizeof(uint));
2162 #if SIZEOF_INT == 4
2163 #define UINT_MAX_AS_DOUBLE 4294967296.0
2164 #elif SIZEOF_INT == 8
2165 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2166 #else
2167 #error SIZEOF_INT is neither 4 nor 8
2168 #endif
2169 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2172 /** Generate and return a new random hostname starting with <b>prefix</b>,
2173 * ending with <b>suffix</b>, and containing no less than
2174 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2175 * characters between. */
2176 char *
2177 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2178 const char *suffix)
2180 char *result, *rand_bytes;
2181 int randlen, rand_bytes_len;
2182 size_t resultlen, prefixlen;
2184 tor_assert(max_rand_len >= min_rand_len);
2185 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2186 prefixlen = strlen(prefix);
2187 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2189 rand_bytes_len = ((randlen*5)+7)/8;
2190 if (rand_bytes_len % 5)
2191 rand_bytes_len += 5 - (rand_bytes_len%5);
2192 rand_bytes = tor_malloc(rand_bytes_len);
2193 crypto_rand(rand_bytes, rand_bytes_len);
2195 result = tor_malloc(resultlen);
2196 memcpy(result, prefix, prefixlen);
2197 base32_encode(result+prefixlen, resultlen-prefixlen,
2198 rand_bytes, rand_bytes_len);
2199 tor_free(rand_bytes);
2200 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2202 return result;
2205 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2206 * is empty. */
2207 void *
2208 smartlist_choose(const smartlist_t *sl)
2210 int len = smartlist_len(sl);
2211 if (len)
2212 return smartlist_get(sl,crypto_rand_int(len));
2213 return NULL; /* no elements to choose from */
2216 /** Scramble the elements of <b>sl</b> into a random order. */
2217 void
2218 smartlist_shuffle(smartlist_t *sl)
2220 int i;
2221 /* From the end of the list to the front, choose at random from the
2222 positions we haven't looked at yet, and swap that position into the
2223 current position. Remember to give "no swap" the same probability as
2224 any other swap. */
2225 for (i = smartlist_len(sl)-1; i > 0; --i) {
2226 int j = crypto_rand_int(i+1);
2227 smartlist_swap(sl, i, j);
2231 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2232 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2233 * bytes. Return the number of bytes written on success; -1 if
2234 * destlen is too short, or other failure.
2237 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2239 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2240 * it ever shows up in the profile. */
2241 EVP_ENCODE_CTX ctx;
2242 int len, ret;
2243 tor_assert(srclen < INT_MAX);
2245 /* 48 bytes of input -> 64 bytes of output plus newline.
2246 Plus one more byte, in case I'm wrong.
2248 if (destlen < ((srclen/48)+1)*66)
2249 return -1;
2250 if (destlen > SIZE_T_CEILING)
2251 return -1;
2253 EVP_EncodeInit(&ctx);
2254 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2255 (unsigned char*)src, (int)srclen);
2256 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2257 ret += len;
2258 return ret;
2261 #define X 255
2262 #define SP 64
2263 #define PAD 65
2264 /** Internal table mapping byte values to what they represent in base64.
2265 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2266 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2267 * end-of-string. */
2268 static const uint8_t base64_decode_table[256] = {
2269 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2270 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2271 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2272 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2273 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2274 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2275 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2276 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2277 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2278 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2279 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2280 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2281 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2282 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2283 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2284 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2287 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2288 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2289 * bytes. Return the number of bytes written on success; -1 if
2290 * destlen is too short, or other failure.
2292 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2293 * spaces or padding.
2295 * NOTE 2: This implementation does not check for the correct number of
2296 * padding "=" characters at the end of the string, and does not check
2297 * for internal padding characters.
2300 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2302 #ifdef USE_OPENSSL_BASE64
2303 EVP_ENCODE_CTX ctx;
2304 int len, ret;
2305 /* 64 bytes of input -> *up to* 48 bytes of output.
2306 Plus one more byte, in case I'm wrong.
2308 if (destlen < ((srclen/64)+1)*49)
2309 return -1;
2310 if (destlen > SIZE_T_CEILING)
2311 return -1;
2313 EVP_DecodeInit(&ctx);
2314 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2315 (unsigned char*)src, srclen);
2316 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2317 ret += len;
2318 return ret;
2319 #else
2320 const char *eos = src+srclen;
2321 uint32_t n=0;
2322 int n_idx=0;
2323 char *dest_orig = dest;
2325 /* Max number of bits == srclen*6.
2326 * Number of bytes required to hold all bits == (srclen*6)/8.
2327 * Yes, we want to round down: anything that hangs over the end of a
2328 * byte is padding. */
2329 if (destlen < (srclen*3)/4)
2330 return -1;
2331 if (destlen > SIZE_T_CEILING)
2332 return -1;
2334 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2335 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2336 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2338 for ( ; src < eos; ++src) {
2339 unsigned char c = (unsigned char) *src;
2340 uint8_t v = base64_decode_table[c];
2341 switch (v) {
2342 case X:
2343 /* This character isn't allowed in base64. */
2344 return -1;
2345 case SP:
2346 /* This character is whitespace, and has no effect. */
2347 continue;
2348 case PAD:
2349 /* We've hit an = character: the data is over. */
2350 goto end_of_loop;
2351 default:
2352 /* We have an actual 6-bit value. Append it to the bits in n. */
2353 n = (n<<6) | v;
2354 if ((++n_idx) == 4) {
2355 /* We've accumulated 24 bits in n. Flush them. */
2356 *dest++ = (n>>16);
2357 *dest++ = (n>>8) & 0xff;
2358 *dest++ = (n) & 0xff;
2359 n_idx = 0;
2360 n = 0;
2364 end_of_loop:
2365 /* If we have leftover bits, we need to cope. */
2366 switch (n_idx) {
2367 case 0:
2368 default:
2369 /* No leftover bits. We win. */
2370 break;
2371 case 1:
2372 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2373 return -1;
2374 case 2:
2375 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2376 *dest++ = n >> 4;
2377 break;
2378 case 3:
2379 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2380 *dest++ = n >> 10;
2381 *dest++ = n >> 2;
2384 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2385 tor_assert((dest-dest_orig) <= INT_MAX);
2387 return (int)(dest-dest_orig);
2388 #endif
2390 #undef X
2391 #undef SP
2392 #undef PAD
2394 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2395 * and newline characters, and store the nul-terminated result in the first
2396 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2398 digest_to_base64(char *d64, const char *digest)
2400 char buf[256];
2401 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2402 buf[BASE64_DIGEST_LEN] = '\0';
2403 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2404 return 0;
2407 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2408 * trailing newline or = characters), decode it and store the result in the
2409 * first DIGEST_LEN bytes at <b>digest</b>. */
2411 digest_from_base64(char *digest, const char *d64)
2413 #ifdef USE_OPENSSL_BASE64
2414 char buf_in[BASE64_DIGEST_LEN+3];
2415 char buf[256];
2416 if (strlen(d64) != BASE64_DIGEST_LEN)
2417 return -1;
2418 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2419 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2420 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2421 return -1;
2422 memcpy(digest, buf, DIGEST_LEN);
2423 return 0;
2424 #else
2425 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2426 return 0;
2427 else
2428 return -1;
2429 #endif
2432 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2433 * trailing = and newline characters, and store the nul-terminated result in
2434 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2436 digest256_to_base64(char *d64, const char *digest)
2438 char buf[256];
2439 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2440 buf[BASE64_DIGEST256_LEN] = '\0';
2441 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2442 return 0;
2445 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2446 * trailing newline or = characters), decode it and store the result in the
2447 * first DIGEST256_LEN bytes at <b>digest</b>. */
2449 digest256_from_base64(char *digest, const char *d64)
2451 #ifdef USE_OPENSSL_BASE64
2452 char buf_in[BASE64_DIGEST256_LEN+3];
2453 char buf[256];
2454 if (strlen(d64) != BASE64_DIGEST256_LEN)
2455 return -1;
2456 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2457 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2458 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2459 return -1;
2460 memcpy(digest, buf, DIGEST256_LEN);
2461 return 0;
2462 #else
2463 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2464 return 0;
2465 else
2466 return -1;
2467 #endif
2470 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2471 * that srclen*8 is a multiple of 5.
2473 void
2474 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2476 unsigned int i, v, u;
2477 size_t nbits = srclen * 8, bit;
2479 tor_assert(srclen < SIZE_T_CEILING/8);
2480 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2481 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2482 tor_assert(destlen < SIZE_T_CEILING);
2484 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2485 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2486 v = ((uint8_t)src[bit/8]) << 8;
2487 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2488 /* set u to the 5-bit value at the bit'th bit of src. */
2489 u = (v >> (11-(bit%8))) & 0x1F;
2490 dest[i] = BASE32_CHARS[u];
2492 dest[i] = '\0';
2495 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2496 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2499 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2501 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2502 * it ever shows up in the profile. */
2503 unsigned int i;
2504 size_t nbits, j, bit;
2505 char *tmp;
2506 nbits = srclen * 5;
2508 tor_assert(srclen < SIZE_T_CEILING / 5);
2509 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2510 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2511 tor_assert(destlen < SIZE_T_CEILING);
2513 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2514 tmp = tor_malloc_zero(srclen);
2515 for (j = 0; j < srclen; ++j) {
2516 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2517 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2518 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2519 else {
2520 log_warn(LD_BUG, "illegal character in base32 encoded string");
2521 tor_free(tmp);
2522 return -1;
2526 /* Assemble result byte-wise by applying five possible cases. */
2527 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2528 switch (bit % 40) {
2529 case 0:
2530 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2531 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2532 break;
2533 case 8:
2534 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2535 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2536 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2537 break;
2538 case 16:
2539 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2540 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2541 break;
2542 case 24:
2543 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2544 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2545 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2546 break;
2547 case 32:
2548 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2549 ((uint8_t)tmp[(bit/5)+1]);
2550 break;
2554 memset(tmp, 0, srclen);
2555 tor_free(tmp);
2556 tmp = NULL;
2557 return 0;
2560 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2561 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2562 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2563 * are a salt; the 9th byte describes how much iteration to do.
2564 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2566 void
2567 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2568 size_t secret_len, const char *s2k_specifier)
2570 crypto_digest_env_t *d;
2571 uint8_t c;
2572 size_t count, tmplen;
2573 char *tmp;
2574 tor_assert(key_out_len < SIZE_T_CEILING);
2576 #define EXPBIAS 6
2577 c = s2k_specifier[8];
2578 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2579 #undef EXPBIAS
2581 tor_assert(key_out_len <= DIGEST_LEN);
2583 d = crypto_new_digest_env();
2584 tmplen = 8+secret_len;
2585 tmp = tor_malloc(tmplen);
2586 memcpy(tmp,s2k_specifier,8);
2587 memcpy(tmp+8,secret,secret_len);
2588 secret_len += 8;
2589 while (count) {
2590 if (count >= secret_len) {
2591 crypto_digest_add_bytes(d, tmp, secret_len);
2592 count -= secret_len;
2593 } else {
2594 crypto_digest_add_bytes(d, tmp, count);
2595 count = 0;
2598 crypto_digest_get_digest(d, key_out, key_out_len);
2599 memset(tmp, 0, tmplen);
2600 tor_free(tmp);
2601 crypto_free_digest_env(d);
2604 #ifdef TOR_IS_MULTITHREADED
2605 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2606 static void
2607 _openssl_locking_cb(int mode, int n, const char *file, int line)
2609 (void)file;
2610 (void)line;
2611 if (!_openssl_mutexes)
2612 /* This is not a really good fix for the
2613 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2614 * it can't hurt. */
2615 return;
2616 if (mode & CRYPTO_LOCK)
2617 tor_mutex_acquire(_openssl_mutexes[n]);
2618 else
2619 tor_mutex_release(_openssl_mutexes[n]);
2622 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2623 * as a lock. */
2624 struct CRYPTO_dynlock_value {
2625 tor_mutex_t *lock;
2628 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2629 * documentation in OpenSSL's docs for more info. */
2630 static struct CRYPTO_dynlock_value *
2631 _openssl_dynlock_create_cb(const char *file, int line)
2633 struct CRYPTO_dynlock_value *v;
2634 (void)file;
2635 (void)line;
2636 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2637 v->lock = tor_mutex_new();
2638 return v;
2641 /** OpenSSL callback function to acquire or release a lock: see
2642 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2643 static void
2644 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2645 const char *file, int line)
2647 (void)file;
2648 (void)line;
2649 if (mode & CRYPTO_LOCK)
2650 tor_mutex_acquire(v->lock);
2651 else
2652 tor_mutex_release(v->lock);
2655 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2656 * documentation in OpenSSL's docs for more info. */
2657 static void
2658 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2659 const char *file, int line)
2661 (void)file;
2662 (void)line;
2663 tor_mutex_free(v->lock);
2664 tor_free(v);
2667 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2668 * multithreaded. */
2669 static int
2670 setup_openssl_threading(void)
2672 int i;
2673 int n = CRYPTO_num_locks();
2674 _n_openssl_mutexes = n;
2675 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2676 for (i=0; i < n; ++i)
2677 _openssl_mutexes[i] = tor_mutex_new();
2678 CRYPTO_set_locking_callback(_openssl_locking_cb);
2679 CRYPTO_set_id_callback(tor_get_thread_id);
2680 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2681 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2682 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2683 return 0;
2685 #else
2686 static int
2687 setup_openssl_threading(void)
2689 return 0;
2691 #endif