Fix a heap overflow found by debuger, and make it harder to make that mistake again
[tor/rransom.git] / src / common / crypto.c
blob7cb849a64ba2a99e1eb0633cf2b33a05e5fb6977
1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file crypto.c
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
11 **/
13 #include "orconfig.h"
15 #ifdef MS_WINDOWS
16 #define WIN32_WINNT 0x400
17 #define _WIN32_WINNT 0x400
18 #define WIN32_LEAN_AND_MEAN
19 #include <windows.h>
20 #include <wincrypt.h>
21 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
22 * use either definition. */
23 #undef OCSP_RESPONSE
24 #endif
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/rand.h>
31 #include <openssl/opensslv.h>
32 #include <openssl/bn.h>
33 #include <openssl/dh.h>
34 #include <openssl/conf.h>
35 #include <openssl/hmac.h>
37 #ifdef HAVE_CTYPE_H
38 #include <ctype.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_SYS_FCNTL_H
47 #include <sys/fcntl.h>
48 #endif
50 #define CRYPTO_PRIVATE
51 #include "crypto.h"
52 #include "log.h"
53 #include "aes.h"
54 #include "util.h"
55 #include "container.h"
56 #include "compat.h"
58 #if OPENSSL_VERSION_NUMBER < 0x00907000l
59 #error "We require OpenSSL >= 0.9.7"
60 #endif
62 #include <openssl/engine.h>
64 /** Macro: is k a valid RSA public or private key? */
65 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
66 /** Macro: is k a valid RSA private key? */
67 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
69 #ifdef TOR_IS_MULTITHREADED
70 /** A number of preallocated mutexes for use by OpenSSL. */
71 static tor_mutex_t **_openssl_mutexes = NULL;
72 /** How many mutexes have we allocated for use by OpenSSL? */
73 static int _n_openssl_mutexes = 0;
74 #endif
76 /** A public key, or a public/private key-pair. */
77 struct crypto_pk_env_t
79 int refs; /* reference counting so we don't have to copy keys */
80 RSA *key;
83 /** Key and stream information for a stream cipher. */
84 struct crypto_cipher_env_t
86 char key[CIPHER_KEY_LEN];
87 aes_cnt_cipher_t *cipher;
90 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
91 * while we're waiting for the second.*/
92 struct crypto_dh_env_t {
93 DH *dh;
96 static int setup_openssl_threading(void);
97 static int tor_check_dh_key(BIGNUM *bn);
99 /** Return the number of bytes added by padding method <b>padding</b>.
101 static INLINE int
102 crypto_get_rsa_padding_overhead(int padding)
104 switch (padding)
106 case RSA_NO_PADDING: return 0;
107 case RSA_PKCS1_OAEP_PADDING: return 42;
108 case RSA_PKCS1_PADDING: return 11;
109 default: tor_assert(0); return -1;
113 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
115 static INLINE int
116 crypto_get_rsa_padding(int padding)
118 switch (padding)
120 case PK_NO_PADDING: return RSA_NO_PADDING;
121 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
122 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
123 default: tor_assert(0); return -1;
127 /** Boolean: has OpenSSL's crypto been initialized? */
128 static int _crypto_global_initialized = 0;
130 /** Log all pending crypto errors at level <b>severity</b>. Use
131 * <b>doing</b> to describe our current activities.
133 static void
134 crypto_log_errors(int severity, const char *doing)
136 unsigned long err;
137 const char *msg, *lib, *func;
138 while ((err = ERR_get_error()) != 0) {
139 msg = (const char*)ERR_reason_error_string(err);
140 lib = (const char*)ERR_lib_error_string(err);
141 func = (const char*)ERR_func_error_string(err);
142 if (!msg) msg = "(null)";
143 if (!lib) lib = "(null)";
144 if (!func) func = "(null)";
145 if (doing) {
146 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
147 doing, msg, lib, func);
148 } else {
149 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
154 /** Log any OpenSSL engines we're using at NOTICE. */
155 static void
156 log_engine(const char *fn, ENGINE *e)
158 if (e) {
159 const char *name, *id;
160 name = ENGINE_get_name(e);
161 id = ENGINE_get_id(e);
162 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
163 name?name:"?", id?id:"?", fn);
164 } else {
165 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
169 /** Initialize the crypto library. Return 0 on success, -1 on failure.
172 crypto_global_init(int useAccel)
174 if (!_crypto_global_initialized) {
175 ERR_load_crypto_strings();
176 OpenSSL_add_all_algorithms();
177 _crypto_global_initialized = 1;
178 setup_openssl_threading();
179 /* XXX the below is a bug, since we can't know if we're supposed
180 * to be using hardware acceleration or not. we should arrange
181 * for this function to be called before init_keys. But make it
182 * not complain loudly, at least until we make acceleration work. */
183 if (useAccel < 0) {
184 log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
186 if (useAccel > 0) {
187 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
188 ENGINE_load_builtin_engines();
189 if (!ENGINE_register_all_complete())
190 return -1;
192 /* XXXX make sure this isn't leaking. */
193 log_engine("RSA", ENGINE_get_default_RSA());
194 log_engine("DH", ENGINE_get_default_DH());
195 log_engine("RAND", ENGINE_get_default_RAND());
196 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
197 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
198 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
200 return crypto_seed_rng(1);
202 return 0;
205 /** Free crypto resources held by this thread. */
206 void
207 crypto_thread_cleanup(void)
209 ERR_remove_state(0);
212 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
215 crypto_global_cleanup(void)
217 EVP_cleanup();
218 ERR_remove_state(0);
219 ERR_free_strings();
220 ENGINE_cleanup();
221 CONF_modules_unload(1);
222 CRYPTO_cleanup_all_ex_data();
223 #ifdef TOR_IS_MULTITHREADED
224 if (_n_openssl_mutexes) {
225 int n = _n_openssl_mutexes;
226 tor_mutex_t **ms = _openssl_mutexes;
227 int i;
228 _openssl_mutexes = NULL;
229 _n_openssl_mutexes = 0;
230 for (i=0;i<n;++i) {
231 tor_mutex_free(ms[i]);
233 tor_free(ms);
235 #endif
236 return 0;
239 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
240 crypto_pk_env_t *
241 _crypto_new_pk_env_rsa(RSA *rsa)
243 crypto_pk_env_t *env;
244 tor_assert(rsa);
245 env = tor_malloc(sizeof(crypto_pk_env_t));
246 env->refs = 1;
247 env->key = rsa;
248 return env;
251 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
252 * returns NULL if this isn't an RSA key. */
253 crypto_pk_env_t *
254 _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
256 RSA *rsa;
257 if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
258 return NULL;
259 return _crypto_new_pk_env_rsa(rsa);
262 /** Helper, used by tor-checkkey.c. Return the RSA from a crypto_pk_env_t. */
263 RSA *
264 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
266 return env->key;
269 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
270 * private is set, include the private-key portion of the key. */
271 EVP_PKEY *
272 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
274 RSA *key = NULL;
275 EVP_PKEY *pkey = NULL;
276 tor_assert(env->key);
277 if (private) {
278 if (!(key = RSAPrivateKey_dup(env->key)))
279 goto error;
280 } else {
281 if (!(key = RSAPublicKey_dup(env->key)))
282 goto error;
284 if (!(pkey = EVP_PKEY_new()))
285 goto error;
286 if (!(EVP_PKEY_assign_RSA(pkey, key)))
287 goto error;
288 return pkey;
289 error:
290 if (pkey)
291 EVP_PKEY_free(pkey);
292 if (key)
293 RSA_free(key);
294 return NULL;
297 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
299 DH *
300 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
302 return dh->dh;
305 /** Allocate and return storage for a public key. The key itself will not yet
306 * be set.
308 crypto_pk_env_t *
309 crypto_new_pk_env(void)
311 RSA *rsa;
313 rsa = RSA_new();
314 if (!rsa) return NULL;
315 return _crypto_new_pk_env_rsa(rsa);
318 /** Release a reference to an asymmetric key; when all the references
319 * are released, free the key.
321 void
322 crypto_free_pk_env(crypto_pk_env_t *env)
324 tor_assert(env);
326 if (--env->refs > 0)
327 return;
329 if (env->key)
330 RSA_free(env->key);
332 tor_free(env);
335 /** Create a new symmetric cipher for a given key and encryption flag
336 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
337 * on failure.
339 crypto_cipher_env_t *
340 crypto_create_init_cipher(const char *key, int encrypt_mode)
342 int r;
343 crypto_cipher_env_t *crypto = NULL;
345 if (! (crypto = crypto_new_cipher_env())) {
346 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
347 return NULL;
350 if (crypto_cipher_set_key(crypto, key)) {
351 crypto_log_errors(LOG_WARN, "setting symmetric key");
352 goto error;
355 if (encrypt_mode)
356 r = crypto_cipher_encrypt_init_cipher(crypto);
357 else
358 r = crypto_cipher_decrypt_init_cipher(crypto);
360 if (r)
361 goto error;
362 return crypto;
364 error:
365 if (crypto)
366 crypto_free_cipher_env(crypto);
367 return NULL;
370 /** Allocate and return a new symmetric cipher.
372 crypto_cipher_env_t *
373 crypto_new_cipher_env(void)
375 crypto_cipher_env_t *env;
377 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
378 env->cipher = aes_new_cipher();
379 return env;
382 /** Free a symmetric cipher.
384 void
385 crypto_free_cipher_env(crypto_cipher_env_t *env)
387 tor_assert(env);
389 tor_assert(env->cipher);
390 aes_free_cipher(env->cipher);
391 memset(env, 0, sizeof(crypto_cipher_env_t));
392 tor_free(env);
395 /* public key crypto */
397 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
398 * success, -1 on failure.
401 crypto_pk_generate_key(crypto_pk_env_t *env)
403 tor_assert(env);
405 if (env->key)
406 RSA_free(env->key);
407 #if OPENSSL_VERSION_NUMBER < 0x00908000l
408 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
409 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
410 #else
411 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
413 BIGNUM *e = BN_new();
414 RSA *r = NULL;
415 if (!e)
416 goto done;
417 if (! BN_set_word(e, 65537))
418 goto done;
419 r = RSA_new();
420 if (!r)
421 goto done;
422 if (RSA_generate_key_ex(r, PK_BYTES*8, e, NULL) == -1)
423 goto done;
425 env->key = r;
426 r = NULL;
427 done:
428 if (e)
429 BN_free(e);
430 if (r)
431 RSA_free(r);
433 #endif
434 if (!env->key) {
435 crypto_log_errors(LOG_WARN, "generating RSA key");
436 return -1;
439 return 0;
442 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
443 * Return 0 on success, -1 on failure.
445 /* Used here, and used for testing. */
447 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
448 const char *s)
450 BIO *b;
452 tor_assert(env);
453 tor_assert(s);
455 /* Create a read-only memory BIO, backed by the NUL-terminated string 's' */
456 b = BIO_new_mem_buf((char*)s, -1);
458 if (env->key)
459 RSA_free(env->key);
461 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
463 BIO_free(b);
465 if (!env->key) {
466 crypto_log_errors(LOG_WARN, "Error parsing private key");
467 return -1;
469 return 0;
472 /** Read a PEM-encoded private key from the file named by
473 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
476 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
477 const char *keyfile)
479 char *contents;
480 int r;
482 /* Read the file into a string. */
483 contents = read_file_to_str(keyfile, 0, NULL);
484 if (!contents) {
485 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
486 return -1;
489 /* Try to parse it. */
490 r = crypto_pk_read_private_key_from_string(env, contents);
491 tor_free(contents);
492 if (r)
493 return -1; /* read_private_key_from_string already warned, so we don't.*/
495 /* Make sure it's valid. */
496 if (crypto_pk_check_key(env) <= 0)
497 return -1;
499 return 0;
502 /** Helper function to implement crypto_pk_write_*_key_to_string. */
503 static int
504 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
505 size_t *len, int is_public)
507 BUF_MEM *buf;
508 BIO *b;
509 int r;
511 tor_assert(env);
512 tor_assert(env->key);
513 tor_assert(dest);
515 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
517 /* Now you can treat b as if it were a file. Just use the
518 * PEM_*_bio_* functions instead of the non-bio variants.
520 if (is_public)
521 r = PEM_write_bio_RSAPublicKey(b, env->key);
522 else
523 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
525 if (!r) {
526 crypto_log_errors(LOG_WARN, "writing RSA key to string");
527 BIO_free(b);
528 return -1;
531 BIO_get_mem_ptr(b, &buf);
532 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
533 BIO_free(b);
535 *dest = tor_malloc(buf->length+1);
536 memcpy(*dest, buf->data, buf->length);
537 (*dest)[buf->length] = 0; /* nul terminate it */
538 *len = buf->length;
539 BUF_MEM_free(buf);
541 return 0;
544 /** PEM-encode the public key portion of <b>env</b> and write it to a
545 * newly allocated string. On success, set *<b>dest</b> to the new
546 * string, *<b>len</b> to the string's length, and return 0. On
547 * failure, return -1.
550 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
551 size_t *len)
553 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
556 /** PEM-encode the private key portion of <b>env</b> and write it to a
557 * newly allocated string. On success, set *<b>dest</b> to the new
558 * string, *<b>len</b> to the string's length, and return 0. On
559 * failure, return -1.
562 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
563 size_t *len)
565 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
568 /** Read a PEM-encoded public key from the first <b>len</b> characters of
569 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
570 * failure.
573 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
574 size_t len)
576 BIO *b;
578 tor_assert(env);
579 tor_assert(src);
580 tor_assert(len<INT_MAX);
582 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
584 BIO_write(b, src, (int)len);
586 if (env->key)
587 RSA_free(env->key);
588 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
589 BIO_free(b);
590 if (!env->key) {
591 crypto_log_errors(LOG_WARN, "reading public key from string");
592 return -1;
595 return 0;
598 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
599 * PEM-encoded. Return 0 on success, -1 on failure.
602 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
603 const char *fname)
605 BIO *bio;
606 char *cp;
607 long len;
608 char *s;
609 int r;
611 tor_assert(PRIVATE_KEY_OK(env));
613 if (!(bio = BIO_new(BIO_s_mem())))
614 return -1;
615 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
616 == 0) {
617 crypto_log_errors(LOG_WARN, "writing private key");
618 BIO_free(bio);
619 return -1;
621 len = BIO_get_mem_data(bio, &cp);
622 tor_assert(len >= 0);
623 s = tor_malloc(len+1);
624 memcpy(s, cp, len);
625 s[len]='\0';
626 r = write_str_to_file(fname, s, 0);
627 BIO_free(bio);
628 tor_free(s);
629 return r;
632 /** Return true iff <b>env</b> has a valid key.
635 crypto_pk_check_key(crypto_pk_env_t *env)
637 int r;
638 tor_assert(env);
640 r = RSA_check_key(env->key);
641 if (r <= 0)
642 crypto_log_errors(LOG_WARN,"checking RSA key");
643 return r;
646 /** Return true iff <b>key</b> contains the private-key portion of the RSA
647 * key. */
649 crypto_pk_key_is_private(const crypto_pk_env_t *key)
651 tor_assert(key);
652 return PRIVATE_KEY_OK(key);
655 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
656 * if a==b, and 1 if a\>b.
659 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
661 int result;
663 if (!a || !b)
664 return -1;
666 if (!a->key || !b->key)
667 return -1;
669 tor_assert(PUBLIC_KEY_OK(a));
670 tor_assert(PUBLIC_KEY_OK(b));
671 result = BN_cmp((a->key)->n, (b->key)->n);
672 if (result)
673 return result;
674 return BN_cmp((a->key)->e, (b->key)->e);
677 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
678 size_t
679 crypto_pk_keysize(crypto_pk_env_t *env)
681 tor_assert(env);
682 tor_assert(env->key);
684 return (size_t) RSA_size(env->key);
687 /** Increase the reference count of <b>env</b>, and return it.
689 crypto_pk_env_t *
690 crypto_pk_dup_key(crypto_pk_env_t *env)
692 tor_assert(env);
693 tor_assert(env->key);
695 env->refs++;
696 return env;
699 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
700 crypto_pk_env_t *
701 crypto_pk_copy_full(crypto_pk_env_t *env)
703 RSA *new_key;
704 tor_assert(env);
705 tor_assert(env->key);
707 if (PRIVATE_KEY_OK(env)) {
708 new_key = RSAPrivateKey_dup(env->key);
709 } else {
710 new_key = RSAPublicKey_dup(env->key);
713 return _crypto_new_pk_env_rsa(new_key);
716 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
717 * in <b>env</b>, using the padding method <b>padding</b>. On success,
718 * write the result to <b>to</b>, and return the number of bytes
719 * written. On failure, return -1.
721 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
722 * at least the length of the modulus of <b>env</b>.
725 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to, size_t tolen,
726 const char *from, size_t fromlen, int padding)
728 int r;
729 tor_assert(env);
730 tor_assert(from);
731 tor_assert(to);
732 tor_assert(fromlen<INT_MAX);
733 tor_assert(tolen >= crypto_pk_keysize(env));
735 r = RSA_public_encrypt((int)fromlen,
736 (unsigned char*)from, (unsigned char*)to,
737 env->key, crypto_get_rsa_padding(padding));
738 if (r<0) {
739 crypto_log_errors(LOG_WARN, "performing RSA encryption");
740 return -1;
742 return r;
745 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
746 * in <b>env</b>, using the padding method <b>padding</b>. On success,
747 * write the result to <b>to</b>, and return the number of bytes
748 * written. On failure, return -1.
750 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
751 * at least the length of the modulus of <b>env</b>.
754 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
755 size_t tolen,
756 const char *from, size_t fromlen,
757 int padding, int warnOnFailure)
759 int r;
760 tor_assert(env);
761 tor_assert(from);
762 tor_assert(to);
763 tor_assert(env->key);
764 tor_assert(fromlen<INT_MAX);
765 tor_assert(tolen >= crypto_pk_keysize(env));
766 if (!env->key->p)
767 /* Not a private key */
768 return -1;
770 r = RSA_private_decrypt((int)fromlen,
771 (unsigned char*)from, (unsigned char*)to,
772 env->key, crypto_get_rsa_padding(padding));
774 if (r<0) {
775 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
776 "performing RSA decryption");
777 return -1;
779 return r;
782 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
783 * public key in <b>env</b>, using PKCS1 padding. On success, write the
784 * signed data to <b>to</b>, and return the number of bytes written.
785 * On failure, return -1.
787 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
788 * at least the length of the modulus of <b>env</b>.
791 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
792 size_t tolen,
793 const char *from, size_t fromlen)
795 int r;
796 tor_assert(env);
797 tor_assert(from);
798 tor_assert(to);
799 tor_assert(fromlen < INT_MAX);
800 tor_assert(tolen >= crypto_pk_keysize(env));
801 r = RSA_public_decrypt((int)fromlen,
802 (unsigned char*)from, (unsigned char*)to,
803 env->key, RSA_PKCS1_PADDING);
805 if (r<0) {
806 crypto_log_errors(LOG_WARN, "checking RSA signature");
807 return -1;
809 return r;
812 /** Check a siglen-byte long signature at <b>sig</b> against
813 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
814 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
815 * SHA1(data). Else return -1.
818 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
819 size_t datalen, const char *sig, size_t siglen)
821 char digest[DIGEST_LEN];
822 char *buf;
823 size_t buflen;
824 int r;
826 tor_assert(env);
827 tor_assert(data);
828 tor_assert(sig);
829 tor_assert(datalen < SIZE_T_CEILING);
830 tor_assert(siglen < SIZE_T_CEILING);
832 if (crypto_digest(digest,data,datalen)<0) {
833 log_warn(LD_BUG, "couldn't compute digest");
834 return -1;
836 buflen = crypto_pk_keysize(env)+1;
837 buf = tor_malloc(buflen);
838 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
839 if (r != DIGEST_LEN) {
840 log_warn(LD_CRYPTO, "Invalid signature");
841 tor_free(buf);
842 return -1;
844 if (memcmp(buf, digest, DIGEST_LEN)) {
845 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
846 tor_free(buf);
847 return -1;
849 tor_free(buf);
851 return 0;
854 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
855 * <b>env</b>, using PKCS1 padding. On success, write the signature to
856 * <b>to</b>, and return the number of bytes written. On failure, return
857 * -1.
859 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
860 * at least the length of the modulus of <b>env</b>.
863 crypto_pk_private_sign(crypto_pk_env_t *env, char *to, size_t tolen,
864 const char *from, size_t fromlen)
866 int r;
867 tor_assert(env);
868 tor_assert(from);
869 tor_assert(to);
870 tor_assert(fromlen < INT_MAX);
871 tor_assert(tolen >= crypto_pk_keysize(env));
872 if (!env->key->p)
873 /* Not a private key */
874 return -1;
876 r = RSA_private_encrypt((int)fromlen,
877 (unsigned char*)from, (unsigned char*)to,
878 env->key, RSA_PKCS1_PADDING);
879 if (r<0) {
880 crypto_log_errors(LOG_WARN, "generating RSA signature");
881 return -1;
883 return r;
886 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
887 * <b>from</b>; sign the data with the private key in <b>env</b>, and
888 * store it in <b>to</b>. Return the number of bytes written on
889 * success, and -1 on failure.
891 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
892 * at least the length of the modulus of <b>env</b>.
895 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to, size_t tolen,
896 const char *from, size_t fromlen)
898 int r;
899 char digest[DIGEST_LEN];
900 if (crypto_digest(digest,from,fromlen)<0)
901 return -1;
902 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
903 memset(digest, 0, sizeof(digest));
904 return r;
907 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
908 * bytes of data from <b>from</b>, with padding type 'padding',
909 * storing the results on <b>to</b>.
911 * If no padding is used, the public key must be at least as large as
912 * <b>from</b>.
914 * Returns the number of bytes written on success, -1 on failure.
916 * The encrypted data consists of:
917 * - The source data, padded and encrypted with the public key, if the
918 * padded source data is no longer than the public key, and <b>force</b>
919 * is false, OR
920 * - The beginning of the source data prefixed with a 16-byte symmetric key,
921 * padded and encrypted with the public key; followed by the rest of
922 * the source data encrypted in AES-CTR mode with the symmetric key.
925 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
926 char *to, size_t tolen,
927 const char *from,
928 size_t fromlen,
929 int padding, int force)
931 int overhead, outlen, r;
932 size_t pkeylen, symlen;
933 crypto_cipher_env_t *cipher = NULL;
934 char *buf = NULL;
936 tor_assert(env);
937 tor_assert(from);
938 tor_assert(to);
939 tor_assert(fromlen < SIZE_T_CEILING);
941 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
942 pkeylen = crypto_pk_keysize(env);
944 if (padding == PK_NO_PADDING && fromlen < pkeylen)
945 return -1;
947 if (!force && fromlen+overhead <= pkeylen) {
948 /* It all fits in a single encrypt. */
949 return crypto_pk_public_encrypt(env,to,
950 tolen,
951 from,fromlen,padding);
953 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
954 tor_assert(tolen >= pkeylen);
956 cipher = crypto_new_cipher_env();
957 if (!cipher) return -1;
958 if (crypto_cipher_generate_key(cipher)<0)
959 goto err;
960 /* You can't just run around RSA-encrypting any bitstream: if it's
961 * greater than the RSA key, then OpenSSL will happily encrypt, and
962 * later decrypt to the wrong value. So we set the first bit of
963 * 'cipher->key' to 0 if we aren't padding. This means that our
964 * symmetric key is really only 127 bits.
966 if (padding == PK_NO_PADDING)
967 cipher->key[0] &= 0x7f;
968 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
969 goto err;
970 buf = tor_malloc(pkeylen+1);
971 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
972 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
974 /* Length of symmetrically encrypted data. */
975 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
977 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
978 if (outlen!=(int)pkeylen) {
979 goto err;
981 r = crypto_cipher_encrypt(cipher, to+outlen,
982 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
984 if (r<0) goto err;
985 memset(buf, 0, pkeylen);
986 tor_free(buf);
987 crypto_free_cipher_env(cipher);
988 tor_assert(outlen+symlen < INT_MAX);
989 return (int)(outlen + symlen);
990 err:
991 if (buf) {
992 memset(buf, 0, pkeylen);
993 tor_free(buf);
995 if (cipher) crypto_free_cipher_env(cipher);
996 return -1;
999 /** Invert crypto_pk_public_hybrid_encrypt. */
1001 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1002 char *to,
1003 size_t tolen,
1004 const char *from,
1005 size_t fromlen,
1006 int padding, int warnOnFailure)
1008 int outlen, r;
1009 size_t pkeylen;
1010 crypto_cipher_env_t *cipher = NULL;
1011 char *buf = NULL;
1013 tor_assert(fromlen < SIZE_T_CEILING);
1014 pkeylen = crypto_pk_keysize(env);
1016 if (fromlen <= pkeylen) {
1017 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1018 warnOnFailure);
1021 buf = tor_malloc(pkeylen+1);
1022 outlen = crypto_pk_private_decrypt(env,buf,pkeylen+1,from,pkeylen,padding,
1023 warnOnFailure);
1024 if (outlen<0) {
1025 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1026 "Error decrypting public-key data");
1027 goto err;
1029 if (outlen < CIPHER_KEY_LEN) {
1030 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1031 "No room for a symmetric key");
1032 goto err;
1034 cipher = crypto_create_init_cipher(buf, 0);
1035 if (!cipher) {
1036 goto err;
1038 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1039 outlen -= CIPHER_KEY_LEN;
1040 tor_assert(tolen - outlen >= fromlen - pkeylen);
1041 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1042 if (r<0)
1043 goto err;
1044 memset(buf,0,pkeylen);
1045 tor_free(buf);
1046 crypto_free_cipher_env(cipher);
1047 tor_assert(outlen + fromlen < INT_MAX);
1048 return (int)(outlen + (fromlen-pkeylen));
1049 err:
1050 memset(buf,0,pkeylen);
1051 tor_free(buf);
1052 if (cipher) crypto_free_cipher_env(cipher);
1053 return -1;
1056 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1057 * Return -1 on error, or the number of characters used on success.
1060 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1062 int len;
1063 unsigned char *buf, *cp;
1064 len = i2d_RSAPublicKey(pk->key, NULL);
1065 if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
1066 return -1;
1067 cp = buf = tor_malloc(len+1);
1068 len = i2d_RSAPublicKey(pk->key, &cp);
1069 if (len < 0) {
1070 crypto_log_errors(LOG_WARN,"encoding public key");
1071 tor_free(buf);
1072 return -1;
1074 /* We don't encode directly into 'dest', because that would be illegal
1075 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1077 memcpy(dest,buf,len);
1078 tor_free(buf);
1079 return len;
1082 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1083 * success and NULL on failure.
1085 crypto_pk_env_t *
1086 crypto_pk_asn1_decode(const char *str, size_t len)
1088 RSA *rsa;
1089 unsigned char *buf;
1090 /* This ifdef suppresses a type warning. Take out the first case once
1091 * everybody is using OpenSSL 0.9.7 or later.
1093 const unsigned char *cp;
1094 cp = buf = tor_malloc(len);
1095 memcpy(buf,str,len);
1096 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1097 tor_free(buf);
1098 if (!rsa) {
1099 crypto_log_errors(LOG_WARN,"decoding public key");
1100 return NULL;
1102 return _crypto_new_pk_env_rsa(rsa);
1105 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1106 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1107 * Return 0 on success, -1 on failure.
1110 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1112 unsigned char *buf, *bufp;
1113 int len;
1115 len = i2d_RSAPublicKey(pk->key, NULL);
1116 if (len < 0)
1117 return -1;
1118 buf = bufp = tor_malloc(len+1);
1119 len = i2d_RSAPublicKey(pk->key, &bufp);
1120 if (len < 0) {
1121 crypto_log_errors(LOG_WARN,"encoding public key");
1122 tor_free(buf);
1123 return -1;
1125 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1126 tor_free(buf);
1127 return -1;
1129 tor_free(buf);
1130 return 0;
1133 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1134 * every four spaces. */
1135 /* static */ void
1136 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1138 int n = 0;
1139 char *end = out+outlen;
1140 tor_assert(outlen < SIZE_T_CEILING);
1142 while (*in && out<end) {
1143 *out++ = *in++;
1144 if (++n == 4 && *in && out<end) {
1145 n = 0;
1146 *out++ = ' ';
1149 tor_assert(out<end);
1150 *out = '\0';
1153 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1154 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1155 * space). Return 0 on success, -1 on failure.
1157 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1158 * of the public key, converted to hexadecimal, in upper case, with a
1159 * space after every four digits.
1161 * If <b>add_space</b> is false, omit the spaces.
1164 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1166 char digest[DIGEST_LEN];
1167 char hexdigest[HEX_DIGEST_LEN+1];
1168 if (crypto_pk_get_digest(pk, digest)) {
1169 return -1;
1171 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1172 if (add_space) {
1173 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1174 } else {
1175 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1177 return 0;
1180 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1183 crypto_pk_check_fingerprint_syntax(const char *s)
1185 int i;
1186 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1187 if ((i%5) == 4) {
1188 if (!TOR_ISSPACE(s[i])) return 0;
1189 } else {
1190 if (!TOR_ISXDIGIT(s[i])) return 0;
1193 if (s[FINGERPRINT_LEN]) return 0;
1194 return 1;
1197 /* symmetric crypto */
1199 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1200 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1203 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1205 tor_assert(env);
1207 return crypto_rand(env->key, CIPHER_KEY_LEN);
1210 /** Set the symmetric key for the cipher in <b>env</b> to the first
1211 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1212 * Return 0 on success, -1 on failure.
1215 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1217 tor_assert(env);
1218 tor_assert(key);
1220 if (!env->key)
1221 return -1;
1223 memcpy(env->key, key, CIPHER_KEY_LEN);
1224 return 0;
1227 /** Generate an initialization vector for our AES-CTR cipher; store it
1228 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1229 void
1230 crypto_cipher_generate_iv(char *iv_out)
1232 crypto_rand(iv_out, CIPHER_IV_LEN);
1235 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1236 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1237 * <b>iv</b>. */
1239 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1241 tor_assert(env);
1242 tor_assert(iv);
1243 aes_set_iv(env->cipher, iv);
1244 return 0;
1247 /** Return a pointer to the key set for the cipher in <b>env</b>.
1249 const char *
1250 crypto_cipher_get_key(crypto_cipher_env_t *env)
1252 return env->key;
1255 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1256 * success, -1 on failure.
1259 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1261 tor_assert(env);
1263 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1264 return 0;
1267 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1268 * success, -1 on failure.
1271 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1273 tor_assert(env);
1275 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1276 return 0;
1279 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1280 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1281 * On failure, return -1.
1284 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1285 const char *from, size_t fromlen)
1287 tor_assert(env);
1288 tor_assert(env->cipher);
1289 tor_assert(from);
1290 tor_assert(fromlen);
1291 tor_assert(to);
1292 tor_assert(fromlen < SIZE_T_CEILING);
1294 aes_crypt(env->cipher, from, fromlen, to);
1295 return 0;
1298 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1299 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1300 * On failure, return -1.
1303 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1304 const char *from, size_t fromlen)
1306 tor_assert(env);
1307 tor_assert(from);
1308 tor_assert(to);
1309 tor_assert(fromlen < SIZE_T_CEILING);
1311 aes_crypt(env->cipher, from, fromlen, to);
1312 return 0;
1315 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1316 * on success, return 0. On failure, return -1.
1319 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1321 tor_assert(len < SIZE_T_CEILING);
1322 aes_crypt_inplace(env->cipher, buf, len);
1323 return 0;
1326 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1327 * <b>cipher</b> to the buffer in <b>to</b> of length
1328 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1329 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1330 * number of bytes written, on failure, return -1.
1332 * This function adjusts the current position of the counter in <b>cipher</b>
1333 * to immediately after the encrypted data.
1336 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1337 char *to, size_t tolen,
1338 const char *from, size_t fromlen)
1340 tor_assert(cipher);
1341 tor_assert(from);
1342 tor_assert(to);
1343 tor_assert(fromlen < INT_MAX);
1345 if (fromlen < 1)
1346 return -1;
1347 if (tolen < fromlen + CIPHER_IV_LEN)
1348 return -1;
1350 crypto_cipher_generate_iv(to);
1351 if (crypto_cipher_set_iv(cipher, to)<0)
1352 return -1;
1353 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1354 return (int)(fromlen + CIPHER_IV_LEN);
1357 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1358 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1359 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1360 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1361 * number of bytes written, on failure, return -1.
1363 * This function adjusts the current position of the counter in <b>cipher</b>
1364 * to immediately after the decrypted data.
1367 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1368 char *to, size_t tolen,
1369 const char *from, size_t fromlen)
1371 tor_assert(cipher);
1372 tor_assert(from);
1373 tor_assert(to);
1374 tor_assert(fromlen < INT_MAX);
1376 if (fromlen <= CIPHER_IV_LEN)
1377 return -1;
1378 if (tolen < fromlen - CIPHER_IV_LEN)
1379 return -1;
1381 if (crypto_cipher_set_iv(cipher, from)<0)
1382 return -1;
1383 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1384 return (int)(fromlen - CIPHER_IV_LEN);
1387 /* SHA-1 */
1389 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1390 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1391 * Return 0 on success, -1 on failure.
1394 crypto_digest(char *digest, const char *m, size_t len)
1396 tor_assert(m);
1397 tor_assert(digest);
1398 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1401 /** Intermediate information about the digest of a stream of data. */
1402 struct crypto_digest_env_t {
1403 SHA_CTX d;
1406 /** Allocate and return a new digest object.
1408 crypto_digest_env_t *
1409 crypto_new_digest_env(void)
1411 crypto_digest_env_t *r;
1412 r = tor_malloc(sizeof(crypto_digest_env_t));
1413 SHA1_Init(&r->d);
1414 return r;
1417 /** Deallocate a digest object.
1419 void
1420 crypto_free_digest_env(crypto_digest_env_t *digest)
1422 memset(digest, 0, sizeof(crypto_digest_env_t));
1423 tor_free(digest);
1426 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1428 void
1429 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1430 size_t len)
1432 tor_assert(digest);
1433 tor_assert(data);
1434 /* Using the SHA1_*() calls directly means we don't support doing
1435 * SHA1 in hardware. But so far the delay of getting the question
1436 * to the hardware, and hearing the answer, is likely higher than
1437 * just doing it ourselves. Hashes are fast.
1439 SHA1_Update(&digest->d, (void*)data, len);
1442 /** Compute the hash of the data that has been passed to the digest
1443 * object; write the first out_len bytes of the result to <b>out</b>.
1444 * <b>out_len</b> must be \<= DIGEST_LEN.
1446 void
1447 crypto_digest_get_digest(crypto_digest_env_t *digest,
1448 char *out, size_t out_len)
1450 unsigned char r[DIGEST_LEN];
1451 SHA_CTX tmpctx;
1452 tor_assert(digest);
1453 tor_assert(out);
1454 tor_assert(out_len <= DIGEST_LEN);
1455 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1456 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1457 SHA1_Final(r, &tmpctx);
1458 memcpy(out, r, out_len);
1459 memset(r, 0, sizeof(r));
1462 /** Allocate and return a new digest object with the same state as
1463 * <b>digest</b>
1465 crypto_digest_env_t *
1466 crypto_digest_dup(const crypto_digest_env_t *digest)
1468 crypto_digest_env_t *r;
1469 tor_assert(digest);
1470 r = tor_malloc(sizeof(crypto_digest_env_t));
1471 memcpy(r,digest,sizeof(crypto_digest_env_t));
1472 return r;
1475 /** Replace the state of the digest object <b>into</b> with the state
1476 * of the digest object <b>from</b>.
1478 void
1479 crypto_digest_assign(crypto_digest_env_t *into,
1480 const crypto_digest_env_t *from)
1482 tor_assert(into);
1483 tor_assert(from);
1484 memcpy(into,from,sizeof(crypto_digest_env_t));
1487 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1488 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1489 * in <b>hmac_out</b>.
1491 void
1492 crypto_hmac_sha1(char *hmac_out,
1493 const char *key, size_t key_len,
1494 const char *msg, size_t msg_len)
1496 tor_assert(key_len < INT_MAX);
1497 tor_assert(msg_len < INT_MAX);
1498 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1499 (unsigned char*)hmac_out, NULL);
1502 /* DH */
1504 /** Shared P parameter for our DH key exchanged. */
1505 static BIGNUM *dh_param_p = NULL;
1506 /** Shared G parameter for our DH key exchanges. */
1507 static BIGNUM *dh_param_g = NULL;
1509 /** Initialize dh_param_p and dh_param_g if they are not already
1510 * set. */
1511 static void
1512 init_dh_param(void)
1514 BIGNUM *p, *g;
1515 int r;
1516 if (dh_param_p && dh_param_g)
1517 return;
1519 p = BN_new();
1520 g = BN_new();
1521 tor_assert(p);
1522 tor_assert(g);
1524 /* This is from rfc2409, section 6.2. It's a safe prime, and
1525 supposedly it equals:
1526 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1528 r = BN_hex2bn(&p,
1529 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1530 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1531 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1532 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1533 "49286651ECE65381FFFFFFFFFFFFFFFF");
1534 tor_assert(r);
1536 r = BN_set_word(g, 2);
1537 tor_assert(r);
1538 dh_param_p = p;
1539 dh_param_g = g;
1542 #define DH_PRIVATE_KEY_BITS 320
1544 /** Allocate and return a new DH object for a key exchange.
1546 crypto_dh_env_t *
1547 crypto_dh_new(void)
1549 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1551 if (!dh_param_p)
1552 init_dh_param();
1554 if (!(res->dh = DH_new()))
1555 goto err;
1557 if (!(res->dh->p = BN_dup(dh_param_p)))
1558 goto err;
1560 if (!(res->dh->g = BN_dup(dh_param_g)))
1561 goto err;
1563 res->dh->length = DH_PRIVATE_KEY_BITS;
1565 return res;
1566 err:
1567 crypto_log_errors(LOG_WARN, "creating DH object");
1568 if (res->dh) DH_free(res->dh); /* frees p and g too */
1569 tor_free(res);
1570 return NULL;
1573 /** Return the length of the DH key in <b>dh</b>, in bytes.
1576 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1578 tor_assert(dh);
1579 return DH_size(dh->dh);
1582 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1583 * success, -1 on failure.
1586 crypto_dh_generate_public(crypto_dh_env_t *dh)
1588 again:
1589 if (!DH_generate_key(dh->dh)) {
1590 crypto_log_errors(LOG_WARN, "generating DH key");
1591 return -1;
1593 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1594 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1595 "the-universe chances really do happen. Trying again.");
1596 /* Free and clear the keys, so OpenSSL will actually try again. */
1597 BN_free(dh->dh->pub_key);
1598 BN_free(dh->dh->priv_key);
1599 dh->dh->pub_key = dh->dh->priv_key = NULL;
1600 goto again;
1602 return 0;
1605 /** Generate g^x as necessary, and write the g^x for the key exchange
1606 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1607 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1610 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1612 int bytes;
1613 tor_assert(dh);
1614 if (!dh->dh->pub_key) {
1615 if (crypto_dh_generate_public(dh)<0)
1616 return -1;
1619 tor_assert(dh->dh->pub_key);
1620 bytes = BN_num_bytes(dh->dh->pub_key);
1621 tor_assert(bytes >= 0);
1622 if (pubkey_len < (size_t)bytes) {
1623 log_warn(LD_CRYPTO,
1624 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1625 (int) pubkey_len, bytes);
1626 return -1;
1629 memset(pubkey, 0, pubkey_len);
1630 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1632 return 0;
1635 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1636 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1637 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1639 static int
1640 tor_check_dh_key(BIGNUM *bn)
1642 BIGNUM *x;
1643 char *s;
1644 tor_assert(bn);
1645 x = BN_new();
1646 tor_assert(x);
1647 if (!dh_param_p)
1648 init_dh_param();
1649 BN_set_word(x, 1);
1650 if (BN_cmp(bn,x)<=0) {
1651 log_warn(LD_CRYPTO, "DH key must be at least 2.");
1652 goto err;
1654 BN_copy(x,dh_param_p);
1655 BN_sub_word(x, 1);
1656 if (BN_cmp(bn,x)>=0) {
1657 log_warn(LD_CRYPTO, "DH key must be at most p-2.");
1658 goto err;
1660 BN_free(x);
1661 return 0;
1662 err:
1663 BN_free(x);
1664 s = BN_bn2hex(bn);
1665 log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1666 OPENSSL_free(s);
1667 return -1;
1670 #undef MIN
1671 #define MIN(a,b) ((a)<(b)?(a):(b))
1672 /** Given a DH key exchange object, and our peer's value of g^y (as a
1673 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1674 * <b>secret_bytes_out</b> bytes of shared key material and write them
1675 * to <b>secret_out</b>. Return the number of bytes generated on success,
1676 * or -1 on failure.
1678 * (We generate key material by computing
1679 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1680 * where || is concatenation.)
1682 ssize_t
1683 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1684 const char *pubkey, size_t pubkey_len,
1685 char *secret_out, size_t secret_bytes_out)
1687 char *secret_tmp = NULL;
1688 BIGNUM *pubkey_bn = NULL;
1689 size_t secret_len=0;
1690 int result=0;
1691 tor_assert(dh);
1692 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1693 tor_assert(pubkey_len < INT_MAX);
1695 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1696 (int)pubkey_len, NULL)))
1697 goto error;
1698 if (tor_check_dh_key(pubkey_bn)<0) {
1699 /* Check for invalid public keys. */
1700 log_warn(LD_CRYPTO,"Rejected invalid g^x");
1701 goto error;
1703 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1704 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1705 if (result < 0) {
1706 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1707 goto error;
1709 secret_len = result;
1710 if (crypto_expand_key_material(secret_tmp, secret_len,
1711 secret_out, secret_bytes_out)<0)
1712 goto error;
1713 secret_len = secret_bytes_out;
1715 goto done;
1716 error:
1717 result = -1;
1718 done:
1719 crypto_log_errors(LOG_WARN, "completing DH handshake");
1720 if (pubkey_bn)
1721 BN_free(pubkey_bn);
1722 tor_free(secret_tmp);
1723 if (result < 0)
1724 return result;
1725 else
1726 return secret_len;
1729 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1730 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1731 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1732 * H(K | [00]) | H(K | [01]) | ....
1734 * Return 0 on success, -1 on failure.
1737 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1738 char *key_out, size_t key_out_len)
1740 int i;
1741 char *cp, *tmp = tor_malloc(key_in_len+1);
1742 char digest[DIGEST_LEN];
1744 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1745 tor_assert(key_out_len <= DIGEST_LEN*256);
1747 memcpy(tmp, key_in, key_in_len);
1748 for (cp = key_out, i=0; cp < key_out+key_out_len;
1749 ++i, cp += DIGEST_LEN) {
1750 tmp[key_in_len] = i;
1751 if (crypto_digest(digest, tmp, key_in_len+1))
1752 goto err;
1753 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1755 memset(tmp, 0, key_in_len+1);
1756 tor_free(tmp);
1757 memset(digest, 0, sizeof(digest));
1758 return 0;
1760 err:
1761 memset(tmp, 0, key_in_len+1);
1762 tor_free(tmp);
1763 memset(digest, 0, sizeof(digest));
1764 return -1;
1767 /** Free a DH key exchange object.
1769 void
1770 crypto_dh_free(crypto_dh_env_t *dh)
1772 tor_assert(dh);
1773 tor_assert(dh->dh);
1774 DH_free(dh->dh);
1775 tor_free(dh);
1778 /* random numbers */
1780 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1781 * work for us too. */
1782 #define ADD_ENTROPY 32
1784 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1785 "release".) */
1786 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1788 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1789 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1790 * that fd without checking whether it fit in the fd_set. Thus, if the
1791 * system has not just been started up, it is unsafe to call */
1792 #define RAND_POLL_IS_SAFE \
1793 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1794 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1795 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1797 /** Seed OpenSSL's random number generator with bytes from the operating
1798 * system. <b>startup</b> should be true iff we have just started Tor and
1799 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1802 crypto_seed_rng(int startup)
1804 char buf[ADD_ENTROPY];
1805 int rand_poll_status = 0;
1807 /* local variables */
1808 #ifdef MS_WINDOWS
1809 static int provider_set = 0;
1810 static HCRYPTPROV provider;
1811 #else
1812 static const char *filenames[] = {
1813 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1815 int fd, i;
1816 size_t n;
1817 #endif
1819 #if HAVE_RAND_POLL
1820 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1821 * entropy than we do. We'll try calling that, *and* calling our own entropy
1822 * functions. If one succeeds, we'll accept the RNG as seeded. */
1823 if (startup || RAND_POLL_IS_SAFE) {
1824 rand_poll_status = RAND_poll();
1825 if (rand_poll_status == 0)
1826 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1828 #endif
1830 #ifdef MS_WINDOWS
1831 if (!provider_set) {
1832 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1833 CRYPT_VERIFYCONTEXT)) {
1834 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1835 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1836 return rand_poll_status ? 0 : -1;
1839 provider_set = 1;
1841 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1842 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1843 return rand_poll_status ? 0 : -1;
1845 RAND_seed(buf, sizeof(buf));
1846 memset(buf, 0, sizeof(buf));
1847 return 0;
1848 #else
1849 for (i = 0; filenames[i]; ++i) {
1850 fd = open(filenames[i], O_RDONLY, 0);
1851 if (fd<0) continue;
1852 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1853 n = read_all(fd, buf, sizeof(buf), 0);
1854 close(fd);
1855 if (n != sizeof(buf)) {
1856 log_warn(LD_CRYPTO,
1857 "Error reading from entropy source (read only %lu bytes).",
1858 (unsigned long)n);
1859 return -1;
1861 RAND_seed(buf, (int)sizeof(buf));
1862 memset(buf, 0, sizeof(buf));
1863 return 0;
1866 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1867 return rand_poll_status ? 0 : -1;
1868 #endif
1871 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
1872 * success, -1 on failure.
1875 crypto_rand(char *to, size_t n)
1877 int r;
1878 tor_assert(n < INT_MAX);
1879 tor_assert(to);
1880 r = RAND_bytes((unsigned char*)to, (int)n);
1881 if (r == 0)
1882 crypto_log_errors(LOG_WARN, "generating random data");
1883 return (r == 1) ? 0 : -1;
1886 /** Return a pseudorandom integer, chosen uniformly from the values
1887 * between 0 and <b>max</b>-1. */
1889 crypto_rand_int(unsigned int max)
1891 unsigned int val;
1892 unsigned int cutoff;
1893 tor_assert(max < UINT_MAX);
1894 tor_assert(max > 0); /* don't div by 0 */
1896 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1897 * distribution with clipping at the upper end of unsigned int's
1898 * range.
1900 cutoff = UINT_MAX - (UINT_MAX%max);
1901 while (1) {
1902 crypto_rand((char*)&val, sizeof(val));
1903 if (val < cutoff)
1904 return val % max;
1908 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
1909 * between 0 and <b>max</b>-1. */
1910 uint64_t
1911 crypto_rand_uint64(uint64_t max)
1913 uint64_t val;
1914 uint64_t cutoff;
1915 tor_assert(max < UINT64_MAX);
1916 tor_assert(max > 0); /* don't div by 0 */
1918 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1919 * distribution with clipping at the upper end of unsigned int's
1920 * range.
1922 cutoff = UINT64_MAX - (UINT64_MAX%max);
1923 while (1) {
1924 crypto_rand((char*)&val, sizeof(val));
1925 if (val < cutoff)
1926 return val % max;
1930 /** Generate and return a new random hostname starting with <b>prefix</b>,
1931 * ending with <b>suffix</b>, and containing no less than
1932 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
1933 * characters between. */
1934 char *
1935 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
1936 const char *suffix)
1938 char *result, *rand_bytes;
1939 int randlen, rand_bytes_len;
1940 size_t resultlen, prefixlen;
1942 tor_assert(max_rand_len >= min_rand_len);
1943 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
1944 prefixlen = strlen(prefix);
1945 resultlen = prefixlen + strlen(suffix) + randlen + 16;
1947 rand_bytes_len = ((randlen*5)+7)/8;
1948 if (rand_bytes_len % 5)
1949 rand_bytes_len += 5 - (rand_bytes_len%5);
1950 rand_bytes = tor_malloc(rand_bytes_len);
1951 crypto_rand(rand_bytes, rand_bytes_len);
1953 result = tor_malloc(resultlen);
1954 memcpy(result, prefix, prefixlen);
1955 base32_encode(result+prefixlen, resultlen-prefixlen,
1956 rand_bytes, rand_bytes_len);
1957 tor_free(rand_bytes);
1958 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
1960 return result;
1963 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
1964 * is empty. */
1965 void *
1966 smartlist_choose(const smartlist_t *sl)
1968 int len = smartlist_len(sl);
1969 if (len)
1970 return smartlist_get(sl,crypto_rand_int(len));
1971 return NULL; /* no elements to choose from */
1974 /** Scramble the elements of <b>sl</b> into a random order. */
1975 void
1976 smartlist_shuffle(smartlist_t *sl)
1978 int i;
1979 /* From the end of the list to the front, choose at random from the
1980 positions we haven't looked at yet, and swap that position into the
1981 current position. Remember to give "no swap" the same probability as
1982 any other swap. */
1983 for (i = smartlist_len(sl)-1; i > 0; --i) {
1984 int j = crypto_rand_int(i+1);
1985 smartlist_swap(sl, i, j);
1989 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1990 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1991 * bytes. Return the number of bytes written on success; -1 if
1992 * destlen is too short, or other failure.
1995 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1997 /* FFFF we might want to rewrite this along the lines of base64_decode, if
1998 * it ever shows up in the profile. */
1999 EVP_ENCODE_CTX ctx;
2000 int len, ret;
2001 tor_assert(srclen < INT_MAX);
2003 /* 48 bytes of input -> 64 bytes of output plus newline.
2004 Plus one more byte, in case I'm wrong.
2006 if (destlen < ((srclen/48)+1)*66)
2007 return -1;
2008 if (destlen > SIZE_T_CEILING)
2009 return -1;
2011 EVP_EncodeInit(&ctx);
2012 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2013 (unsigned char*)src, (int)srclen);
2014 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2015 ret += len;
2016 return ret;
2019 #define X 255
2020 #define SP 64
2021 #define PAD 65
2022 /** Internal table mapping byte values to what they represent in base64.
2023 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2024 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2025 * end-of-string. */
2026 static const uint8_t base64_decode_table[256] = {
2027 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2028 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2029 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2030 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2031 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2032 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2033 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2034 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 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,
2039 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2040 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2041 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2042 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2045 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2046 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2047 * bytes. Return the number of bytes written on success; -1 if
2048 * destlen is too short, or other failure.
2050 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2051 * spaces or padding.
2053 * NOTE 2: This implementation does not check for the correct number of
2054 * padding "=" characters at the end of the string, and does not check
2055 * for internal padding characters.
2058 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2060 #ifdef USE_OPENSSL_BASE64
2061 EVP_ENCODE_CTX ctx;
2062 int len, ret;
2063 /* 64 bytes of input -> *up to* 48 bytes of output.
2064 Plus one more byte, in case I'm wrong.
2066 if (destlen < ((srclen/64)+1)*49)
2067 return -1;
2068 if (destlen > SIZE_T_CEILING)
2069 return -1;
2071 EVP_DecodeInit(&ctx);
2072 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2073 (unsigned char*)src, srclen);
2074 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2075 ret += len;
2076 return ret;
2077 #else
2078 const char *eos = src+srclen;
2079 uint32_t n=0;
2080 int n_idx=0;
2081 char *dest_orig = dest;
2083 /* Max number of bits == srclen*6.
2084 * Number of bytes required to hold all bits == (srclen*6)/8.
2085 * Yes, we want to round down: anything that hangs over the end of a
2086 * byte is padding. */
2087 if (destlen < (srclen*3)/4)
2088 return -1;
2089 if (destlen > SIZE_T_CEILING)
2090 return -1;
2092 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2093 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2094 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2096 for ( ; src < eos; ++src) {
2097 unsigned char c = (unsigned char) *src;
2098 uint8_t v = base64_decode_table[c];
2099 switch (v) {
2100 case X:
2101 /* This character isn't allowed in base64. */
2102 return -1;
2103 case SP:
2104 /* This character is whitespace, and has no effect. */
2105 continue;
2106 case PAD:
2107 /* We've hit an = character: the data is over. */
2108 goto end_of_loop;
2109 default:
2110 /* We have an actual 6-bit value. Append it to the bits in n. */
2111 n = (n<<6) | v;
2112 if ((++n_idx) == 4) {
2113 /* We've accumulated 24 bits in n. Flush them. */
2114 *dest++ = (n>>16);
2115 *dest++ = (n>>8) & 0xff;
2116 *dest++ = (n) & 0xff;
2117 n_idx = 0;
2118 n = 0;
2122 end_of_loop:
2123 /* If we have leftover bits, we need to cope. */
2124 switch (n_idx) {
2125 case 0:
2126 default:
2127 /* No leftover bits. We win. */
2128 break;
2129 case 1:
2130 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2131 return -1;
2132 case 2:
2133 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2134 *dest++ = n >> 4;
2135 break;
2136 case 3:
2137 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2138 *dest++ = n >> 10;
2139 *dest++ = n >> 2;
2142 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2143 tor_assert((dest-dest_orig) <= INT_MAX);
2145 return (int)(dest-dest_orig);
2146 #endif
2148 #undef X
2149 #undef SP
2150 #undef PAD
2152 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2153 * and newline characters, and store the nul-terminated result in the first
2154 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2156 digest_to_base64(char *d64, const char *digest)
2158 char buf[256];
2159 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2160 buf[BASE64_DIGEST_LEN] = '\0';
2161 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2162 return 0;
2165 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2166 * trailing newline or = characters), decode it and store the result in the
2167 * first DIGEST_LEN bytes at <b>digest</b>. */
2169 digest_from_base64(char *digest, const char *d64)
2171 #ifdef USE_OPENSSL_BASE64
2172 char buf_in[BASE64_DIGEST_LEN+3];
2173 char buf[256];
2174 if (strlen(d64) != BASE64_DIGEST_LEN)
2175 return -1;
2176 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2177 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2178 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2179 return -1;
2180 memcpy(digest, buf, DIGEST_LEN);
2181 return 0;
2182 #else
2183 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2184 return 0;
2185 else
2186 return -1;
2187 #endif
2190 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2191 * that srclen*8 is a multiple of 5.
2193 void
2194 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2196 unsigned int i, bit, v, u;
2197 size_t nbits = srclen * 8;
2199 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2200 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2201 tor_assert(destlen < SIZE_T_CEILING);
2203 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2204 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2205 v = ((uint8_t)src[bit/8]) << 8;
2206 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2207 /* set u to the 5-bit value at the bit'th bit of src. */
2208 u = (v >> (11-(bit%8))) & 0x1F;
2209 dest[i] = BASE32_CHARS[u];
2211 dest[i] = '\0';
2214 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2215 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2218 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2220 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2221 * it ever shows up in the profile. */
2222 unsigned int i, j, bit;
2223 size_t nbits;
2224 char *tmp;
2225 nbits = srclen * 5;
2227 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2228 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2229 tor_assert(destlen < SIZE_T_CEILING);
2231 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2232 tmp = tor_malloc_zero(srclen);
2233 for (j = 0; j < srclen; ++j) {
2234 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2235 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2236 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2237 else {
2238 log_warn(LD_BUG, "illegal character in base32 encoded string");
2239 tor_free(tmp);
2240 return -1;
2244 /* Assemble result byte-wise by applying five possible cases. */
2245 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2246 switch (bit % 40) {
2247 case 0:
2248 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2249 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2250 break;
2251 case 8:
2252 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2253 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2254 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2255 break;
2256 case 16:
2257 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2258 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2259 break;
2260 case 24:
2261 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2262 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2263 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2264 break;
2265 case 32:
2266 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2267 ((uint8_t)tmp[(bit/5)+1]);
2268 break;
2272 memset(tmp, 0, srclen);
2273 tor_free(tmp);
2274 tmp = NULL;
2275 return 0;
2278 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2279 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2280 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2281 * are a salt; the 9th byte describes how much iteration to do.
2282 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2284 void
2285 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2286 size_t secret_len, const char *s2k_specifier)
2288 crypto_digest_env_t *d;
2289 uint8_t c;
2290 size_t count, tmplen;
2291 char *tmp;
2292 tor_assert(key_out_len < SIZE_T_CEILING);
2294 #define EXPBIAS 6
2295 c = s2k_specifier[8];
2296 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2297 #undef EXPBIAS
2299 tor_assert(key_out_len <= DIGEST_LEN);
2301 d = crypto_new_digest_env();
2302 tmplen = 8+secret_len;
2303 tmp = tor_malloc(tmplen);
2304 memcpy(tmp,s2k_specifier,8);
2305 memcpy(tmp+8,secret,secret_len);
2306 secret_len += 8;
2307 while (count) {
2308 if (count >= secret_len) {
2309 crypto_digest_add_bytes(d, tmp, secret_len);
2310 count -= secret_len;
2311 } else {
2312 crypto_digest_add_bytes(d, tmp, count);
2313 count = 0;
2316 crypto_digest_get_digest(d, key_out, key_out_len);
2317 memset(tmp, 0, tmplen);
2318 tor_free(tmp);
2319 crypto_free_digest_env(d);
2322 #ifdef TOR_IS_MULTITHREADED
2323 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2324 static void
2325 _openssl_locking_cb(int mode, int n, const char *file, int line)
2327 (void)file;
2328 (void)line;
2329 if (!_openssl_mutexes)
2330 /* This is not a really good fix for the
2331 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2332 * it can't hurt. */
2333 return;
2334 if (mode & CRYPTO_LOCK)
2335 tor_mutex_acquire(_openssl_mutexes[n]);
2336 else
2337 tor_mutex_release(_openssl_mutexes[n]);
2340 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2341 * as a lock. */
2342 struct CRYPTO_dynlock_value {
2343 tor_mutex_t *lock;
2346 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2347 * documentation in OpenSSL's docs for more info. */
2348 static struct CRYPTO_dynlock_value *
2349 _openssl_dynlock_create_cb(const char *file, int line)
2351 struct CRYPTO_dynlock_value *v;
2352 (void)file;
2353 (void)line;
2354 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2355 v->lock = tor_mutex_new();
2356 return v;
2359 /** OpenSSL callback function to acquire or release a lock: see
2360 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2361 static void
2362 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2363 const char *file, int line)
2365 (void)file;
2366 (void)line;
2367 if (mode & CRYPTO_LOCK)
2368 tor_mutex_acquire(v->lock);
2369 else
2370 tor_mutex_release(v->lock);
2373 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2374 * documentation in OpenSSL's docs for more info. */
2375 static void
2376 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2377 const char *file, int line)
2379 (void)file;
2380 (void)line;
2381 tor_mutex_free(v->lock);
2382 tor_free(v);
2385 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2386 * multithreaded. */
2387 static int
2388 setup_openssl_threading(void)
2390 int i;
2391 int n = CRYPTO_num_locks();
2392 _n_openssl_mutexes = n;
2393 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2394 for (i=0; i < n; ++i)
2395 _openssl_mutexes[i] = tor_mutex_new();
2396 CRYPTO_set_locking_callback(_openssl_locking_cb);
2397 CRYPTO_set_id_callback(tor_get_thread_id);
2398 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2399 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2400 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2401 return 0;
2403 #else
2404 static int
2405 setup_openssl_threading(void)
2407 return 0;
2409 #endif