Clean up Section 1 of rend-spec.txt.
[tor/rransom.git] / src / common / crypto.c
blobbfb81d3ccdd644eb25542bc723a341f61008406f
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-2010, 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;
409 if (env->key)
410 RSA_free(env->key);
412 tor_free(env);
415 /** Create a new symmetric cipher for a given key and encryption flag
416 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
417 * on failure.
419 crypto_cipher_env_t *
420 crypto_create_init_cipher(const char *key, int encrypt_mode)
422 int r;
423 crypto_cipher_env_t *crypto = NULL;
425 if (! (crypto = crypto_new_cipher_env())) {
426 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
427 return NULL;
430 crypto_cipher_set_key(crypto, key);
432 if (encrypt_mode)
433 r = crypto_cipher_encrypt_init_cipher(crypto);
434 else
435 r = crypto_cipher_decrypt_init_cipher(crypto);
437 if (r)
438 goto error;
439 return crypto;
441 error:
442 if (crypto)
443 crypto_free_cipher_env(crypto);
444 return NULL;
447 /** Allocate and return a new symmetric cipher.
449 crypto_cipher_env_t *
450 crypto_new_cipher_env(void)
452 crypto_cipher_env_t *env;
454 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
455 env->cipher = aes_new_cipher();
456 return env;
459 /** Free a symmetric cipher.
461 void
462 crypto_free_cipher_env(crypto_cipher_env_t *env)
464 if (!env)
465 return;
467 tor_assert(env->cipher);
468 aes_free_cipher(env->cipher);
469 memset(env, 0, sizeof(crypto_cipher_env_t));
470 tor_free(env);
473 /* public key crypto */
475 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
476 * Return 0 on success, -1 on failure.
479 crypto_pk_generate_key_with_bits(crypto_pk_env_t *env, int bits)
481 tor_assert(env);
483 if (env->key)
484 RSA_free(env->key);
485 #if OPENSSL_VERSION_NUMBER < 0x00908000l
486 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
487 env->key = RSA_generate_key(bits, 65537, NULL, NULL);
488 #else
489 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
491 BIGNUM *e = BN_new();
492 RSA *r = NULL;
493 if (!e)
494 goto done;
495 if (! BN_set_word(e, 65537))
496 goto done;
497 r = RSA_new();
498 if (!r)
499 goto done;
500 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
501 goto done;
503 env->key = r;
504 r = NULL;
505 done:
506 if (e)
507 BN_free(e);
508 if (r)
509 RSA_free(r);
511 #endif
512 if (!env->key) {
513 crypto_log_errors(LOG_WARN, "generating RSA key");
514 return -1;
517 return 0;
520 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
521 * Return 0 on success, -1 on failure.
523 /* Used here, and used for testing. */
525 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
526 const char *s)
528 BIO *b;
530 tor_assert(env);
531 tor_assert(s);
533 /* Create a read-only memory BIO, backed by the NUL-terminated string 's' */
534 b = BIO_new_mem_buf((char*)s, -1);
536 if (env->key)
537 RSA_free(env->key);
539 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
541 BIO_free(b);
543 if (!env->key) {
544 crypto_log_errors(LOG_WARN, "Error parsing private key");
545 return -1;
547 return 0;
550 /** Read a PEM-encoded private key from the file named by
551 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
554 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
555 const char *keyfile)
557 char *contents;
558 int r;
560 /* Read the file into a string. */
561 contents = read_file_to_str(keyfile, 0, NULL);
562 if (!contents) {
563 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
564 return -1;
567 /* Try to parse it. */
568 r = crypto_pk_read_private_key_from_string(env, contents);
569 tor_free(contents);
570 if (r)
571 return -1; /* read_private_key_from_string already warned, so we don't.*/
573 /* Make sure it's valid. */
574 if (crypto_pk_check_key(env) <= 0)
575 return -1;
577 return 0;
580 /** Helper function to implement crypto_pk_write_*_key_to_string. */
581 static int
582 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
583 size_t *len, int is_public)
585 BUF_MEM *buf;
586 BIO *b;
587 int r;
589 tor_assert(env);
590 tor_assert(env->key);
591 tor_assert(dest);
593 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
595 /* Now you can treat b as if it were a file. Just use the
596 * PEM_*_bio_* functions instead of the non-bio variants.
598 if (is_public)
599 r = PEM_write_bio_RSAPublicKey(b, env->key);
600 else
601 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
603 if (!r) {
604 crypto_log_errors(LOG_WARN, "writing RSA key to string");
605 BIO_free(b);
606 return -1;
609 BIO_get_mem_ptr(b, &buf);
610 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
611 BIO_free(b);
613 *dest = tor_malloc(buf->length+1);
614 memcpy(*dest, buf->data, buf->length);
615 (*dest)[buf->length] = 0; /* nul terminate it */
616 *len = buf->length;
617 BUF_MEM_free(buf);
619 return 0;
622 /** PEM-encode the public key portion of <b>env</b> and write it to a
623 * newly allocated string. On success, set *<b>dest</b> to the new
624 * string, *<b>len</b> to the string's length, and return 0. On
625 * failure, return -1.
628 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
629 size_t *len)
631 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
634 /** PEM-encode the private key portion of <b>env</b> and write it to a
635 * newly allocated string. On success, set *<b>dest</b> to the new
636 * string, *<b>len</b> to the string's length, and return 0. On
637 * failure, return -1.
640 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
641 size_t *len)
643 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
646 /** Read a PEM-encoded public key from the first <b>len</b> characters of
647 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
648 * failure.
651 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
652 size_t len)
654 BIO *b;
656 tor_assert(env);
657 tor_assert(src);
658 tor_assert(len<INT_MAX);
660 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
662 BIO_write(b, src, (int)len);
664 if (env->key)
665 RSA_free(env->key);
666 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
667 BIO_free(b);
668 if (!env->key) {
669 crypto_log_errors(LOG_WARN, "reading public key from string");
670 return -1;
673 return 0;
676 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
677 * PEM-encoded. Return 0 on success, -1 on failure.
680 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
681 const char *fname)
683 BIO *bio;
684 char *cp;
685 long len;
686 char *s;
687 int r;
689 tor_assert(PRIVATE_KEY_OK(env));
691 if (!(bio = BIO_new(BIO_s_mem())))
692 return -1;
693 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
694 == 0) {
695 crypto_log_errors(LOG_WARN, "writing private key");
696 BIO_free(bio);
697 return -1;
699 len = BIO_get_mem_data(bio, &cp);
700 tor_assert(len >= 0);
701 s = tor_malloc(len+1);
702 memcpy(s, cp, len);
703 s[len]='\0';
704 r = write_str_to_file(fname, s, 0);
705 BIO_free(bio);
706 tor_free(s);
707 return r;
710 /** Return true iff <b>env</b> has a valid key.
713 crypto_pk_check_key(crypto_pk_env_t *env)
715 int r;
716 tor_assert(env);
718 r = RSA_check_key(env->key);
719 if (r <= 0)
720 crypto_log_errors(LOG_WARN,"checking RSA key");
721 return r;
724 /** Return true iff <b>key</b> contains the private-key portion of the RSA
725 * key. */
727 crypto_pk_key_is_private(const crypto_pk_env_t *key)
729 tor_assert(key);
730 return PRIVATE_KEY_OK(key);
733 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
734 * if a==b, and 1 if a\>b.
737 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
739 int result;
741 if (!a || !b)
742 return -1;
744 if (!a->key || !b->key)
745 return -1;
747 tor_assert(PUBLIC_KEY_OK(a));
748 tor_assert(PUBLIC_KEY_OK(b));
749 result = BN_cmp((a->key)->n, (b->key)->n);
750 if (result)
751 return result;
752 return BN_cmp((a->key)->e, (b->key)->e);
755 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
756 size_t
757 crypto_pk_keysize(crypto_pk_env_t *env)
759 tor_assert(env);
760 tor_assert(env->key);
762 return (size_t) RSA_size(env->key);
765 /** Increase the reference count of <b>env</b>, and return it.
767 crypto_pk_env_t *
768 crypto_pk_dup_key(crypto_pk_env_t *env)
770 tor_assert(env);
771 tor_assert(env->key);
773 env->refs++;
774 return env;
777 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
778 crypto_pk_env_t *
779 crypto_pk_copy_full(crypto_pk_env_t *env)
781 RSA *new_key;
782 int privatekey = 0;
783 tor_assert(env);
784 tor_assert(env->key);
786 if (PRIVATE_KEY_OK(env)) {
787 new_key = RSAPrivateKey_dup(env->key);
788 privatekey = 1;
789 } else {
790 new_key = RSAPublicKey_dup(env->key);
792 if (!new_key) {
793 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
794 privatekey?"private":"public");
795 crypto_log_errors(LOG_ERR,
796 privatekey ? "Duplicating a private key" :
797 "Duplicating a public key");
798 tor_fragile_assert();
799 return NULL;
802 return _crypto_new_pk_env_rsa(new_key);
805 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
806 * in <b>env</b>, using the padding method <b>padding</b>. On success,
807 * write the result to <b>to</b>, and return the number of bytes
808 * written. On failure, return -1.
811 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
812 const char *from, size_t fromlen, int padding)
814 int r;
815 tor_assert(env);
816 tor_assert(from);
817 tor_assert(to);
818 tor_assert(fromlen<INT_MAX);
820 r = RSA_public_encrypt((int)fromlen,
821 (unsigned char*)from, (unsigned char*)to,
822 env->key, crypto_get_rsa_padding(padding));
823 if (r<0) {
824 crypto_log_errors(LOG_WARN, "performing RSA encryption");
825 return -1;
827 return r;
830 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
831 * in <b>env</b>, using the padding method <b>padding</b>. On success,
832 * write the result to <b>to</b>, and return the number of bytes
833 * written. On failure, return -1.
836 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
837 const char *from, size_t fromlen,
838 int padding, int warnOnFailure)
840 int r;
841 tor_assert(env);
842 tor_assert(from);
843 tor_assert(to);
844 tor_assert(env->key);
845 tor_assert(fromlen<INT_MAX);
846 if (!env->key->p)
847 /* Not a private key */
848 return -1;
850 r = RSA_private_decrypt((int)fromlen,
851 (unsigned char*)from, (unsigned char*)to,
852 env->key, crypto_get_rsa_padding(padding));
854 if (r<0) {
855 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
856 "performing RSA decryption");
857 return -1;
859 return r;
862 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
863 * public key in <b>env</b>, using PKCS1 padding. On success, write the
864 * signed data to <b>to</b>, and return the number of bytes written.
865 * On failure, return -1.
868 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
869 const char *from, size_t fromlen)
871 int r;
872 tor_assert(env);
873 tor_assert(from);
874 tor_assert(to);
875 tor_assert(fromlen < INT_MAX);
876 r = RSA_public_decrypt((int)fromlen,
877 (unsigned char*)from, (unsigned char*)to,
878 env->key, RSA_PKCS1_PADDING);
880 if (r<0) {
881 crypto_log_errors(LOG_WARN, "checking RSA signature");
882 return -1;
884 return r;
887 /** Check a siglen-byte long signature at <b>sig</b> against
888 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
889 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
890 * SHA1(data). Else return -1.
893 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
894 size_t datalen, const char *sig, size_t siglen)
896 char digest[DIGEST_LEN];
897 char *buf;
898 int r;
900 tor_assert(env);
901 tor_assert(data);
902 tor_assert(sig);
904 if (crypto_digest(digest,data,datalen)<0) {
905 log_warn(LD_BUG, "couldn't compute digest");
906 return -1;
908 buf = tor_malloc(crypto_pk_keysize(env)+1);
909 r = crypto_pk_public_checksig(env,buf,sig,siglen);
910 if (r != DIGEST_LEN) {
911 log_warn(LD_CRYPTO, "Invalid signature");
912 tor_free(buf);
913 return -1;
915 if (memcmp(buf, digest, DIGEST_LEN)) {
916 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
917 tor_free(buf);
918 return -1;
920 tor_free(buf);
922 return 0;
925 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
926 * <b>env</b>, using PKCS1 padding. On success, write the signature to
927 * <b>to</b>, and return the number of bytes written. On failure, return
928 * -1.
931 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
932 const char *from, size_t fromlen)
934 int r;
935 tor_assert(env);
936 tor_assert(from);
937 tor_assert(to);
938 tor_assert(fromlen < INT_MAX);
939 if (!env->key->p)
940 /* Not a private key */
941 return -1;
943 r = RSA_private_encrypt((int)fromlen,
944 (unsigned char*)from, (unsigned char*)to,
945 env->key, RSA_PKCS1_PADDING);
946 if (r<0) {
947 crypto_log_errors(LOG_WARN, "generating RSA signature");
948 return -1;
950 return r;
953 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
954 * <b>from</b>; sign the data with the private key in <b>env</b>, and
955 * store it in <b>to</b>. Return the number of bytes written on
956 * success, and -1 on failure.
959 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
960 const char *from, size_t fromlen)
962 int r;
963 char digest[DIGEST_LEN];
964 if (crypto_digest(digest,from,fromlen)<0)
965 return -1;
966 r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
967 memset(digest, 0, sizeof(digest));
968 return r;
971 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
972 * bytes of data from <b>from</b>, with padding type 'padding',
973 * storing the results on <b>to</b>.
975 * If no padding is used, the public key must be at least as large as
976 * <b>from</b>.
978 * Returns the number of bytes written on success, -1 on failure.
980 * The encrypted data consists of:
981 * - The source data, padded and encrypted with the public key, if the
982 * padded source data is no longer than the public key, and <b>force</b>
983 * is false, OR
984 * - The beginning of the source data prefixed with a 16-byte symmetric key,
985 * padded and encrypted with the public key; followed by the rest of
986 * the source data encrypted in AES-CTR mode with the symmetric key.
989 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
990 char *to,
991 const char *from,
992 size_t fromlen,
993 int padding, int force)
995 int overhead, outlen, r;
996 size_t pkeylen, symlen;
997 crypto_cipher_env_t *cipher = NULL;
998 char *buf = NULL;
1000 tor_assert(env);
1001 tor_assert(from);
1002 tor_assert(to);
1004 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1005 pkeylen = crypto_pk_keysize(env);
1007 if (padding == PK_NO_PADDING && fromlen < pkeylen)
1008 return -1;
1010 if (!force && fromlen+overhead <= pkeylen) {
1011 /* It all fits in a single encrypt. */
1012 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
1014 cipher = crypto_new_cipher_env();
1015 if (!cipher) return -1;
1016 if (crypto_cipher_generate_key(cipher)<0)
1017 goto err;
1018 /* You can't just run around RSA-encrypting any bitstream: if it's
1019 * greater than the RSA key, then OpenSSL will happily encrypt, and
1020 * later decrypt to the wrong value. So we set the first bit of
1021 * 'cipher->key' to 0 if we aren't padding. This means that our
1022 * symmetric key is really only 127 bits.
1024 if (padding == PK_NO_PADDING)
1025 cipher->key[0] &= 0x7f;
1026 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
1027 goto err;
1028 buf = tor_malloc(pkeylen+1);
1029 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1030 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1032 /* Length of symmetrically encrypted data. */
1033 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1035 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
1036 if (outlen!=(int)pkeylen) {
1037 goto err;
1039 r = crypto_cipher_encrypt(cipher, to+outlen,
1040 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1042 if (r<0) goto err;
1043 memset(buf, 0, pkeylen);
1044 tor_free(buf);
1045 crypto_free_cipher_env(cipher);
1046 tor_assert(outlen+symlen < INT_MAX);
1047 return (int)(outlen + symlen);
1048 err:
1049 if (buf) {
1050 memset(buf, 0, pkeylen);
1051 tor_free(buf);
1053 if (cipher) crypto_free_cipher_env(cipher);
1054 return -1;
1057 /** Invert crypto_pk_public_hybrid_encrypt. */
1059 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1060 char *to,
1061 const char *from,
1062 size_t fromlen,
1063 int padding, int warnOnFailure)
1065 int outlen, r;
1066 size_t pkeylen;
1067 crypto_cipher_env_t *cipher = NULL;
1068 char *buf = NULL;
1070 pkeylen = crypto_pk_keysize(env);
1072 if (fromlen <= pkeylen) {
1073 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
1074 warnOnFailure);
1076 buf = tor_malloc(pkeylen+1);
1077 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
1078 warnOnFailure);
1079 if (outlen<0) {
1080 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1081 "Error decrypting public-key data");
1082 goto err;
1084 if (outlen < CIPHER_KEY_LEN) {
1085 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1086 "No room for a symmetric key");
1087 goto err;
1089 cipher = crypto_create_init_cipher(buf, 0);
1090 if (!cipher) {
1091 goto err;
1093 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1094 outlen -= CIPHER_KEY_LEN;
1095 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1096 if (r<0)
1097 goto err;
1098 memset(buf,0,pkeylen);
1099 tor_free(buf);
1100 crypto_free_cipher_env(cipher);
1101 tor_assert(outlen + fromlen < INT_MAX);
1102 return (int)(outlen + (fromlen-pkeylen));
1103 err:
1104 memset(buf,0,pkeylen);
1105 tor_free(buf);
1106 if (cipher) crypto_free_cipher_env(cipher);
1107 return -1;
1110 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1111 * Return -1 on error, or the number of characters used on success.
1114 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1116 int len;
1117 unsigned char *buf, *cp;
1118 len = i2d_RSAPublicKey(pk->key, NULL);
1119 if (len < 0 || (size_t)len > dest_len)
1120 return -1;
1121 cp = buf = tor_malloc(len+1);
1122 len = i2d_RSAPublicKey(pk->key, &cp);
1123 if (len < 0) {
1124 crypto_log_errors(LOG_WARN,"encoding public key");
1125 tor_free(buf);
1126 return -1;
1128 /* We don't encode directly into 'dest', because that would be illegal
1129 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1131 memcpy(dest,buf,len);
1132 tor_free(buf);
1133 return len;
1136 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1137 * success and NULL on failure.
1139 crypto_pk_env_t *
1140 crypto_pk_asn1_decode(const char *str, size_t len)
1142 RSA *rsa;
1143 unsigned char *buf;
1144 /* This ifdef suppresses a type warning. Take out the first case once
1145 * everybody is using OpenSSL 0.9.7 or later.
1147 const unsigned char *cp;
1148 cp = buf = tor_malloc(len);
1149 memcpy(buf,str,len);
1150 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1151 tor_free(buf);
1152 if (!rsa) {
1153 crypto_log_errors(LOG_WARN,"decoding public key");
1154 return NULL;
1156 return _crypto_new_pk_env_rsa(rsa);
1159 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1160 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1161 * Return 0 on success, -1 on failure.
1164 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1166 unsigned char *buf, *bufp;
1167 int len;
1169 len = i2d_RSAPublicKey(pk->key, NULL);
1170 if (len < 0)
1171 return -1;
1172 buf = bufp = tor_malloc(len+1);
1173 len = i2d_RSAPublicKey(pk->key, &bufp);
1174 if (len < 0) {
1175 crypto_log_errors(LOG_WARN,"encoding public key");
1176 tor_free(buf);
1177 return -1;
1179 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1180 tor_free(buf);
1181 return -1;
1183 tor_free(buf);
1184 return 0;
1187 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1188 * every four spaces. */
1189 /* static */ void
1190 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1192 int n = 0;
1193 char *end = out+outlen;
1194 while (*in && out<end) {
1195 *out++ = *in++;
1196 if (++n == 4 && *in && out<end) {
1197 n = 0;
1198 *out++ = ' ';
1201 tor_assert(out<end);
1202 *out = '\0';
1205 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1206 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1207 * space). Return 0 on success, -1 on failure.
1209 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1210 * of the public key, converted to hexadecimal, in upper case, with a
1211 * space after every four digits.
1213 * If <b>add_space</b> is false, omit the spaces.
1216 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1218 char digest[DIGEST_LEN];
1219 char hexdigest[HEX_DIGEST_LEN+1];
1220 if (crypto_pk_get_digest(pk, digest)) {
1221 return -1;
1223 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1224 if (add_space) {
1225 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1226 } else {
1227 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1229 return 0;
1232 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1235 crypto_pk_check_fingerprint_syntax(const char *s)
1237 int i;
1238 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1239 if ((i%5) == 4) {
1240 if (!TOR_ISSPACE(s[i])) return 0;
1241 } else {
1242 if (!TOR_ISXDIGIT(s[i])) return 0;
1245 if (s[FINGERPRINT_LEN]) return 0;
1246 return 1;
1249 /* symmetric crypto */
1251 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1252 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1255 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1257 tor_assert(env);
1259 return crypto_rand(env->key, CIPHER_KEY_LEN);
1262 /** Set the symmetric key for the cipher in <b>env</b> to the first
1263 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1265 void
1266 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1268 tor_assert(env);
1269 tor_assert(key);
1271 memcpy(env->key, key, CIPHER_KEY_LEN);
1274 /** Generate an initialization vector for our AES-CTR cipher; store it
1275 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1276 void
1277 crypto_cipher_generate_iv(char *iv_out)
1279 crypto_rand(iv_out, CIPHER_IV_LEN);
1282 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1283 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1284 * <b>iv</b>. */
1286 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1288 tor_assert(env);
1289 tor_assert(iv);
1290 aes_set_iv(env->cipher, iv);
1291 return 0;
1294 /** Return a pointer to the key set for the cipher in <b>env</b>.
1296 const char *
1297 crypto_cipher_get_key(crypto_cipher_env_t *env)
1299 return env->key;
1302 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1303 * success, -1 on failure.
1306 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1308 tor_assert(env);
1310 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1311 return 0;
1314 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1315 * success, -1 on failure.
1318 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1320 tor_assert(env);
1322 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1323 return 0;
1326 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1327 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1328 * On failure, return -1.
1331 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1332 const char *from, size_t fromlen)
1334 tor_assert(env);
1335 tor_assert(env->cipher);
1336 tor_assert(from);
1337 tor_assert(fromlen);
1338 tor_assert(to);
1340 aes_crypt(env->cipher, from, fromlen, to);
1341 return 0;
1344 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1345 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1346 * On failure, return -1.
1349 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1350 const char *from, size_t fromlen)
1352 tor_assert(env);
1353 tor_assert(from);
1354 tor_assert(to);
1356 aes_crypt(env->cipher, from, fromlen, to);
1357 return 0;
1360 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1361 * on success, return 0. On failure, return -1.
1364 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1366 aes_crypt_inplace(env->cipher, buf, len);
1367 return 0;
1370 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1371 * <b>cipher</b> to the buffer in <b>to</b> of length
1372 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1373 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1374 * number of bytes written, on failure, return -1.
1376 * This function adjusts the current position of the counter in <b>cipher</b>
1377 * to immediately after the encrypted data.
1380 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1381 char *to, size_t tolen,
1382 const char *from, size_t fromlen)
1384 tor_assert(cipher);
1385 tor_assert(from);
1386 tor_assert(to);
1387 tor_assert(fromlen < INT_MAX);
1389 if (fromlen < 1)
1390 return -1;
1391 if (tolen < fromlen + CIPHER_IV_LEN)
1392 return -1;
1394 crypto_cipher_generate_iv(to);
1395 if (crypto_cipher_set_iv(cipher, to)<0)
1396 return -1;
1397 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1398 return (int)(fromlen + CIPHER_IV_LEN);
1401 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1402 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1403 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1404 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1405 * number of bytes written, on failure, return -1.
1407 * This function adjusts the current position of the counter in <b>cipher</b>
1408 * to immediately after the decrypted data.
1411 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1412 char *to, size_t tolen,
1413 const char *from, size_t fromlen)
1415 tor_assert(cipher);
1416 tor_assert(from);
1417 tor_assert(to);
1418 tor_assert(fromlen < INT_MAX);
1420 if (fromlen <= CIPHER_IV_LEN)
1421 return -1;
1422 if (tolen < fromlen - CIPHER_IV_LEN)
1423 return -1;
1425 if (crypto_cipher_set_iv(cipher, from)<0)
1426 return -1;
1427 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1428 return (int)(fromlen - CIPHER_IV_LEN);
1431 /* SHA-1 */
1433 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1434 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1435 * Return 0 on success, -1 on failure.
1438 crypto_digest(char *digest, const char *m, size_t len)
1440 tor_assert(m);
1441 tor_assert(digest);
1442 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1446 crypto_digest256(char *digest, const char *m, size_t len,
1447 digest_algorithm_t algorithm)
1449 tor_assert(m);
1450 tor_assert(digest);
1451 tor_assert(algorithm == DIGEST_SHA256);
1452 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1455 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1456 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1457 * success, -1 on failure. */
1459 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1461 digest_algorithm_t i;
1462 tor_assert(ds_out);
1463 memset(ds_out, 0, sizeof(*ds_out));
1464 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1465 return -1;
1466 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1467 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1468 return -1;
1470 return 0;
1473 /** Return the name of an algorithm, as used in directory documents. */
1474 const char *
1475 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1477 switch (alg) {
1478 case DIGEST_SHA1:
1479 return "sha1";
1480 case DIGEST_SHA256:
1481 return "sha256";
1482 default:
1483 tor_fragile_assert();
1484 return "??unknown_digest??";
1488 /** Given the name of a digest algorithm, return its integer value, or -1 if
1489 * the name is not recognized. */
1491 crypto_digest_algorithm_parse_name(const char *name)
1493 if (!strcmp(name, "sha1"))
1494 return DIGEST_SHA1;
1495 else if (!strcmp(name, "sha256"))
1496 return DIGEST_SHA256;
1497 else
1498 return -1;
1501 /** Intermediate information about the digest of a stream of data. */
1502 struct crypto_digest_env_t {
1503 union {
1504 SHA_CTX sha1;
1505 SHA256_CTX sha2;
1506 } d;
1507 digest_algorithm_t algorithm : 8;
1510 /** Allocate and return a new digest object.
1512 crypto_digest_env_t *
1513 crypto_new_digest_env(void)
1515 crypto_digest_env_t *r;
1516 r = tor_malloc(sizeof(crypto_digest_env_t));
1517 SHA1_Init(&r->d.sha1);
1518 r->algorithm = DIGEST_SHA1;
1519 return r;
1522 crypto_digest_env_t *
1523 crypto_new_digest256_env(digest_algorithm_t algorithm)
1525 crypto_digest_env_t *r;
1526 tor_assert(algorithm == DIGEST_SHA256);
1527 r = tor_malloc(sizeof(crypto_digest_env_t));
1528 SHA256_Init(&r->d.sha2);
1529 r->algorithm = algorithm;
1530 return r;
1533 /** Deallocate a digest object.
1535 void
1536 crypto_free_digest_env(crypto_digest_env_t *digest)
1538 if (!digest)
1539 return;
1540 memset(digest, 0, sizeof(crypto_digest_env_t));
1541 tor_free(digest);
1544 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1546 void
1547 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1548 size_t len)
1550 tor_assert(digest);
1551 tor_assert(data);
1552 /* Using the SHA*_*() calls directly means we don't support doing
1553 * SHA in hardware. But so far the delay of getting the question
1554 * to the hardware, and hearing the answer, is likely higher than
1555 * just doing it ourselves. Hashes are fast.
1557 switch (digest->algorithm) {
1558 case DIGEST_SHA1:
1559 SHA1_Update(&digest->d.sha1, (void*)data, len);
1560 break;
1561 case DIGEST_SHA256:
1562 SHA256_Update(&digest->d.sha2, (void*)data, len);
1563 break;
1564 default:
1565 tor_fragile_assert();
1566 break;
1570 /** Compute the hash of the data that has been passed to the digest
1571 * object; write the first out_len bytes of the result to <b>out</b>.
1572 * <b>out_len</b> must be \<= DIGEST256_LEN.
1574 void
1575 crypto_digest_get_digest(crypto_digest_env_t *digest,
1576 char *out, size_t out_len)
1578 unsigned char r[DIGEST256_LEN];
1579 crypto_digest_env_t tmpenv;
1580 tor_assert(digest);
1581 tor_assert(out);
1582 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1583 memcpy(&tmpenv, digest, sizeof(crypto_digest_env_t));
1584 switch (digest->algorithm) {
1585 case DIGEST_SHA1:
1586 tor_assert(out_len <= DIGEST_LEN);
1587 SHA1_Final(r, &tmpenv.d.sha1);
1588 break;
1589 case DIGEST_SHA256:
1590 tor_assert(out_len <= DIGEST256_LEN);
1591 SHA256_Final(r, &tmpenv.d.sha2);
1592 break;
1593 default:
1594 tor_fragile_assert();
1595 break;
1597 memcpy(out, r, out_len);
1598 memset(r, 0, sizeof(r));
1601 /** Allocate and return a new digest object with the same state as
1602 * <b>digest</b>
1604 crypto_digest_env_t *
1605 crypto_digest_dup(const crypto_digest_env_t *digest)
1607 crypto_digest_env_t *r;
1608 tor_assert(digest);
1609 r = tor_malloc(sizeof(crypto_digest_env_t));
1610 memcpy(r,digest,sizeof(crypto_digest_env_t));
1611 return r;
1614 /** Replace the state of the digest object <b>into</b> with the state
1615 * of the digest object <b>from</b>.
1617 void
1618 crypto_digest_assign(crypto_digest_env_t *into,
1619 const crypto_digest_env_t *from)
1621 tor_assert(into);
1622 tor_assert(from);
1623 memcpy(into,from,sizeof(crypto_digest_env_t));
1626 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1627 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1628 * in <b>hmac_out</b>.
1630 void
1631 crypto_hmac_sha1(char *hmac_out,
1632 const char *key, size_t key_len,
1633 const char *msg, size_t msg_len)
1635 tor_assert(key_len < INT_MAX);
1636 tor_assert(msg_len < INT_MAX);
1637 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1638 (unsigned char*)hmac_out, NULL);
1641 /* DH */
1643 /** Shared P parameter for our DH key exchanged. */
1644 static BIGNUM *dh_param_p = NULL;
1645 /** Shared G parameter for our DH key exchanges. */
1646 static BIGNUM *dh_param_g = NULL;
1648 /** Initialize dh_param_p and dh_param_g if they are not already
1649 * set. */
1650 static void
1651 init_dh_param(void)
1653 BIGNUM *p, *g;
1654 int r;
1655 if (dh_param_p && dh_param_g)
1656 return;
1658 p = BN_new();
1659 g = BN_new();
1660 tor_assert(p);
1661 tor_assert(g);
1663 /* This is from rfc2409, section 6.2. It's a safe prime, and
1664 supposedly it equals:
1665 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1667 r = BN_hex2bn(&p,
1668 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1669 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1670 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1671 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1672 "49286651ECE65381FFFFFFFFFFFFFFFF");
1673 tor_assert(r);
1675 r = BN_set_word(g, 2);
1676 tor_assert(r);
1677 dh_param_p = p;
1678 dh_param_g = g;
1681 #define DH_PRIVATE_KEY_BITS 320
1683 /** Allocate and return a new DH object for a key exchange.
1685 crypto_dh_env_t *
1686 crypto_dh_new(void)
1688 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1690 if (!dh_param_p)
1691 init_dh_param();
1693 if (!(res->dh = DH_new()))
1694 goto err;
1696 if (!(res->dh->p = BN_dup(dh_param_p)))
1697 goto err;
1699 if (!(res->dh->g = BN_dup(dh_param_g)))
1700 goto err;
1702 res->dh->length = DH_PRIVATE_KEY_BITS;
1704 return res;
1705 err:
1706 crypto_log_errors(LOG_WARN, "creating DH object");
1707 if (res->dh) DH_free(res->dh); /* frees p and g too */
1708 tor_free(res);
1709 return NULL;
1712 /** Return the length of the DH key in <b>dh</b>, in bytes.
1715 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1717 tor_assert(dh);
1718 return DH_size(dh->dh);
1721 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1722 * success, -1 on failure.
1725 crypto_dh_generate_public(crypto_dh_env_t *dh)
1727 again:
1728 if (!DH_generate_key(dh->dh)) {
1729 crypto_log_errors(LOG_WARN, "generating DH key");
1730 return -1;
1732 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
1733 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1734 "the-universe chances really do happen. Trying again.");
1735 /* Free and clear the keys, so OpenSSL will actually try again. */
1736 BN_free(dh->dh->pub_key);
1737 BN_free(dh->dh->priv_key);
1738 dh->dh->pub_key = dh->dh->priv_key = NULL;
1739 goto again;
1741 return 0;
1744 /** Generate g^x as necessary, and write the g^x for the key exchange
1745 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1746 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1749 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1751 int bytes;
1752 tor_assert(dh);
1753 if (!dh->dh->pub_key) {
1754 if (crypto_dh_generate_public(dh)<0)
1755 return -1;
1758 tor_assert(dh->dh->pub_key);
1759 bytes = BN_num_bytes(dh->dh->pub_key);
1760 tor_assert(bytes >= 0);
1761 if (pubkey_len < (size_t)bytes) {
1762 log_warn(LD_CRYPTO,
1763 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1764 (int) pubkey_len, bytes);
1765 return -1;
1768 memset(pubkey, 0, pubkey_len);
1769 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1771 return 0;
1774 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1775 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1776 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1778 static int
1779 tor_check_dh_key(int severity, BIGNUM *bn)
1781 BIGNUM *x;
1782 char *s;
1783 tor_assert(bn);
1784 x = BN_new();
1785 tor_assert(x);
1786 if (!dh_param_p)
1787 init_dh_param();
1788 BN_set_word(x, 1);
1789 if (BN_cmp(bn,x)<=0) {
1790 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
1791 goto err;
1793 BN_copy(x,dh_param_p);
1794 BN_sub_word(x, 1);
1795 if (BN_cmp(bn,x)>=0) {
1796 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
1797 goto err;
1799 BN_free(x);
1800 return 0;
1801 err:
1802 BN_free(x);
1803 s = BN_bn2hex(bn);
1804 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1805 OPENSSL_free(s);
1806 return -1;
1809 #undef MIN
1810 #define MIN(a,b) ((a)<(b)?(a):(b))
1811 /** Given a DH key exchange object, and our peer's value of g^y (as a
1812 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1813 * <b>secret_bytes_out</b> bytes of shared key material and write them
1814 * to <b>secret_out</b>. Return the number of bytes generated on success,
1815 * or -1 on failure.
1817 * (We generate key material by computing
1818 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1819 * where || is concatenation.)
1821 ssize_t
1822 crypto_dh_compute_secret(int severity, crypto_dh_env_t *dh,
1823 const char *pubkey, size_t pubkey_len,
1824 char *secret_out, size_t secret_bytes_out)
1826 char *secret_tmp = NULL;
1827 BIGNUM *pubkey_bn = NULL;
1828 size_t secret_len=0;
1829 int result=0;
1830 tor_assert(dh);
1831 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1832 tor_assert(pubkey_len < INT_MAX);
1834 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1835 (int)pubkey_len, NULL)))
1836 goto error;
1837 if (tor_check_dh_key(severity, pubkey_bn)<0) {
1838 /* Check for invalid public keys. */
1839 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
1840 goto error;
1842 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1843 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1844 if (result < 0) {
1845 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1846 goto error;
1848 secret_len = result;
1849 if (crypto_expand_key_material(secret_tmp, secret_len,
1850 secret_out, secret_bytes_out)<0)
1851 goto error;
1852 secret_len = secret_bytes_out;
1854 goto done;
1855 error:
1856 result = -1;
1857 done:
1858 crypto_log_errors(LOG_WARN, "completing DH handshake");
1859 if (pubkey_bn)
1860 BN_free(pubkey_bn);
1861 tor_free(secret_tmp);
1862 if (result < 0)
1863 return result;
1864 else
1865 return secret_len;
1868 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1869 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1870 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1871 * H(K | [00]) | H(K | [01]) | ....
1873 * Return 0 on success, -1 on failure.
1876 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1877 char *key_out, size_t key_out_len)
1879 int i;
1880 char *cp, *tmp = tor_malloc(key_in_len+1);
1881 char digest[DIGEST_LEN];
1883 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1884 tor_assert(key_out_len <= DIGEST_LEN*256);
1886 memcpy(tmp, key_in, key_in_len);
1887 for (cp = key_out, i=0; cp < key_out+key_out_len;
1888 ++i, cp += DIGEST_LEN) {
1889 tmp[key_in_len] = i;
1890 if (crypto_digest(digest, tmp, key_in_len+1))
1891 goto err;
1892 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1894 memset(tmp, 0, key_in_len+1);
1895 tor_free(tmp);
1896 memset(digest, 0, sizeof(digest));
1897 return 0;
1899 err:
1900 memset(tmp, 0, key_in_len+1);
1901 tor_free(tmp);
1902 memset(digest, 0, sizeof(digest));
1903 return -1;
1906 /** Free a DH key exchange object.
1908 void
1909 crypto_dh_free(crypto_dh_env_t *dh)
1911 if (!dh)
1912 return;
1913 tor_assert(dh->dh);
1914 DH_free(dh->dh);
1915 tor_free(dh);
1918 /* random numbers */
1920 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1921 * work for us too. */
1922 #define ADD_ENTROPY 32
1924 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1925 "release".) */
1926 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1928 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1929 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1930 * that fd without checking whether it fit in the fd_set. Thus, if the
1931 * system has not just been started up, it is unsafe to call */
1932 #define RAND_POLL_IS_SAFE \
1933 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1934 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1935 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1937 /** Seed OpenSSL's random number generator with bytes from the operating
1938 * system. <b>startup</b> should be true iff we have just started Tor and
1939 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1942 crypto_seed_rng(int startup)
1944 char buf[ADD_ENTROPY];
1945 int rand_poll_status = 0;
1947 /* local variables */
1948 #ifdef MS_WINDOWS
1949 static int provider_set = 0;
1950 static HCRYPTPROV provider;
1951 #else
1952 static const char *filenames[] = {
1953 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1955 int fd, i;
1956 size_t n;
1957 #endif
1959 #if HAVE_RAND_POLL
1960 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1961 * entropy than we do. We'll try calling that, *and* calling our own entropy
1962 * functions. If one succeeds, we'll accept the RNG as seeded. */
1963 if (startup || RAND_POLL_IS_SAFE) {
1964 rand_poll_status = RAND_poll();
1965 if (rand_poll_status == 0)
1966 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1968 #endif
1970 #ifdef MS_WINDOWS
1971 if (!provider_set) {
1972 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1973 CRYPT_VERIFYCONTEXT)) {
1974 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1975 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1976 return rand_poll_status ? 0 : -1;
1979 provider_set = 1;
1981 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1982 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1983 return rand_poll_status ? 0 : -1;
1985 RAND_seed(buf, sizeof(buf));
1986 memset(buf, 0, sizeof(buf));
1987 return 0;
1988 #else
1989 for (i = 0; filenames[i]; ++i) {
1990 fd = open(filenames[i], O_RDONLY, 0);
1991 if (fd<0) continue;
1992 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1993 n = read_all(fd, buf, sizeof(buf), 0);
1994 close(fd);
1995 if (n != sizeof(buf)) {
1996 log_warn(LD_CRYPTO,
1997 "Error reading from entropy source (read only %lu bytes).",
1998 (unsigned long)n);
1999 return -1;
2001 RAND_seed(buf, (int)sizeof(buf));
2002 memset(buf, 0, sizeof(buf));
2003 return 0;
2006 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
2007 return rand_poll_status ? 0 : -1;
2008 #endif
2011 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2012 * success, -1 on failure.
2015 crypto_rand(char *to, size_t n)
2017 int r;
2018 tor_assert(n < INT_MAX);
2019 tor_assert(to);
2020 r = RAND_bytes((unsigned char*)to, (int)n);
2021 if (r == 0)
2022 crypto_log_errors(LOG_WARN, "generating random data");
2023 return (r == 1) ? 0 : -1;
2026 /** Return a pseudorandom integer, chosen uniformly from the values
2027 * between 0 and <b>max</b>-1. */
2029 crypto_rand_int(unsigned int max)
2031 unsigned int val;
2032 unsigned int cutoff;
2033 tor_assert(max < UINT_MAX);
2034 tor_assert(max > 0); /* don't div by 0 */
2036 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2037 * distribution with clipping at the upper end of unsigned int's
2038 * range.
2040 cutoff = UINT_MAX - (UINT_MAX%max);
2041 while (1) {
2042 crypto_rand((char*)&val, sizeof(val));
2043 if (val < cutoff)
2044 return val % max;
2048 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2049 * between 0 and <b>max</b>-1. */
2050 uint64_t
2051 crypto_rand_uint64(uint64_t max)
2053 uint64_t val;
2054 uint64_t cutoff;
2055 tor_assert(max < UINT64_MAX);
2056 tor_assert(max > 0); /* don't div by 0 */
2058 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2059 * distribution with clipping at the upper end of unsigned int's
2060 * range.
2062 cutoff = UINT64_MAX - (UINT64_MAX%max);
2063 while (1) {
2064 crypto_rand((char*)&val, sizeof(val));
2065 if (val < cutoff)
2066 return val % max;
2070 /** Return a pseudorandom double d, chosen uniformly from the range
2071 * 0.0 <= d < 1.0.
2073 double
2074 crypto_rand_double(void)
2076 /* We just use an unsigned int here; we don't really care about getting
2077 * more than 32 bits of resolution */
2078 unsigned int uint;
2079 crypto_rand((char*)&uint, sizeof(uint));
2080 #if SIZEOF_INT == 4
2081 #define UINT_MAX_AS_DOUBLE 4294967296.0
2082 #elif SIZEOF_INT == 8
2083 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2084 #else
2085 #error SIZEOF_INT is neither 4 nor 8
2086 #endif
2087 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2090 /** Generate and return a new random hostname starting with <b>prefix</b>,
2091 * ending with <b>suffix</b>, and containing no less than
2092 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2093 * characters between. */
2094 char *
2095 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2096 const char *suffix)
2098 char *result, *rand_bytes;
2099 int randlen, rand_bytes_len;
2100 size_t resultlen, prefixlen;
2102 tor_assert(max_rand_len >= min_rand_len);
2103 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2104 prefixlen = strlen(prefix);
2105 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2107 rand_bytes_len = ((randlen*5)+7)/8;
2108 if (rand_bytes_len % 5)
2109 rand_bytes_len += 5 - (rand_bytes_len%5);
2110 rand_bytes = tor_malloc(rand_bytes_len);
2111 crypto_rand(rand_bytes, rand_bytes_len);
2113 result = tor_malloc(resultlen);
2114 memcpy(result, prefix, prefixlen);
2115 base32_encode(result+prefixlen, resultlen-prefixlen,
2116 rand_bytes, rand_bytes_len);
2117 tor_free(rand_bytes);
2118 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2120 return result;
2123 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2124 * is empty. */
2125 void *
2126 smartlist_choose(const smartlist_t *sl)
2128 int len = smartlist_len(sl);
2129 if (len)
2130 return smartlist_get(sl,crypto_rand_int(len));
2131 return NULL; /* no elements to choose from */
2134 /** Scramble the elements of <b>sl</b> into a random order. */
2135 void
2136 smartlist_shuffle(smartlist_t *sl)
2138 int i;
2139 /* From the end of the list to the front, choose at random from the
2140 positions we haven't looked at yet, and swap that position into the
2141 current position. Remember to give "no swap" the same probability as
2142 any other swap. */
2143 for (i = smartlist_len(sl)-1; i > 0; --i) {
2144 int j = crypto_rand_int(i+1);
2145 smartlist_swap(sl, i, j);
2149 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2150 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2151 * bytes. Return the number of bytes written on success; -1 if
2152 * destlen is too short, or other failure.
2155 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2157 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2158 * it ever shows up in the profile. */
2159 EVP_ENCODE_CTX ctx;
2160 int len, ret;
2161 tor_assert(srclen < INT_MAX);
2163 /* 48 bytes of input -> 64 bytes of output plus newline.
2164 Plus one more byte, in case I'm wrong.
2166 if (destlen < ((srclen/48)+1)*66)
2167 return -1;
2168 if (destlen > SIZE_T_CEILING)
2169 return -1;
2171 EVP_EncodeInit(&ctx);
2172 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2173 (unsigned char*)src, (int)srclen);
2174 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2175 ret += len;
2176 return ret;
2179 #define X 255
2180 #define SP 64
2181 #define PAD 65
2182 /** Internal table mapping byte values to what they represent in base64.
2183 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2184 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2185 * end-of-string. */
2186 static const uint8_t base64_decode_table[256] = {
2187 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2188 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2189 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2190 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2191 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2192 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2193 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2194 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2195 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2196 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2197 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2198 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2199 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2200 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2201 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2202 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2205 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2206 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2207 * bytes. Return the number of bytes written on success; -1 if
2208 * destlen is too short, or other failure.
2210 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2211 * spaces or padding.
2213 * NOTE 2: This implementation does not check for the correct number of
2214 * padding "=" characters at the end of the string, and does not check
2215 * for internal padding characters.
2218 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2220 #ifdef USE_OPENSSL_BASE64
2221 EVP_ENCODE_CTX ctx;
2222 int len, ret;
2223 /* 64 bytes of input -> *up to* 48 bytes of output.
2224 Plus one more byte, in case I'm wrong.
2226 if (destlen < ((srclen/64)+1)*49)
2227 return -1;
2228 if (destlen > SIZE_T_CEILING)
2229 return -1;
2231 EVP_DecodeInit(&ctx);
2232 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2233 (unsigned char*)src, srclen);
2234 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2235 ret += len;
2236 return ret;
2237 #else
2238 const char *eos = src+srclen;
2239 uint32_t n=0;
2240 int n_idx=0;
2241 char *dest_orig = dest;
2243 /* Max number of bits == srclen*6.
2244 * Number of bytes required to hold all bits == (srclen*6)/8.
2245 * Yes, we want to round down: anything that hangs over the end of a
2246 * byte is padding. */
2247 if (destlen < (srclen*3)/4)
2248 return -1;
2249 if (destlen > SIZE_T_CEILING)
2250 return -1;
2252 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2253 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2254 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2256 for ( ; src < eos; ++src) {
2257 unsigned char c = (unsigned char) *src;
2258 uint8_t v = base64_decode_table[c];
2259 switch (v) {
2260 case X:
2261 /* This character isn't allowed in base64. */
2262 return -1;
2263 case SP:
2264 /* This character is whitespace, and has no effect. */
2265 continue;
2266 case PAD:
2267 /* We've hit an = character: the data is over. */
2268 goto end_of_loop;
2269 default:
2270 /* We have an actual 6-bit value. Append it to the bits in n. */
2271 n = (n<<6) | v;
2272 if ((++n_idx) == 4) {
2273 /* We've accumulated 24 bits in n. Flush them. */
2274 *dest++ = (n>>16);
2275 *dest++ = (n>>8) & 0xff;
2276 *dest++ = (n) & 0xff;
2277 n_idx = 0;
2278 n = 0;
2282 end_of_loop:
2283 /* If we have leftover bits, we need to cope. */
2284 switch (n_idx) {
2285 case 0:
2286 default:
2287 /* No leftover bits. We win. */
2288 break;
2289 case 1:
2290 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2291 return -1;
2292 case 2:
2293 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2294 *dest++ = n >> 4;
2295 break;
2296 case 3:
2297 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2298 *dest++ = n >> 10;
2299 *dest++ = n >> 2;
2302 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2303 tor_assert((dest-dest_orig) <= INT_MAX);
2305 return (int)(dest-dest_orig);
2306 #endif
2308 #undef X
2309 #undef SP
2310 #undef PAD
2312 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2313 * and newline characters, and store the nul-terminated result in the first
2314 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2316 digest_to_base64(char *d64, const char *digest)
2318 char buf[256];
2319 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2320 buf[BASE64_DIGEST_LEN] = '\0';
2321 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2322 return 0;
2325 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2326 * trailing newline or = characters), decode it and store the result in the
2327 * first DIGEST_LEN bytes at <b>digest</b>. */
2329 digest_from_base64(char *digest, const char *d64)
2331 #ifdef USE_OPENSSL_BASE64
2332 char buf_in[BASE64_DIGEST_LEN+3];
2333 char buf[256];
2334 if (strlen(d64) != BASE64_DIGEST_LEN)
2335 return -1;
2336 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2337 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2338 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2339 return -1;
2340 memcpy(digest, buf, DIGEST_LEN);
2341 return 0;
2342 #else
2343 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2344 return 0;
2345 else
2346 return -1;
2347 #endif
2350 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2351 * trailing = and newline characters, and store the nul-terminated result in
2352 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2354 digest256_to_base64(char *d64, const char *digest)
2356 char buf[256];
2357 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2358 buf[BASE64_DIGEST256_LEN] = '\0';
2359 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2360 return 0;
2363 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2364 * trailing newline or = characters), decode it and store the result in the
2365 * first DIGEST256_LEN bytes at <b>digest</b>. */
2367 digest256_from_base64(char *digest, const char *d64)
2369 #ifdef USE_OPENSSL_BASE64
2370 char buf_in[BASE64_DIGEST256_LEN+3];
2371 char buf[256];
2372 if (strlen(d64) != BASE64_DIGEST256_LEN)
2373 return -1;
2374 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2375 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2376 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2377 return -1;
2378 memcpy(digest, buf, DIGEST256_LEN);
2379 return 0;
2380 #else
2381 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2382 return 0;
2383 else
2384 return -1;
2385 #endif
2388 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2389 * that srclen*8 is a multiple of 5.
2391 void
2392 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2394 unsigned int i, bit, v, u;
2395 size_t nbits = srclen * 8;
2397 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2398 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2399 tor_assert(destlen < SIZE_T_CEILING);
2401 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2402 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2403 v = ((uint8_t)src[bit/8]) << 8;
2404 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2405 /* set u to the 5-bit value at the bit'th bit of src. */
2406 u = (v >> (11-(bit%8))) & 0x1F;
2407 dest[i] = BASE32_CHARS[u];
2409 dest[i] = '\0';
2412 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2413 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2416 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2418 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2419 * it ever shows up in the profile. */
2420 unsigned int i, j, bit;
2421 size_t nbits;
2422 char *tmp;
2423 nbits = srclen * 5;
2425 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2426 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2427 tor_assert(destlen < SIZE_T_CEILING);
2429 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2430 tmp = tor_malloc_zero(srclen);
2431 for (j = 0; j < srclen; ++j) {
2432 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2433 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2434 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2435 else {
2436 log_warn(LD_BUG, "illegal character in base32 encoded string");
2437 tor_free(tmp);
2438 return -1;
2442 /* Assemble result byte-wise by applying five possible cases. */
2443 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2444 switch (bit % 40) {
2445 case 0:
2446 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2447 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2448 break;
2449 case 8:
2450 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2451 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2452 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2453 break;
2454 case 16:
2455 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2456 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2457 break;
2458 case 24:
2459 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2460 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2461 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2462 break;
2463 case 32:
2464 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2465 ((uint8_t)tmp[(bit/5)+1]);
2466 break;
2470 memset(tmp, 0, srclen);
2471 tor_free(tmp);
2472 tmp = NULL;
2473 return 0;
2476 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2477 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2478 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2479 * are a salt; the 9th byte describes how much iteration to do.
2480 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2482 void
2483 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2484 size_t secret_len, const char *s2k_specifier)
2486 crypto_digest_env_t *d;
2487 uint8_t c;
2488 size_t count, tmplen;
2489 char *tmp;
2490 tor_assert(key_out_len < SIZE_T_CEILING);
2492 #define EXPBIAS 6
2493 c = s2k_specifier[8];
2494 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2495 #undef EXPBIAS
2497 tor_assert(key_out_len <= DIGEST_LEN);
2499 d = crypto_new_digest_env();
2500 tmplen = 8+secret_len;
2501 tmp = tor_malloc(tmplen);
2502 memcpy(tmp,s2k_specifier,8);
2503 memcpy(tmp+8,secret,secret_len);
2504 secret_len += 8;
2505 while (count) {
2506 if (count >= secret_len) {
2507 crypto_digest_add_bytes(d, tmp, secret_len);
2508 count -= secret_len;
2509 } else {
2510 crypto_digest_add_bytes(d, tmp, count);
2511 count = 0;
2514 crypto_digest_get_digest(d, key_out, key_out_len);
2515 memset(tmp, 0, tmplen);
2516 tor_free(tmp);
2517 crypto_free_digest_env(d);
2520 #ifdef TOR_IS_MULTITHREADED
2521 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2522 static void
2523 _openssl_locking_cb(int mode, int n, const char *file, int line)
2525 (void)file;
2526 (void)line;
2527 if (!_openssl_mutexes)
2528 /* This is not a really good fix for the
2529 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2530 * it can't hurt. */
2531 return;
2532 if (mode & CRYPTO_LOCK)
2533 tor_mutex_acquire(_openssl_mutexes[n]);
2534 else
2535 tor_mutex_release(_openssl_mutexes[n]);
2538 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2539 * as a lock. */
2540 struct CRYPTO_dynlock_value {
2541 tor_mutex_t *lock;
2544 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2545 * documentation in OpenSSL's docs for more info. */
2546 static struct CRYPTO_dynlock_value *
2547 _openssl_dynlock_create_cb(const char *file, int line)
2549 struct CRYPTO_dynlock_value *v;
2550 (void)file;
2551 (void)line;
2552 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2553 v->lock = tor_mutex_new();
2554 return v;
2557 /** OpenSSL callback function to acquire or release a lock: see
2558 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2559 static void
2560 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2561 const char *file, int line)
2563 (void)file;
2564 (void)line;
2565 if (mode & CRYPTO_LOCK)
2566 tor_mutex_acquire(v->lock);
2567 else
2568 tor_mutex_release(v->lock);
2571 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2572 * documentation in OpenSSL's docs for more info. */
2573 static void
2574 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2575 const char *file, int line)
2577 (void)file;
2578 (void)line;
2579 tor_mutex_free(v->lock);
2580 tor_free(v);
2583 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2584 * multithreaded. */
2585 static int
2586 setup_openssl_threading(void)
2588 int i;
2589 int n = CRYPTO_num_locks();
2590 _n_openssl_mutexes = n;
2591 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2592 for (i=0; i < n; ++i)
2593 _openssl_mutexes[i] = tor_mutex_new();
2594 CRYPTO_set_locking_callback(_openssl_locking_cb);
2595 CRYPTO_set_id_callback(tor_get_thread_id);
2596 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2597 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2598 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2599 return 0;
2601 #else
2602 static int
2603 setup_openssl_threading(void)
2605 return 0;
2607 #endif