Implement queue with O(1) operations, and correct some math.
[tor/rransom.git] / src / common / crypto.c
blob57c636db68e517c90f1822788f136370e83bfdf5
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-2009, 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 "log.h"
54 #include "aes.h"
55 #include "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 /** Macro: is k a valid RSA public or private key? */
66 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
67 /** Macro: is k a valid RSA private key? */
68 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
70 #ifdef TOR_IS_MULTITHREADED
71 /** A number of preallocated mutexes for use by OpenSSL. */
72 static tor_mutex_t **_openssl_mutexes = NULL;
73 /** How many mutexes have we allocated for use by OpenSSL? */
74 static int _n_openssl_mutexes = 0;
75 #endif
77 /** A public key, or a public/private key-pair. */
78 struct crypto_pk_env_t
80 int refs; /* reference counting so we don't have to copy keys */
81 RSA *key;
84 /** Key and stream information for a stream cipher. */
85 struct crypto_cipher_env_t
87 char key[CIPHER_KEY_LEN];
88 aes_cnt_cipher_t *cipher;
91 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
92 * while we're waiting for the second.*/
93 struct crypto_dh_env_t {
94 DH *dh;
97 static int setup_openssl_threading(void);
98 static int tor_check_dh_key(BIGNUM *bn);
100 /** Return the number of bytes added by padding method <b>padding</b>.
102 static INLINE int
103 crypto_get_rsa_padding_overhead(int padding)
105 switch (padding)
107 case RSA_NO_PADDING: return 0;
108 case RSA_PKCS1_OAEP_PADDING: return 42;
109 case RSA_PKCS1_PADDING: return 11;
110 default: tor_assert(0); return -1;
114 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
116 static INLINE int
117 crypto_get_rsa_padding(int padding)
119 switch (padding)
121 case PK_NO_PADDING: return RSA_NO_PADDING;
122 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
123 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
124 default: tor_assert(0); return -1;
128 /** Boolean: has OpenSSL's crypto been initialized? */
129 static int _crypto_global_initialized = 0;
131 /** Log all pending crypto errors at level <b>severity</b>. Use
132 * <b>doing</b> to describe our current activities.
134 static void
135 crypto_log_errors(int severity, const char *doing)
137 unsigned long err;
138 const char *msg, *lib, *func;
139 while ((err = ERR_get_error()) != 0) {
140 msg = (const char*)ERR_reason_error_string(err);
141 lib = (const char*)ERR_lib_error_string(err);
142 func = (const char*)ERR_func_error_string(err);
143 if (!msg) msg = "(null)";
144 if (!lib) lib = "(null)";
145 if (!func) func = "(null)";
146 if (doing) {
147 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
148 doing, msg, lib, func);
149 } else {
150 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
155 /** Log any OpenSSL engines we're using at NOTICE. */
156 static void
157 log_engine(const char *fn, ENGINE *e)
159 if (e) {
160 const char *name, *id;
161 name = ENGINE_get_name(e);
162 id = ENGINE_get_id(e);
163 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
164 name?name:"?", id?id:"?", fn);
165 } else {
166 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
170 /** Try to load an engine in a shared library via fully qualified path.
172 static ENGINE *
173 try_load_engine(const char *path, const char *engine)
175 ENGINE *e = ENGINE_by_id("dynamic");
176 if (e) {
177 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
178 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
179 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
180 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
181 ENGINE_free(e);
182 e = NULL;
185 return e;
188 /** Initialize the crypto library. Return 0 on success, -1 on failure.
191 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
193 if (!_crypto_global_initialized) {
194 ERR_load_crypto_strings();
195 OpenSSL_add_all_algorithms();
196 _crypto_global_initialized = 1;
197 setup_openssl_threading();
198 if (useAccel > 0) {
199 ENGINE *e = NULL;
200 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
201 ENGINE_load_builtin_engines();
202 ENGINE_register_all_complete();
203 if (accelName) {
204 if (accelDir) {
205 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
206 " via path \"%s\".", accelName, accelDir);
207 e = try_load_engine(accelName, accelDir);
208 } else {
209 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
210 " acceleration support.", accelName);
211 e = ENGINE_by_id(accelName);
213 if (!e) {
214 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
215 accelName);
216 } else {
217 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
218 accelName);
221 if (e) {
222 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
223 " setting default ciphers.");
224 ENGINE_set_default(e, ENGINE_METHOD_ALL);
226 log_engine("RSA", ENGINE_get_default_RSA());
227 log_engine("DH", ENGINE_get_default_DH());
228 log_engine("RAND", ENGINE_get_default_RAND());
229 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
230 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
231 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
232 } else {
233 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
235 return crypto_seed_rng(1);
237 return 0;
240 /** Free crypto resources held by this thread. */
241 void
242 crypto_thread_cleanup(void)
244 ERR_remove_state(0);
247 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
250 crypto_global_cleanup(void)
252 EVP_cleanup();
253 ERR_remove_state(0);
254 ERR_free_strings();
255 ENGINE_cleanup();
256 CONF_modules_unload(1);
257 CRYPTO_cleanup_all_ex_data();
258 #ifdef TOR_IS_MULTITHREADED
259 if (_n_openssl_mutexes) {
260 int n = _n_openssl_mutexes;
261 tor_mutex_t **ms = _openssl_mutexes;
262 int i;
263 _openssl_mutexes = NULL;
264 _n_openssl_mutexes = 0;
265 for (i=0;i<n;++i) {
266 tor_mutex_free(ms[i]);
268 tor_free(ms);
270 #endif
271 return 0;
274 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
275 crypto_pk_env_t *
276 _crypto_new_pk_env_rsa(RSA *rsa)
278 crypto_pk_env_t *env;
279 tor_assert(rsa);
280 env = tor_malloc(sizeof(crypto_pk_env_t));
281 env->refs = 1;
282 env->key = rsa;
283 return env;
286 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
287 * returns NULL if this isn't an RSA key. */
288 crypto_pk_env_t *
289 _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
291 RSA *rsa;
292 if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
293 return NULL;
294 return _crypto_new_pk_env_rsa(rsa);
297 /** Helper, used by tor-checkkey.c. Return the RSA from a crypto_pk_env_t. */
298 RSA *
299 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
301 return env->key;
304 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
305 * private is set, include the private-key portion of the key. */
306 EVP_PKEY *
307 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
309 RSA *key = NULL;
310 EVP_PKEY *pkey = NULL;
311 tor_assert(env->key);
312 if (private) {
313 if (!(key = RSAPrivateKey_dup(env->key)))
314 goto error;
315 } else {
316 if (!(key = RSAPublicKey_dup(env->key)))
317 goto error;
319 if (!(pkey = EVP_PKEY_new()))
320 goto error;
321 if (!(EVP_PKEY_assign_RSA(pkey, key)))
322 goto error;
323 return pkey;
324 error:
325 if (pkey)
326 EVP_PKEY_free(pkey);
327 if (key)
328 RSA_free(key);
329 return NULL;
332 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
334 DH *
335 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
337 return dh->dh;
340 /** Allocate and return storage for a public key. The key itself will not yet
341 * be set.
343 crypto_pk_env_t *
344 crypto_new_pk_env(void)
346 RSA *rsa;
348 rsa = RSA_new();
349 if (!rsa) return NULL;
350 return _crypto_new_pk_env_rsa(rsa);
353 /** Release a reference to an asymmetric key; when all the references
354 * are released, free the key.
356 void
357 crypto_free_pk_env(crypto_pk_env_t *env)
359 tor_assert(env);
361 if (--env->refs > 0)
362 return;
364 if (env->key)
365 RSA_free(env->key);
367 tor_free(env);
370 /** Create a new symmetric cipher for a given key and encryption flag
371 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
372 * on failure.
374 crypto_cipher_env_t *
375 crypto_create_init_cipher(const char *key, int encrypt_mode)
377 int r;
378 crypto_cipher_env_t *crypto = NULL;
380 if (! (crypto = crypto_new_cipher_env())) {
381 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
382 return NULL;
385 if (crypto_cipher_set_key(crypto, key)) {
386 crypto_log_errors(LOG_WARN, "setting symmetric key");
387 goto error;
390 if (encrypt_mode)
391 r = crypto_cipher_encrypt_init_cipher(crypto);
392 else
393 r = crypto_cipher_decrypt_init_cipher(crypto);
395 if (r)
396 goto error;
397 return crypto;
399 error:
400 if (crypto)
401 crypto_free_cipher_env(crypto);
402 return NULL;
405 /** Allocate and return a new symmetric cipher.
407 crypto_cipher_env_t *
408 crypto_new_cipher_env(void)
410 crypto_cipher_env_t *env;
412 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
413 env->cipher = aes_new_cipher();
414 return env;
417 /** Free a symmetric cipher.
419 void
420 crypto_free_cipher_env(crypto_cipher_env_t *env)
422 tor_assert(env);
424 tor_assert(env->cipher);
425 aes_free_cipher(env->cipher);
426 memset(env, 0, sizeof(crypto_cipher_env_t));
427 tor_free(env);
430 /* public key crypto */
432 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
433 * success, -1 on failure.
436 crypto_pk_generate_key(crypto_pk_env_t *env)
438 tor_assert(env);
440 if (env->key)
441 RSA_free(env->key);
442 #if OPENSSL_VERSION_NUMBER < 0x00908000l
443 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
444 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
445 #else
446 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
448 BIGNUM *e = BN_new();
449 RSA *r = NULL;
450 if (!e)
451 goto done;
452 if (! BN_set_word(e, 65537))
453 goto done;
454 r = RSA_new();
455 if (!r)
456 goto done;
457 if (RSA_generate_key_ex(r, PK_BYTES*8, e, NULL) == -1)
458 goto done;
460 env->key = r;
461 r = NULL;
462 done:
463 if (e)
464 BN_free(e);
465 if (r)
466 RSA_free(r);
468 #endif
469 if (!env->key) {
470 crypto_log_errors(LOG_WARN, "generating RSA key");
471 return -1;
474 return 0;
477 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
478 * Return 0 on success, -1 on failure.
480 /* Used here, and used for testing. */
482 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
483 const char *s)
485 BIO *b;
487 tor_assert(env);
488 tor_assert(s);
490 /* Create a read-only memory BIO, backed by the NUL-terminated string 's' */
491 b = BIO_new_mem_buf((char*)s, -1);
493 if (env->key)
494 RSA_free(env->key);
496 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
498 BIO_free(b);
500 if (!env->key) {
501 crypto_log_errors(LOG_WARN, "Error parsing private key");
502 return -1;
504 return 0;
507 /** Read a PEM-encoded private key from the file named by
508 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
511 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
512 const char *keyfile)
514 char *contents;
515 int r;
517 /* Read the file into a string. */
518 contents = read_file_to_str(keyfile, 0, NULL);
519 if (!contents) {
520 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
521 return -1;
524 /* Try to parse it. */
525 r = crypto_pk_read_private_key_from_string(env, contents);
526 tor_free(contents);
527 if (r)
528 return -1; /* read_private_key_from_string already warned, so we don't.*/
530 /* Make sure it's valid. */
531 if (crypto_pk_check_key(env) <= 0)
532 return -1;
534 return 0;
537 /** Helper function to implement crypto_pk_write_*_key_to_string. */
538 static int
539 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
540 size_t *len, int is_public)
542 BUF_MEM *buf;
543 BIO *b;
544 int r;
546 tor_assert(env);
547 tor_assert(env->key);
548 tor_assert(dest);
550 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
552 /* Now you can treat b as if it were a file. Just use the
553 * PEM_*_bio_* functions instead of the non-bio variants.
555 if (is_public)
556 r = PEM_write_bio_RSAPublicKey(b, env->key);
557 else
558 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
560 if (!r) {
561 crypto_log_errors(LOG_WARN, "writing RSA key to string");
562 BIO_free(b);
563 return -1;
566 BIO_get_mem_ptr(b, &buf);
567 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
568 BIO_free(b);
570 tor_assert(buf->length >= 0);
571 *dest = tor_malloc(buf->length+1);
572 memcpy(*dest, buf->data, buf->length);
573 (*dest)[buf->length] = 0; /* nul terminate it */
574 *len = buf->length;
575 BUF_MEM_free(buf);
577 return 0;
580 /** PEM-encode the public key portion of <b>env</b> and write it to a
581 * newly allocated string. On success, set *<b>dest</b> to the new
582 * string, *<b>len</b> to the string's length, and return 0. On
583 * failure, return -1.
586 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
587 size_t *len)
589 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
592 /** PEM-encode the private key portion of <b>env</b> and write it to a
593 * newly allocated string. On success, set *<b>dest</b> to the new
594 * string, *<b>len</b> to the string's length, and return 0. On
595 * failure, return -1.
598 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
599 size_t *len)
601 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
604 /** Read a PEM-encoded public key from the first <b>len</b> characters of
605 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
606 * failure.
609 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
610 size_t len)
612 BIO *b;
614 tor_assert(env);
615 tor_assert(src);
616 tor_assert(len<INT_MAX);
618 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
620 BIO_write(b, src, (int)len);
622 if (env->key)
623 RSA_free(env->key);
624 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
625 BIO_free(b);
626 if (!env->key) {
627 crypto_log_errors(LOG_WARN, "reading public key from string");
628 return -1;
631 return 0;
634 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
635 * PEM-encoded. Return 0 on success, -1 on failure.
638 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
639 const char *fname)
641 BIO *bio;
642 char *cp;
643 long len;
644 char *s;
645 int r;
647 tor_assert(PRIVATE_KEY_OK(env));
649 if (!(bio = BIO_new(BIO_s_mem())))
650 return -1;
651 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
652 == 0) {
653 crypto_log_errors(LOG_WARN, "writing private key");
654 BIO_free(bio);
655 return -1;
657 len = BIO_get_mem_data(bio, &cp);
658 tor_assert(len >= 0);
659 s = tor_malloc(len+1);
660 memcpy(s, cp, len);
661 s[len]='\0';
662 r = write_str_to_file(fname, s, 0);
663 BIO_free(bio);
664 tor_free(s);
665 return r;
668 /** Return true iff <b>env</b> has a valid key.
671 crypto_pk_check_key(crypto_pk_env_t *env)
673 int r;
674 tor_assert(env);
676 r = RSA_check_key(env->key);
677 if (r <= 0)
678 crypto_log_errors(LOG_WARN,"checking RSA key");
679 return r;
682 /** Return true iff <b>key</b> contains the private-key portion of the RSA
683 * key. */
685 crypto_pk_key_is_private(const crypto_pk_env_t *key)
687 tor_assert(key);
688 return PRIVATE_KEY_OK(key);
691 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
692 * if a==b, and 1 if a\>b.
695 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
697 int result;
699 if (!a || !b)
700 return -1;
702 if (!a->key || !b->key)
703 return -1;
705 tor_assert(PUBLIC_KEY_OK(a));
706 tor_assert(PUBLIC_KEY_OK(b));
707 result = BN_cmp((a->key)->n, (b->key)->n);
708 if (result)
709 return result;
710 return BN_cmp((a->key)->e, (b->key)->e);
713 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
714 size_t
715 crypto_pk_keysize(crypto_pk_env_t *env)
717 tor_assert(env);
718 tor_assert(env->key);
720 return (size_t) RSA_size(env->key);
723 /** Increase the reference count of <b>env</b>, and return it.
725 crypto_pk_env_t *
726 crypto_pk_dup_key(crypto_pk_env_t *env)
728 tor_assert(env);
729 tor_assert(env->key);
731 env->refs++;
732 return env;
735 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
736 crypto_pk_env_t *
737 crypto_pk_copy_full(crypto_pk_env_t *env)
739 RSA *new_key;
740 tor_assert(env);
741 tor_assert(env->key);
743 if (PRIVATE_KEY_OK(env)) {
744 new_key = RSAPrivateKey_dup(env->key);
745 } else {
746 new_key = RSAPublicKey_dup(env->key);
749 return _crypto_new_pk_env_rsa(new_key);
752 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
753 * in <b>env</b>, using the padding method <b>padding</b>. On success,
754 * write the result to <b>to</b>, and return the number of bytes
755 * written. On failure, return -1.
758 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
759 const char *from, size_t fromlen, int padding)
761 int r;
762 tor_assert(env);
763 tor_assert(from);
764 tor_assert(to);
765 tor_assert(fromlen<INT_MAX);
767 r = RSA_public_encrypt((int)fromlen,
768 (unsigned char*)from, (unsigned char*)to,
769 env->key, crypto_get_rsa_padding(padding));
770 if (r<0) {
771 crypto_log_errors(LOG_WARN, "performing RSA encryption");
772 return -1;
774 return r;
777 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
778 * in <b>env</b>, using the padding method <b>padding</b>. On success,
779 * write the result to <b>to</b>, and return the number of bytes
780 * written. On failure, return -1.
783 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
784 const char *from, size_t fromlen,
785 int padding, int warnOnFailure)
787 int r;
788 tor_assert(env);
789 tor_assert(from);
790 tor_assert(to);
791 tor_assert(env->key);
792 tor_assert(fromlen<INT_MAX);
793 if (!env->key->p)
794 /* Not a private key */
795 return -1;
797 r = RSA_private_decrypt((int)fromlen,
798 (unsigned char*)from, (unsigned char*)to,
799 env->key, crypto_get_rsa_padding(padding));
801 if (r<0) {
802 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
803 "performing RSA decryption");
804 return -1;
806 return r;
809 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
810 * public key in <b>env</b>, using PKCS1 padding. On success, write the
811 * signed data to <b>to</b>, and return the number of bytes written.
812 * On failure, return -1.
815 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
816 const char *from, size_t fromlen)
818 int r;
819 tor_assert(env);
820 tor_assert(from);
821 tor_assert(to);
822 tor_assert(fromlen < INT_MAX);
823 r = RSA_public_decrypt((int)fromlen,
824 (unsigned char*)from, (unsigned char*)to,
825 env->key, RSA_PKCS1_PADDING);
827 if (r<0) {
828 crypto_log_errors(LOG_WARN, "checking RSA signature");
829 return -1;
831 return r;
834 /** Check a siglen-byte long signature at <b>sig</b> against
835 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
836 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
837 * SHA1(data). Else return -1.
840 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
841 size_t datalen, const char *sig, size_t siglen)
843 char digest[DIGEST_LEN];
844 char *buf;
845 int r;
847 tor_assert(env);
848 tor_assert(data);
849 tor_assert(sig);
851 if (crypto_digest(digest,data,datalen)<0) {
852 log_warn(LD_BUG, "couldn't compute digest");
853 return -1;
855 buf = tor_malloc(crypto_pk_keysize(env)+1);
856 r = crypto_pk_public_checksig(env,buf,sig,siglen);
857 if (r != DIGEST_LEN) {
858 log_warn(LD_CRYPTO, "Invalid signature");
859 tor_free(buf);
860 return -1;
862 if (memcmp(buf, digest, DIGEST_LEN)) {
863 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
864 tor_free(buf);
865 return -1;
867 tor_free(buf);
869 return 0;
872 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
873 * <b>env</b>, using PKCS1 padding. On success, write the signature to
874 * <b>to</b>, and return the number of bytes written. On failure, return
875 * -1.
878 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
879 const char *from, size_t fromlen)
881 int r;
882 tor_assert(env);
883 tor_assert(from);
884 tor_assert(to);
885 tor_assert(fromlen < INT_MAX);
886 if (!env->key->p)
887 /* Not a private key */
888 return -1;
890 r = RSA_private_encrypt((int)fromlen,
891 (unsigned char*)from, (unsigned char*)to,
892 env->key, RSA_PKCS1_PADDING);
893 if (r<0) {
894 crypto_log_errors(LOG_WARN, "generating RSA signature");
895 return -1;
897 return r;
900 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
901 * <b>from</b>; sign the data with the private key in <b>env</b>, and
902 * store it in <b>to</b>. Return the number of bytes written on
903 * success, and -1 on failure.
906 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
907 const char *from, size_t fromlen)
909 int r;
910 char digest[DIGEST_LEN];
911 if (crypto_digest(digest,from,fromlen)<0)
912 return -1;
913 r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
914 memset(digest, 0, sizeof(digest));
915 return r;
918 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
919 * bytes of data from <b>from</b>, with padding type 'padding',
920 * storing the results on <b>to</b>.
922 * If no padding is used, the public key must be at least as large as
923 * <b>from</b>.
925 * Returns the number of bytes written on success, -1 on failure.
927 * The encrypted data consists of:
928 * - The source data, padded and encrypted with the public key, if the
929 * padded source data is no longer than the public key, and <b>force</b>
930 * is false, OR
931 * - The beginning of the source data prefixed with a 16-byte symmetric key,
932 * padded and encrypted with the public key; followed by the rest of
933 * the source data encrypted in AES-CTR mode with the symmetric key.
936 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
937 char *to,
938 const char *from,
939 size_t fromlen,
940 int padding, int force)
942 int overhead, outlen, r;
943 size_t pkeylen, symlen;
944 crypto_cipher_env_t *cipher = NULL;
945 char *buf = NULL;
947 tor_assert(env);
948 tor_assert(from);
949 tor_assert(to);
951 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
952 pkeylen = crypto_pk_keysize(env);
954 if (padding == PK_NO_PADDING && fromlen < pkeylen)
955 return -1;
957 if (!force && fromlen+overhead <= pkeylen) {
958 /* It all fits in a single encrypt. */
959 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
961 cipher = crypto_new_cipher_env();
962 if (!cipher) return -1;
963 if (crypto_cipher_generate_key(cipher)<0)
964 goto err;
965 /* You can't just run around RSA-encrypting any bitstream: if it's
966 * greater than the RSA key, then OpenSSL will happily encrypt, and
967 * later decrypt to the wrong value. So we set the first bit of
968 * 'cipher->key' to 0 if we aren't padding. This means that our
969 * symmetric key is really only 127 bits.
971 if (padding == PK_NO_PADDING)
972 cipher->key[0] &= 0x7f;
973 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
974 goto err;
975 buf = tor_malloc(pkeylen+1);
976 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
977 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
979 /* Length of symmetrically encrypted data. */
980 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
982 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
983 if (outlen!=(int)pkeylen) {
984 goto err;
986 r = crypto_cipher_encrypt(cipher, to+outlen,
987 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
989 if (r<0) goto err;
990 memset(buf, 0, pkeylen);
991 tor_free(buf);
992 crypto_free_cipher_env(cipher);
993 tor_assert(outlen+symlen < INT_MAX);
994 return (int)(outlen + symlen);
995 err:
996 if (buf) {
997 memset(buf, 0, pkeylen);
998 tor_free(buf);
1000 if (cipher) crypto_free_cipher_env(cipher);
1001 return -1;
1004 /** Invert crypto_pk_public_hybrid_encrypt. */
1006 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1007 char *to,
1008 const char *from,
1009 size_t fromlen,
1010 int padding, int warnOnFailure)
1012 int outlen, r;
1013 size_t pkeylen;
1014 crypto_cipher_env_t *cipher = NULL;
1015 char *buf = NULL;
1017 pkeylen = crypto_pk_keysize(env);
1019 if (fromlen <= pkeylen) {
1020 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
1021 warnOnFailure);
1023 buf = tor_malloc(pkeylen+1);
1024 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
1025 warnOnFailure);
1026 if (outlen<0) {
1027 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1028 "Error decrypting public-key data");
1029 goto err;
1031 if (outlen < CIPHER_KEY_LEN) {
1032 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1033 "No room for a symmetric key");
1034 goto err;
1036 cipher = crypto_create_init_cipher(buf, 0);
1037 if (!cipher) {
1038 goto err;
1040 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1041 outlen -= CIPHER_KEY_LEN;
1042 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1043 if (r<0)
1044 goto err;
1045 memset(buf,0,pkeylen);
1046 tor_free(buf);
1047 crypto_free_cipher_env(cipher);
1048 tor_assert(outlen + fromlen < INT_MAX);
1049 return (int)(outlen + (fromlen-pkeylen));
1050 err:
1051 memset(buf,0,pkeylen);
1052 tor_free(buf);
1053 if (cipher) crypto_free_cipher_env(cipher);
1054 return -1;
1057 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1058 * Return -1 on error, or the number of characters used on success.
1061 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1063 int len;
1064 unsigned char *buf, *cp;
1065 len = i2d_RSAPublicKey(pk->key, NULL);
1066 if (len < 0 || (size_t)len > dest_len)
1067 return -1;
1068 cp = buf = tor_malloc(len+1);
1069 len = i2d_RSAPublicKey(pk->key, &cp);
1070 if (len < 0) {
1071 crypto_log_errors(LOG_WARN,"encoding public key");
1072 tor_free(buf);
1073 return -1;
1075 /* We don't encode directly into 'dest', because that would be illegal
1076 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1078 memcpy(dest,buf,len);
1079 tor_free(buf);
1080 return len;
1083 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1084 * success and NULL on failure.
1086 crypto_pk_env_t *
1087 crypto_pk_asn1_decode(const char *str, size_t len)
1089 RSA *rsa;
1090 unsigned char *buf;
1091 /* This ifdef suppresses a type warning. Take out the first case once
1092 * everybody is using OpenSSL 0.9.7 or later.
1094 const unsigned char *cp;
1095 cp = buf = tor_malloc(len);
1096 memcpy(buf,str,len);
1097 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1098 tor_free(buf);
1099 if (!rsa) {
1100 crypto_log_errors(LOG_WARN,"decoding public key");
1101 return NULL;
1103 return _crypto_new_pk_env_rsa(rsa);
1106 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1107 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1108 * Return 0 on success, -1 on failure.
1111 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1113 unsigned char *buf, *bufp;
1114 int len;
1116 len = i2d_RSAPublicKey(pk->key, NULL);
1117 if (len < 0)
1118 return -1;
1119 buf = bufp = tor_malloc(len+1);
1120 len = i2d_RSAPublicKey(pk->key, &bufp);
1121 if (len < 0) {
1122 crypto_log_errors(LOG_WARN,"encoding public key");
1123 tor_free(buf);
1124 return -1;
1126 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1127 tor_free(buf);
1128 return -1;
1130 tor_free(buf);
1131 return 0;
1134 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1135 * every four spaces. */
1136 /* static */ void
1137 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1139 int n = 0;
1140 char *end = out+outlen;
1141 while (*in && out<end) {
1142 *out++ = *in++;
1143 if (++n == 4 && *in && out<end) {
1144 n = 0;
1145 *out++ = ' ';
1148 tor_assert(out<end);
1149 *out = '\0';
1152 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1153 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1154 * space). Return 0 on success, -1 on failure.
1156 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1157 * of the public key, converted to hexadecimal, in upper case, with a
1158 * space after every four digits.
1160 * If <b>add_space</b> is false, omit the spaces.
1163 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1165 char digest[DIGEST_LEN];
1166 char hexdigest[HEX_DIGEST_LEN+1];
1167 if (crypto_pk_get_digest(pk, digest)) {
1168 return -1;
1170 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1171 if (add_space) {
1172 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1173 } else {
1174 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1176 return 0;
1179 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1182 crypto_pk_check_fingerprint_syntax(const char *s)
1184 int i;
1185 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1186 if ((i%5) == 4) {
1187 if (!TOR_ISSPACE(s[i])) return 0;
1188 } else {
1189 if (!TOR_ISXDIGIT(s[i])) return 0;
1192 if (s[FINGERPRINT_LEN]) return 0;
1193 return 1;
1196 /* symmetric crypto */
1198 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1199 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1202 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1204 tor_assert(env);
1206 return crypto_rand(env->key, CIPHER_KEY_LEN);
1209 /** Set the symmetric key for the cipher in <b>env</b> to the first
1210 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1211 * Return 0 on success, -1 on failure.
1214 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1216 tor_assert(env);
1217 tor_assert(key);
1219 if (!env->key)
1220 return -1;
1222 memcpy(env->key, key, CIPHER_KEY_LEN);
1223 return 0;
1226 /** Generate an initialization vector for our AES-CTR cipher; store it
1227 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1228 void
1229 crypto_cipher_generate_iv(char *iv_out)
1231 crypto_rand(iv_out, CIPHER_IV_LEN);
1234 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1235 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1236 * <b>iv</b>. */
1238 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1240 tor_assert(env);
1241 tor_assert(iv);
1242 aes_set_iv(env->cipher, iv);
1243 return 0;
1246 /** Return a pointer to the key set for the cipher in <b>env</b>.
1248 const char *
1249 crypto_cipher_get_key(crypto_cipher_env_t *env)
1251 return env->key;
1254 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1255 * success, -1 on failure.
1258 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1260 tor_assert(env);
1262 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1263 return 0;
1266 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1267 * success, -1 on failure.
1270 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1272 tor_assert(env);
1274 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1275 return 0;
1278 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1279 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1280 * On failure, return -1.
1283 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1284 const char *from, size_t fromlen)
1286 tor_assert(env);
1287 tor_assert(env->cipher);
1288 tor_assert(from);
1289 tor_assert(fromlen);
1290 tor_assert(to);
1292 aes_crypt(env->cipher, from, fromlen, to);
1293 return 0;
1296 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1297 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1298 * On failure, return -1.
1301 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1302 const char *from, size_t fromlen)
1304 tor_assert(env);
1305 tor_assert(from);
1306 tor_assert(to);
1308 aes_crypt(env->cipher, from, fromlen, to);
1309 return 0;
1312 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1313 * on success, return 0. On failure, return -1.
1316 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1318 aes_crypt_inplace(env->cipher, buf, len);
1319 return 0;
1322 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1323 * <b>cipher</b> to the buffer in <b>to</b> of length
1324 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1325 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1326 * number of bytes written, on failure, return -1.
1328 * This function adjusts the current position of the counter in <b>cipher</b>
1329 * to immediately after the encrypted data.
1332 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1333 char *to, size_t tolen,
1334 const char *from, size_t fromlen)
1336 tor_assert(cipher);
1337 tor_assert(from);
1338 tor_assert(to);
1339 tor_assert(fromlen < INT_MAX);
1341 if (fromlen < 1)
1342 return -1;
1343 if (tolen < fromlen + CIPHER_IV_LEN)
1344 return -1;
1346 crypto_cipher_generate_iv(to);
1347 if (crypto_cipher_set_iv(cipher, to)<0)
1348 return -1;
1349 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1350 return (int)(fromlen + CIPHER_IV_LEN);
1353 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1354 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1355 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1356 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1357 * number of bytes written, on failure, return -1.
1359 * This function adjusts the current position of the counter in <b>cipher</b>
1360 * to immediately after the decrypted data.
1363 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1364 char *to, size_t tolen,
1365 const char *from, size_t fromlen)
1367 tor_assert(cipher);
1368 tor_assert(from);
1369 tor_assert(to);
1370 tor_assert(fromlen < INT_MAX);
1372 if (fromlen <= CIPHER_IV_LEN)
1373 return -1;
1374 if (tolen < fromlen - CIPHER_IV_LEN)
1375 return -1;
1377 if (crypto_cipher_set_iv(cipher, from)<0)
1378 return -1;
1379 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1380 return (int)(fromlen - CIPHER_IV_LEN);
1383 /* SHA-1 */
1385 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1386 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1387 * Return 0 on success, -1 on failure.
1390 crypto_digest(char *digest, const char *m, size_t len)
1392 tor_assert(m);
1393 tor_assert(digest);
1394 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1397 /** Intermediate information about the digest of a stream of data. */
1398 struct crypto_digest_env_t {
1399 SHA_CTX d;
1402 /** Allocate and return a new digest object.
1404 crypto_digest_env_t *
1405 crypto_new_digest_env(void)
1407 crypto_digest_env_t *r;
1408 r = tor_malloc(sizeof(crypto_digest_env_t));
1409 SHA1_Init(&r->d);
1410 return r;
1413 /** Deallocate a digest object.
1415 void
1416 crypto_free_digest_env(crypto_digest_env_t *digest)
1418 memset(digest, 0, sizeof(crypto_digest_env_t));
1419 tor_free(digest);
1422 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1424 void
1425 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1426 size_t len)
1428 tor_assert(digest);
1429 tor_assert(data);
1430 /* Using the SHA1_*() calls directly means we don't support doing
1431 * SHA1 in hardware. But so far the delay of getting the question
1432 * to the hardware, and hearing the answer, is likely higher than
1433 * just doing it ourselves. Hashes are fast.
1435 SHA1_Update(&digest->d, (void*)data, len);
1438 /** Compute the hash of the data that has been passed to the digest
1439 * object; write the first out_len bytes of the result to <b>out</b>.
1440 * <b>out_len</b> must be \<= DIGEST_LEN.
1442 void
1443 crypto_digest_get_digest(crypto_digest_env_t *digest,
1444 char *out, size_t out_len)
1446 unsigned char r[DIGEST_LEN];
1447 SHA_CTX tmpctx;
1448 tor_assert(digest);
1449 tor_assert(out);
1450 tor_assert(out_len <= DIGEST_LEN);
1451 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1452 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1453 SHA1_Final(r, &tmpctx);
1454 memcpy(out, r, out_len);
1455 memset(r, 0, sizeof(r));
1458 /** Allocate and return a new digest object with the same state as
1459 * <b>digest</b>
1461 crypto_digest_env_t *
1462 crypto_digest_dup(const crypto_digest_env_t *digest)
1464 crypto_digest_env_t *r;
1465 tor_assert(digest);
1466 r = tor_malloc(sizeof(crypto_digest_env_t));
1467 memcpy(r,digest,sizeof(crypto_digest_env_t));
1468 return r;
1471 /** Replace the state of the digest object <b>into</b> with the state
1472 * of the digest object <b>from</b>.
1474 void
1475 crypto_digest_assign(crypto_digest_env_t *into,
1476 const crypto_digest_env_t *from)
1478 tor_assert(into);
1479 tor_assert(from);
1480 memcpy(into,from,sizeof(crypto_digest_env_t));
1483 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1484 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1485 * in <b>hmac_out</b>.
1487 void
1488 crypto_hmac_sha1(char *hmac_out,
1489 const char *key, size_t key_len,
1490 const char *msg, size_t msg_len)
1492 tor_assert(key_len < INT_MAX);
1493 tor_assert(msg_len < INT_MAX);
1494 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1495 (unsigned char*)hmac_out, NULL);
1498 /* DH */
1500 /** Shared P parameter for our DH key exchanged. */
1501 static BIGNUM *dh_param_p = NULL;
1502 /** Shared G parameter for our DH key exchanges. */
1503 static BIGNUM *dh_param_g = NULL;
1505 /** Initialize dh_param_p and dh_param_g if they are not already
1506 * set. */
1507 static void
1508 init_dh_param(void)
1510 BIGNUM *p, *g;
1511 int r;
1512 if (dh_param_p && dh_param_g)
1513 return;
1515 p = BN_new();
1516 g = BN_new();
1517 tor_assert(p);
1518 tor_assert(g);
1520 /* This is from rfc2409, section 6.2. It's a safe prime, and
1521 supposedly it equals:
1522 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1524 r = BN_hex2bn(&p,
1525 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1526 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1527 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1528 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1529 "49286651ECE65381FFFFFFFFFFFFFFFF");
1530 tor_assert(r);
1532 r = BN_set_word(g, 2);
1533 tor_assert(r);
1534 dh_param_p = p;
1535 dh_param_g = g;
1538 #define DH_PRIVATE_KEY_BITS 320
1540 /** Allocate and return a new DH object for a key exchange.
1542 crypto_dh_env_t *
1543 crypto_dh_new(void)
1545 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1547 if (!dh_param_p)
1548 init_dh_param();
1550 if (!(res->dh = DH_new()))
1551 goto err;
1553 if (!(res->dh->p = BN_dup(dh_param_p)))
1554 goto err;
1556 if (!(res->dh->g = BN_dup(dh_param_g)))
1557 goto err;
1559 res->dh->length = DH_PRIVATE_KEY_BITS;
1561 return res;
1562 err:
1563 crypto_log_errors(LOG_WARN, "creating DH object");
1564 if (res->dh) DH_free(res->dh); /* frees p and g too */
1565 tor_free(res);
1566 return NULL;
1569 /** Return the length of the DH key in <b>dh</b>, in bytes.
1572 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1574 tor_assert(dh);
1575 return DH_size(dh->dh);
1578 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1579 * success, -1 on failure.
1582 crypto_dh_generate_public(crypto_dh_env_t *dh)
1584 again:
1585 if (!DH_generate_key(dh->dh)) {
1586 crypto_log_errors(LOG_WARN, "generating DH key");
1587 return -1;
1589 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1590 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1591 "the-universe chances really do happen. Trying again.");
1592 /* Free and clear the keys, so OpenSSL will actually try again. */
1593 BN_free(dh->dh->pub_key);
1594 BN_free(dh->dh->priv_key);
1595 dh->dh->pub_key = dh->dh->priv_key = NULL;
1596 goto again;
1598 return 0;
1601 /** Generate g^x as necessary, and write the g^x for the key exchange
1602 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1603 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1606 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1608 int bytes;
1609 tor_assert(dh);
1610 if (!dh->dh->pub_key) {
1611 if (crypto_dh_generate_public(dh)<0)
1612 return -1;
1615 tor_assert(dh->dh->pub_key);
1616 bytes = BN_num_bytes(dh->dh->pub_key);
1617 tor_assert(bytes >= 0);
1618 if (pubkey_len < (size_t)bytes) {
1619 log_warn(LD_CRYPTO,
1620 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1621 (int) pubkey_len, bytes);
1622 return -1;
1625 memset(pubkey, 0, pubkey_len);
1626 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1628 return 0;
1631 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1632 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1633 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1635 static int
1636 tor_check_dh_key(BIGNUM *bn)
1638 BIGNUM *x;
1639 char *s;
1640 tor_assert(bn);
1641 x = BN_new();
1642 tor_assert(x);
1643 if (!dh_param_p)
1644 init_dh_param();
1645 BN_set_word(x, 1);
1646 if (BN_cmp(bn,x)<=0) {
1647 log_warn(LD_CRYPTO, "DH key must be at least 2.");
1648 goto err;
1650 BN_copy(x,dh_param_p);
1651 BN_sub_word(x, 1);
1652 if (BN_cmp(bn,x)>=0) {
1653 log_warn(LD_CRYPTO, "DH key must be at most p-2.");
1654 goto err;
1656 BN_free(x);
1657 return 0;
1658 err:
1659 BN_free(x);
1660 s = BN_bn2hex(bn);
1661 log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1662 OPENSSL_free(s);
1663 return -1;
1666 #undef MIN
1667 #define MIN(a,b) ((a)<(b)?(a):(b))
1668 /** Given a DH key exchange object, and our peer's value of g^y (as a
1669 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1670 * <b>secret_bytes_out</b> bytes of shared key material and write them
1671 * to <b>secret_out</b>. Return the number of bytes generated on success,
1672 * or -1 on failure.
1674 * (We generate key material by computing
1675 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1676 * where || is concatenation.)
1678 ssize_t
1679 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1680 const char *pubkey, size_t pubkey_len,
1681 char *secret_out, size_t secret_bytes_out)
1683 char *secret_tmp = NULL;
1684 BIGNUM *pubkey_bn = NULL;
1685 size_t secret_len=0;
1686 int result=0;
1687 tor_assert(dh);
1688 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1689 tor_assert(pubkey_len < INT_MAX);
1691 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1692 (int)pubkey_len, NULL)))
1693 goto error;
1694 if (tor_check_dh_key(pubkey_bn)<0) {
1695 /* Check for invalid public keys. */
1696 log_warn(LD_CRYPTO,"Rejected invalid g^x");
1697 goto error;
1699 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1700 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1701 if (result < 0) {
1702 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1703 goto error;
1705 secret_len = result;
1706 if (crypto_expand_key_material(secret_tmp, secret_len,
1707 secret_out, secret_bytes_out)<0)
1708 goto error;
1709 secret_len = secret_bytes_out;
1711 goto done;
1712 error:
1713 result = -1;
1714 done:
1715 crypto_log_errors(LOG_WARN, "completing DH handshake");
1716 if (pubkey_bn)
1717 BN_free(pubkey_bn);
1718 tor_free(secret_tmp);
1719 if (result < 0)
1720 return result;
1721 else
1722 return secret_len;
1725 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1726 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1727 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1728 * H(K | [00]) | H(K | [01]) | ....
1730 * Return 0 on success, -1 on failure.
1733 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1734 char *key_out, size_t key_out_len)
1736 int i;
1737 char *cp, *tmp = tor_malloc(key_in_len+1);
1738 char digest[DIGEST_LEN];
1740 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1741 tor_assert(key_out_len <= DIGEST_LEN*256);
1743 memcpy(tmp, key_in, key_in_len);
1744 for (cp = key_out, i=0; cp < key_out+key_out_len;
1745 ++i, cp += DIGEST_LEN) {
1746 tmp[key_in_len] = i;
1747 if (crypto_digest(digest, tmp, key_in_len+1))
1748 goto err;
1749 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1751 memset(tmp, 0, key_in_len+1);
1752 tor_free(tmp);
1753 memset(digest, 0, sizeof(digest));
1754 return 0;
1756 err:
1757 memset(tmp, 0, key_in_len+1);
1758 tor_free(tmp);
1759 memset(digest, 0, sizeof(digest));
1760 return -1;
1763 /** Free a DH key exchange object.
1765 void
1766 crypto_dh_free(crypto_dh_env_t *dh)
1768 tor_assert(dh);
1769 tor_assert(dh->dh);
1770 DH_free(dh->dh);
1771 tor_free(dh);
1774 /* random numbers */
1776 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1777 * work for us too. */
1778 #define ADD_ENTROPY 32
1780 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1781 "release".) */
1782 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1784 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1785 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1786 * that fd without checking whether it fit in the fd_set. Thus, if the
1787 * system has not just been started up, it is unsafe to call */
1788 #define RAND_POLL_IS_SAFE \
1789 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1790 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1791 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1793 /** Seed OpenSSL's random number generator with bytes from the operating
1794 * system. <b>startup</b> should be true iff we have just started Tor and
1795 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1798 crypto_seed_rng(int startup)
1800 char buf[ADD_ENTROPY];
1801 int rand_poll_status = 0;
1803 /* local variables */
1804 #ifdef MS_WINDOWS
1805 static int provider_set = 0;
1806 static HCRYPTPROV provider;
1807 #else
1808 static const char *filenames[] = {
1809 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1811 int fd, i;
1812 size_t n;
1813 #endif
1815 #if HAVE_RAND_POLL
1816 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1817 * entropy than we do. We'll try calling that, *and* calling our own entropy
1818 * functions. If one succeeds, we'll accept the RNG as seeded. */
1819 if (startup || RAND_POLL_IS_SAFE) {
1820 rand_poll_status = RAND_poll();
1821 if (rand_poll_status == 0)
1822 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1824 #endif
1826 #ifdef MS_WINDOWS
1827 if (!provider_set) {
1828 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1829 CRYPT_VERIFYCONTEXT)) {
1830 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1831 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1832 return rand_poll_status ? 0 : -1;
1835 provider_set = 1;
1837 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1838 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1839 return rand_poll_status ? 0 : -1;
1841 RAND_seed(buf, sizeof(buf));
1842 memset(buf, 0, sizeof(buf));
1843 return 0;
1844 #else
1845 for (i = 0; filenames[i]; ++i) {
1846 fd = open(filenames[i], O_RDONLY, 0);
1847 if (fd<0) continue;
1848 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1849 n = read_all(fd, buf, sizeof(buf), 0);
1850 close(fd);
1851 if (n != sizeof(buf)) {
1852 log_warn(LD_CRYPTO,
1853 "Error reading from entropy source (read only %lu bytes).",
1854 (unsigned long)n);
1855 return -1;
1857 RAND_seed(buf, (int)sizeof(buf));
1858 memset(buf, 0, sizeof(buf));
1859 return 0;
1862 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1863 return rand_poll_status ? 0 : -1;
1864 #endif
1867 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1868 * success, -1 on failure.
1871 crypto_rand(char *to, size_t n)
1873 int r;
1874 tor_assert(n < INT_MAX);
1875 tor_assert(to);
1876 r = RAND_bytes((unsigned char*)to, (int)n);
1877 if (r == 0)
1878 crypto_log_errors(LOG_WARN, "generating random data");
1879 return (r == 1) ? 0 : -1;
1882 /** Return a pseudorandom integer, chosen uniformly from the values
1883 * between 0 and <b>max</b>-1. */
1885 crypto_rand_int(unsigned int max)
1887 unsigned int val;
1888 unsigned int cutoff;
1889 tor_assert(max < UINT_MAX);
1890 tor_assert(max > 0); /* don't div by 0 */
1892 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1893 * distribution with clipping at the upper end of unsigned int's
1894 * range.
1896 cutoff = UINT_MAX - (UINT_MAX%max);
1897 while (1) {
1898 crypto_rand((char*)&val, sizeof(val));
1899 if (val < cutoff)
1900 return val % max;
1904 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1905 * between 0 and <b>max</b>-1. */
1906 uint64_t
1907 crypto_rand_uint64(uint64_t max)
1909 uint64_t val;
1910 uint64_t cutoff;
1911 tor_assert(max < UINT64_MAX);
1912 tor_assert(max > 0); /* don't div by 0 */
1914 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1915 * distribution with clipping at the upper end of unsigned int's
1916 * range.
1918 cutoff = UINT64_MAX - (UINT64_MAX%max);
1919 while (1) {
1920 crypto_rand((char*)&val, sizeof(val));
1921 if (val < cutoff)
1922 return val % max;
1926 /** Generate and return a new random hostname starting with <b>prefix</b>,
1927 * ending with <b>suffix</b>, and containing no less than
1928 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1929 * characters between. */
1930 char *
1931 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
1932 const char *suffix)
1934 char *result, *rand_bytes;
1935 int randlen, rand_bytes_len;
1936 size_t resultlen, prefixlen;
1938 tor_assert(max_rand_len >= min_rand_len);
1939 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
1940 prefixlen = strlen(prefix);
1941 resultlen = prefixlen + strlen(suffix) + randlen + 16;
1943 rand_bytes_len = ((randlen*5)+7)/8;
1944 if (rand_bytes_len % 5)
1945 rand_bytes_len += 5 - (rand_bytes_len%5);
1946 rand_bytes = tor_malloc(rand_bytes_len);
1947 crypto_rand(rand_bytes, rand_bytes_len);
1949 result = tor_malloc(resultlen);
1950 memcpy(result, prefix, prefixlen);
1951 base32_encode(result+prefixlen, resultlen-prefixlen,
1952 rand_bytes, rand_bytes_len);
1953 tor_free(rand_bytes);
1954 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
1956 return result;
1959 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1960 * is empty. */
1961 void *
1962 smartlist_choose(const smartlist_t *sl)
1964 int len = smartlist_len(sl);
1965 if (len)
1966 return smartlist_get(sl,crypto_rand_int(len));
1967 return NULL; /* no elements to choose from */
1970 /** Scramble the elements of <b>sl</b> into a random order. */
1971 void
1972 smartlist_shuffle(smartlist_t *sl)
1974 int i;
1975 /* From the end of the list to the front, choose at random from the
1976 positions we haven't looked at yet, and swap that position into the
1977 current position. Remember to give "no swap" the same probability as
1978 any other swap. */
1979 for (i = smartlist_len(sl)-1; i > 0; --i) {
1980 int j = crypto_rand_int(i+1);
1981 smartlist_swap(sl, i, j);
1985 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1986 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1987 * bytes. Return the number of bytes written on success; -1 if
1988 * destlen is too short, or other failure.
1991 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1993 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1994 * it ever shows up in the profile. */
1995 EVP_ENCODE_CTX ctx;
1996 int len, ret;
1997 tor_assert(srclen < INT_MAX);
1999 /* 48 bytes of input -> 64 bytes of output plus newline.
2000 Plus one more byte, in case I'm wrong.
2002 if (destlen < ((srclen/48)+1)*66)
2003 return -1;
2004 if (destlen > SIZE_T_CEILING)
2005 return -1;
2007 EVP_EncodeInit(&ctx);
2008 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2009 (unsigned char*)src, (int)srclen);
2010 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2011 ret += len;
2012 return ret;
2015 #define X 255
2016 #define SP 64
2017 #define PAD 65
2018 /** Internal table mapping byte values to what they represent in base64.
2019 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2020 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2021 * end-of-string. */
2022 static const uint8_t base64_decode_table[256] = {
2023 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2024 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2025 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2026 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2027 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2028 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2029 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2030 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2031 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2032 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2033 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2034 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2035 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2036 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2037 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2038 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2041 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2042 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2043 * bytes. Return the number of bytes written on success; -1 if
2044 * destlen is too short, or other failure.
2046 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2047 * spaces or padding.
2049 * NOTE 2: This implementation does not check for the correct number of
2050 * padding "=" characters at the end of the string, and does not check
2051 * for internal padding characters.
2054 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2056 #ifdef USE_OPENSSL_BASE64
2057 EVP_ENCODE_CTX ctx;
2058 int len, ret;
2059 /* 64 bytes of input -> *up to* 48 bytes of output.
2060 Plus one more byte, in case I'm wrong.
2062 if (destlen < ((srclen/64)+1)*49)
2063 return -1;
2064 if (destlen > SIZE_T_CEILING)
2065 return -1;
2067 EVP_DecodeInit(&ctx);
2068 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2069 (unsigned char*)src, srclen);
2070 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2071 ret += len;
2072 return ret;
2073 #else
2074 const char *eos = src+srclen;
2075 uint32_t n=0;
2076 int n_idx=0;
2077 char *dest_orig = dest;
2079 /* Max number of bits == srclen*6.
2080 * Number of bytes required to hold all bits == (srclen*6)/8.
2081 * Yes, we want to round down: anything that hangs over the end of a
2082 * byte is padding. */
2083 if (destlen < (srclen*3)/4)
2084 return -1;
2085 if (destlen > SIZE_T_CEILING)
2086 return -1;
2088 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2089 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2090 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2092 for ( ; src < eos; ++src) {
2093 unsigned char c = (unsigned char) *src;
2094 uint8_t v = base64_decode_table[c];
2095 switch (v) {
2096 case X:
2097 /* This character isn't allowed in base64. */
2098 return -1;
2099 case SP:
2100 /* This character is whitespace, and has no effect. */
2101 continue;
2102 case PAD:
2103 /* We've hit an = character: the data is over. */
2104 goto end_of_loop;
2105 default:
2106 /* We have an actual 6-bit value. Append it to the bits in n. */
2107 n = (n<<6) | v;
2108 if ((++n_idx) == 4) {
2109 /* We've accumulated 24 bits in n. Flush them. */
2110 *dest++ = (n>>16);
2111 *dest++ = (n>>8) & 0xff;
2112 *dest++ = (n) & 0xff;
2113 n_idx = 0;
2114 n = 0;
2118 end_of_loop:
2119 /* If we have leftover bits, we need to cope. */
2120 switch (n_idx) {
2121 case 0:
2122 default:
2123 /* No leftover bits. We win. */
2124 break;
2125 case 1:
2126 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2127 return -1;
2128 case 2:
2129 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2130 *dest++ = n >> 4;
2131 break;
2132 case 3:
2133 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2134 *dest++ = n >> 10;
2135 *dest++ = n >> 2;
2138 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2139 tor_assert((dest-dest_orig) <= INT_MAX);
2141 return (int)(dest-dest_orig);
2142 #endif
2144 #undef X
2145 #undef SP
2146 #undef PAD
2148 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2149 * and newline characters, and store the nul-terminated result in the first
2150 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2152 digest_to_base64(char *d64, const char *digest)
2154 char buf[256];
2155 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2156 buf[BASE64_DIGEST_LEN] = '\0';
2157 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2158 return 0;
2161 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2162 * trailing newline or = characters), decode it and store the result in the
2163 * first DIGEST_LEN bytes at <b>digest</b>. */
2165 digest_from_base64(char *digest, const char *d64)
2167 #ifdef USE_OPENSSL_BASE64
2168 char buf_in[BASE64_DIGEST_LEN+3];
2169 char buf[256];
2170 if (strlen(d64) != BASE64_DIGEST_LEN)
2171 return -1;
2172 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2173 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2174 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2175 return -1;
2176 memcpy(digest, buf, DIGEST_LEN);
2177 return 0;
2178 #else
2179 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2180 return 0;
2181 else
2182 return -1;
2183 #endif
2186 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2187 * that srclen*8 is a multiple of 5.
2189 void
2190 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2192 unsigned int i, bit, v, u;
2193 size_t nbits = srclen * 8;
2195 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2196 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2197 tor_assert(destlen < SIZE_T_CEILING);
2199 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2200 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2201 v = ((uint8_t)src[bit/8]) << 8;
2202 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2203 /* set u to the 5-bit value at the bit'th bit of src. */
2204 u = (v >> (11-(bit%8))) & 0x1F;
2205 dest[i] = BASE32_CHARS[u];
2207 dest[i] = '\0';
2210 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2211 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2214 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2216 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2217 * it ever shows up in the profile. */
2218 unsigned int i, j, bit;
2219 size_t nbits;
2220 char *tmp;
2221 nbits = srclen * 5;
2223 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2224 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2225 tor_assert(destlen < SIZE_T_CEILING);
2227 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2228 tmp = tor_malloc_zero(srclen);
2229 for (j = 0; j < srclen; ++j) {
2230 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2231 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2232 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2233 else {
2234 log_warn(LD_BUG, "illegal character in base32 encoded string");
2235 tor_free(tmp);
2236 return -1;
2240 /* Assemble result byte-wise by applying five possible cases. */
2241 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2242 switch (bit % 40) {
2243 case 0:
2244 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2245 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2246 break;
2247 case 8:
2248 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2249 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2250 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2251 break;
2252 case 16:
2253 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2254 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2255 break;
2256 case 24:
2257 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2258 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2259 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2260 break;
2261 case 32:
2262 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2263 ((uint8_t)tmp[(bit/5)+1]);
2264 break;
2268 memset(tmp, 0, srclen);
2269 tor_free(tmp);
2270 tmp = NULL;
2271 return 0;
2274 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2275 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2276 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2277 * are a salt; the 9th byte describes how much iteration to do.
2278 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2280 void
2281 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2282 size_t secret_len, const char *s2k_specifier)
2284 crypto_digest_env_t *d;
2285 uint8_t c;
2286 size_t count, tmplen;
2287 char *tmp;
2288 tor_assert(key_out_len < SIZE_T_CEILING);
2290 #define EXPBIAS 6
2291 c = s2k_specifier[8];
2292 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2293 #undef EXPBIAS
2295 tor_assert(key_out_len <= DIGEST_LEN);
2297 d = crypto_new_digest_env();
2298 tmplen = 8+secret_len;
2299 tmp = tor_malloc(tmplen);
2300 memcpy(tmp,s2k_specifier,8);
2301 memcpy(tmp+8,secret,secret_len);
2302 secret_len += 8;
2303 while (count) {
2304 if (count >= secret_len) {
2305 crypto_digest_add_bytes(d, tmp, secret_len);
2306 count -= secret_len;
2307 } else {
2308 crypto_digest_add_bytes(d, tmp, count);
2309 count = 0;
2312 crypto_digest_get_digest(d, key_out, key_out_len);
2313 memset(tmp, 0, tmplen);
2314 tor_free(tmp);
2315 crypto_free_digest_env(d);
2318 #ifdef TOR_IS_MULTITHREADED
2319 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2320 static void
2321 _openssl_locking_cb(int mode, int n, const char *file, int line)
2323 (void)file;
2324 (void)line;
2325 if (!_openssl_mutexes)
2326 /* This is not a really good fix for the
2327 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2328 * it can't hurt. */
2329 return;
2330 if (mode & CRYPTO_LOCK)
2331 tor_mutex_acquire(_openssl_mutexes[n]);
2332 else
2333 tor_mutex_release(_openssl_mutexes[n]);
2336 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2337 * as a lock. */
2338 struct CRYPTO_dynlock_value {
2339 tor_mutex_t *lock;
2342 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2343 * documentation in OpenSSL's docs for more info. */
2344 static struct CRYPTO_dynlock_value *
2345 _openssl_dynlock_create_cb(const char *file, int line)
2347 struct CRYPTO_dynlock_value *v;
2348 (void)file;
2349 (void)line;
2350 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2351 v->lock = tor_mutex_new();
2352 return v;
2355 /** OpenSSL callback function to acquire or release a lock: see
2356 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2357 static void
2358 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2359 const char *file, int line)
2361 (void)file;
2362 (void)line;
2363 if (mode & CRYPTO_LOCK)
2364 tor_mutex_acquire(v->lock);
2365 else
2366 tor_mutex_release(v->lock);
2369 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2370 * documentation in OpenSSL's docs for more info. */
2371 static void
2372 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2373 const char *file, int line)
2375 (void)file;
2376 (void)line;
2377 tor_mutex_free(v->lock);
2378 tor_free(v);
2381 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2382 * multithreaded. */
2383 static int
2384 setup_openssl_threading(void)
2386 int i;
2387 int n = CRYPTO_num_locks();
2388 _n_openssl_mutexes = n;
2389 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2390 for (i=0; i < n; ++i)
2391 _openssl_mutexes[i] = tor_mutex_new();
2392 CRYPTO_set_locking_callback(_openssl_locking_cb);
2393 CRYPTO_set_id_callback(tor_get_thread_id);
2394 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2395 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2396 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2397 return 0;
2399 #else
2400 static int
2401 setup_openssl_threading(void)
2403 return 0;
2405 #endif