Merge remote branch 'origin/maint-0.2.1' into maint-0.2.2
[tor/rransom.git] / src / common / crypto.c
blob15b58188ed68fa1b81c339b880840a61ff58e6d3
1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file crypto.c
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL.
11 **/
13 #include "orconfig.h"
15 #ifdef MS_WINDOWS
16 #define WIN32_WINNT 0x400
17 #define _WIN32_WINNT 0x400
18 #define WIN32_LEAN_AND_MEAN
19 #include <windows.h>
20 #include <wincrypt.h>
21 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
22 * use either definition. */
23 #undef OCSP_RESPONSE
24 #endif
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/engine.h>
31 #include <openssl/rand.h>
32 #include <openssl/opensslv.h>
33 #include <openssl/bn.h>
34 #include <openssl/dh.h>
35 #include <openssl/conf.h>
36 #include <openssl/hmac.h>
38 #ifdef HAVE_CTYPE_H
39 #include <ctype.h>
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 #ifdef HAVE_SYS_FCNTL_H
48 #include <sys/fcntl.h>
49 #endif
51 #define CRYPTO_PRIVATE
52 #include "crypto.h"
53 #include "../common/torlog.h"
54 #include "aes.h"
55 #include "../common/util.h"
56 #include "container.h"
57 #include "compat.h"
59 #if OPENSSL_VERSION_NUMBER < 0x00907000l
60 #error "We require OpenSSL >= 0.9.7"
61 #endif
63 #include <openssl/engine.h>
65 #ifdef ANDROID
66 /* Android's OpenSSL seems to have removed all of its Engine support. */
67 #define DISABLE_ENGINES
68 #endif
70 #if OPENSSL_VERSION_NUMBER < 0x00908000l
71 /* On OpenSSL versions before 0.9.8, there is no working SHA256
72 * implementation, so we use Tom St Denis's nice speedy one, slightly adapted
73 * to our needs */
74 #define SHA256_CTX sha256_state
75 #define SHA256_Init sha256_init
76 #define SHA256_Update sha256_process
77 #define LTC_ARGCHK(x) tor_assert(x)
78 #include "sha256.c"
79 #define SHA256_Final(a,b) sha256_done(b,a)
81 static unsigned char *
82 SHA256(const unsigned char *m, size_t len, unsigned char *d)
84 SHA256_CTX ctx;
85 SHA256_Init(&ctx);
86 SHA256_Update(&ctx, m, len);
87 SHA256_Final(d, &ctx);
88 return d;
90 #endif
92 /** Macro: is k a valid RSA public or private key? */
93 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
94 /** Macro: is k a valid RSA private key? */
95 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
97 #ifdef TOR_IS_MULTITHREADED
98 /** A number of preallocated mutexes for use by OpenSSL. */
99 static tor_mutex_t **_openssl_mutexes = NULL;
100 /** How many mutexes have we allocated for use by OpenSSL? */
101 static int _n_openssl_mutexes = 0;
102 #endif
104 /** A public key, or a public/private key-pair. */
105 struct crypto_pk_env_t
107 int refs; /* reference counting so we don't have to copy keys */
108 RSA *key;
111 /** Key and stream information for a stream cipher. */
112 struct crypto_cipher_env_t
114 char key[CIPHER_KEY_LEN];
115 aes_cnt_cipher_t *cipher;
118 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
119 * while we're waiting for the second.*/
120 struct crypto_dh_env_t {
121 DH *dh;
124 static int setup_openssl_threading(void);
125 static int tor_check_dh_key(int severity, BIGNUM *bn);
127 /** Return the number of bytes added by padding method <b>padding</b>.
129 static INLINE int
130 crypto_get_rsa_padding_overhead(int padding)
132 switch (padding)
134 case RSA_NO_PADDING: return 0;
135 case RSA_PKCS1_OAEP_PADDING: return 42;
136 case RSA_PKCS1_PADDING: return 11;
137 default: tor_assert(0); return -1;
141 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
143 static INLINE int
144 crypto_get_rsa_padding(int padding)
146 switch (padding)
148 case PK_NO_PADDING: return RSA_NO_PADDING;
149 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
150 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
151 default: tor_assert(0); return -1;
155 /** Boolean: has OpenSSL's crypto been initialized? */
156 static int _crypto_global_initialized = 0;
158 /** Log all pending crypto errors at level <b>severity</b>. Use
159 * <b>doing</b> to describe our current activities.
161 static void
162 crypto_log_errors(int severity, const char *doing)
164 unsigned long err;
165 const char *msg, *lib, *func;
166 while ((err = ERR_get_error()) != 0) {
167 msg = (const char*)ERR_reason_error_string(err);
168 lib = (const char*)ERR_lib_error_string(err);
169 func = (const char*)ERR_func_error_string(err);
170 if (!msg) msg = "(null)";
171 if (!lib) lib = "(null)";
172 if (!func) func = "(null)";
173 if (doing) {
174 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
175 doing, msg, lib, func);
176 } else {
177 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
182 #ifndef DISABLE_ENGINES
183 /** Log any OpenSSL engines we're using at NOTICE. */
184 static void
185 log_engine(const char *fn, ENGINE *e)
187 if (e) {
188 const char *name, *id;
189 name = ENGINE_get_name(e);
190 id = ENGINE_get_id(e);
191 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
192 name?name:"?", id?id:"?", fn);
193 } else {
194 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
197 #endif
199 #ifndef DISABLE_ENGINES
200 /** Try to load an engine in a shared library via fully qualified path.
202 static ENGINE *
203 try_load_engine(const char *path, const char *engine)
205 ENGINE *e = ENGINE_by_id("dynamic");
206 if (e) {
207 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
208 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
209 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
210 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
211 ENGINE_free(e);
212 e = NULL;
215 return e;
217 #endif
219 /** Initialize the crypto library. Return 0 on success, -1 on failure.
222 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
224 if (!_crypto_global_initialized) {
225 ERR_load_crypto_strings();
226 OpenSSL_add_all_algorithms();
227 _crypto_global_initialized = 1;
228 setup_openssl_threading();
229 if (useAccel > 0) {
230 #ifdef DISABLE_ENGINES
231 (void)accelName;
232 (void)accelDir;
233 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
234 #else
235 ENGINE *e = NULL;
237 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
238 ENGINE_load_builtin_engines();
239 ENGINE_register_all_complete();
241 if (accelName) {
242 if (accelDir) {
243 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
244 " via path \"%s\".", accelName, accelDir);
245 e = try_load_engine(accelName, accelDir);
246 } else {
247 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
248 " acceleration support.", accelName);
249 e = ENGINE_by_id(accelName);
251 if (!e) {
252 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
253 accelName);
254 } else {
255 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
256 accelName);
259 if (e) {
260 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
261 " setting default ciphers.");
262 ENGINE_set_default(e, ENGINE_METHOD_ALL);
264 log_engine("RSA", ENGINE_get_default_RSA());
265 log_engine("DH", ENGINE_get_default_DH());
266 log_engine("RAND", ENGINE_get_default_RAND());
267 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
268 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
269 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
270 #endif
271 } else {
272 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
274 return crypto_seed_rng(1);
276 return 0;
279 /** Free crypto resources held by this thread. */
280 void
281 crypto_thread_cleanup(void)
283 ERR_remove_state(0);
286 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
289 crypto_global_cleanup(void)
291 EVP_cleanup();
292 ERR_remove_state(0);
293 ERR_free_strings();
295 #ifndef DISABLE_ENGINES
296 ENGINE_cleanup();
297 #endif
299 CONF_modules_unload(1);
300 CRYPTO_cleanup_all_ex_data();
301 #ifdef TOR_IS_MULTITHREADED
302 if (_n_openssl_mutexes) {
303 int n = _n_openssl_mutexes;
304 tor_mutex_t **ms = _openssl_mutexes;
305 int i;
306 _openssl_mutexes = NULL;
307 _n_openssl_mutexes = 0;
308 for (i=0;i<n;++i) {
309 tor_mutex_free(ms[i]);
311 tor_free(ms);
313 #endif
314 return 0;
317 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
318 crypto_pk_env_t *
319 _crypto_new_pk_env_rsa(RSA *rsa)
321 crypto_pk_env_t *env;
322 tor_assert(rsa);
323 env = tor_malloc(sizeof(crypto_pk_env_t));
324 env->refs = 1;
325 env->key = rsa;
326 return env;
329 /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
330 * returns NULL if this isn't an RSA key. */
331 crypto_pk_env_t *
332 _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
334 RSA *rsa;
335 if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
336 return NULL;
337 return _crypto_new_pk_env_rsa(rsa);
340 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
341 * crypto_pk_env_t. */
342 RSA *
343 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
345 return env->key;
348 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
349 * private is set, include the private-key portion of the key. */
350 EVP_PKEY *
351 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
353 RSA *key = NULL;
354 EVP_PKEY *pkey = NULL;
355 tor_assert(env->key);
356 if (private) {
357 if (!(key = RSAPrivateKey_dup(env->key)))
358 goto error;
359 } else {
360 if (!(key = RSAPublicKey_dup(env->key)))
361 goto error;
363 if (!(pkey = EVP_PKEY_new()))
364 goto error;
365 if (!(EVP_PKEY_assign_RSA(pkey, key)))
366 goto error;
367 return pkey;
368 error:
369 if (pkey)
370 EVP_PKEY_free(pkey);
371 if (key)
372 RSA_free(key);
373 return NULL;
376 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
378 DH *
379 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
381 return dh->dh;
384 /** Allocate and return storage for a public key. The key itself will not yet
385 * be set.
387 crypto_pk_env_t *
388 crypto_new_pk_env(void)
390 RSA *rsa;
392 rsa = RSA_new();
393 if (!rsa) return NULL;
394 return _crypto_new_pk_env_rsa(rsa);
397 /** Release a reference to an asymmetric key; when all the references
398 * are released, free the key.
400 void
401 crypto_free_pk_env(crypto_pk_env_t *env)
403 if (!env)
404 return;
406 if (--env->refs > 0)
407 return;
408 tor_assert(env->refs == 0);
410 if (env->key)
411 RSA_free(env->key);
413 tor_free(env);
416 /** Create a new symmetric cipher for a given key and encryption flag
417 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
418 * on failure.
420 crypto_cipher_env_t *
421 crypto_create_init_cipher(const char *key, int encrypt_mode)
423 int r;
424 crypto_cipher_env_t *crypto = NULL;
426 if (! (crypto = crypto_new_cipher_env())) {
427 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
428 return NULL;
431 crypto_cipher_set_key(crypto, key);
433 if (encrypt_mode)
434 r = crypto_cipher_encrypt_init_cipher(crypto);
435 else
436 r = crypto_cipher_decrypt_init_cipher(crypto);
438 if (r)
439 goto error;
440 return crypto;
442 error:
443 if (crypto)
444 crypto_free_cipher_env(crypto);
445 return NULL;
448 /** Allocate and return a new symmetric cipher.
450 crypto_cipher_env_t *
451 crypto_new_cipher_env(void)
453 crypto_cipher_env_t *env;
455 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
456 env->cipher = aes_new_cipher();
457 return env;
460 /** Free a symmetric cipher.
462 void
463 crypto_free_cipher_env(crypto_cipher_env_t *env)
465 if (!env)
466 return;
468 tor_assert(env->cipher);
469 aes_free_cipher(env->cipher);
470 memset(env, 0, sizeof(crypto_cipher_env_t));
471 tor_free(env);
474 /* public key crypto */
476 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
477 * Return 0 on success, -1 on failure.
480 crypto_pk_generate_key_with_bits(crypto_pk_env_t *env, int bits)
482 tor_assert(env);
484 if (env->key)
485 RSA_free(env->key);
486 #if OPENSSL_VERSION_NUMBER < 0x00908000l
487 /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
488 env->key = RSA_generate_key(bits, 65537, NULL, NULL);
489 #else
490 /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
492 BIGNUM *e = BN_new();
493 RSA *r = NULL;
494 if (!e)
495 goto done;
496 if (! BN_set_word(e, 65537))
497 goto done;
498 r = RSA_new();
499 if (!r)
500 goto done;
501 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
502 goto done;
504 env->key = r;
505 r = NULL;
506 done:
507 if (e)
508 BN_free(e);
509 if (r)
510 RSA_free(r);
512 #endif
513 if (!env->key) {
514 crypto_log_errors(LOG_WARN, "generating RSA key");
515 return -1;
518 return 0;
521 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
522 * Return 0 on success, -1 on failure.
524 /* Used here, and used for testing. */
526 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
527 const char *s)
529 BIO *b;
531 tor_assert(env);
532 tor_assert(s);
534 /* Create a read-only memory BIO, backed by the NUL-terminated string 's' */
535 b = BIO_new_mem_buf((char*)s, -1);
537 if (env->key)
538 RSA_free(env->key);
540 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
542 BIO_free(b);
544 if (!env->key) {
545 crypto_log_errors(LOG_WARN, "Error parsing private key");
546 return -1;
548 return 0;
551 /** Read a PEM-encoded private key from the file named by
552 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
555 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
556 const char *keyfile)
558 char *contents;
559 int r;
561 /* Read the file into a string. */
562 contents = read_file_to_str(keyfile, 0, NULL);
563 if (!contents) {
564 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
565 return -1;
568 /* Try to parse it. */
569 r = crypto_pk_read_private_key_from_string(env, contents);
570 tor_free(contents);
571 if (r)
572 return -1; /* read_private_key_from_string already warned, so we don't.*/
574 /* Make sure it's valid. */
575 if (crypto_pk_check_key(env) <= 0)
576 return -1;
578 return 0;
581 /** Helper function to implement crypto_pk_write_*_key_to_string. */
582 static int
583 crypto_pk_write_key_to_string_impl(crypto_pk_env_t *env, char **dest,
584 size_t *len, int is_public)
586 BUF_MEM *buf;
587 BIO *b;
588 int r;
590 tor_assert(env);
591 tor_assert(env->key);
592 tor_assert(dest);
594 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
596 /* Now you can treat b as if it were a file. Just use the
597 * PEM_*_bio_* functions instead of the non-bio variants.
599 if (is_public)
600 r = PEM_write_bio_RSAPublicKey(b, env->key);
601 else
602 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
604 if (!r) {
605 crypto_log_errors(LOG_WARN, "writing RSA key to string");
606 BIO_free(b);
607 return -1;
610 BIO_get_mem_ptr(b, &buf);
611 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
612 BIO_free(b);
614 *dest = tor_malloc(buf->length+1);
615 memcpy(*dest, buf->data, buf->length);
616 (*dest)[buf->length] = 0; /* nul terminate it */
617 *len = buf->length;
618 BUF_MEM_free(buf);
620 return 0;
623 /** PEM-encode the public key portion of <b>env</b> and write it to a
624 * newly allocated string. On success, set *<b>dest</b> to the new
625 * string, *<b>len</b> to the string's length, and return 0. On
626 * failure, return -1.
629 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
630 size_t *len)
632 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
635 /** PEM-encode the private key portion of <b>env</b> and write it to a
636 * newly allocated string. On success, set *<b>dest</b> to the new
637 * string, *<b>len</b> to the string's length, and return 0. On
638 * failure, return -1.
641 crypto_pk_write_private_key_to_string(crypto_pk_env_t *env, char **dest,
642 size_t *len)
644 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
647 /** Read a PEM-encoded public key from the first <b>len</b> characters of
648 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
649 * failure.
652 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
653 size_t len)
655 BIO *b;
657 tor_assert(env);
658 tor_assert(src);
659 tor_assert(len<INT_MAX);
661 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
663 BIO_write(b, src, (int)len);
665 if (env->key)
666 RSA_free(env->key);
667 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
668 BIO_free(b);
669 if (!env->key) {
670 crypto_log_errors(LOG_WARN, "reading public key from string");
671 return -1;
674 return 0;
677 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
678 * PEM-encoded. Return 0 on success, -1 on failure.
681 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
682 const char *fname)
684 BIO *bio;
685 char *cp;
686 long len;
687 char *s;
688 int r;
690 tor_assert(PRIVATE_KEY_OK(env));
692 if (!(bio = BIO_new(BIO_s_mem())))
693 return -1;
694 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
695 == 0) {
696 crypto_log_errors(LOG_WARN, "writing private key");
697 BIO_free(bio);
698 return -1;
700 len = BIO_get_mem_data(bio, &cp);
701 tor_assert(len >= 0);
702 s = tor_malloc(len+1);
703 memcpy(s, cp, len);
704 s[len]='\0';
705 r = write_str_to_file(fname, s, 0);
706 BIO_free(bio);
707 tor_free(s);
708 return r;
711 /** Return true iff <b>env</b> has a valid key.
714 crypto_pk_check_key(crypto_pk_env_t *env)
716 int r;
717 tor_assert(env);
719 r = RSA_check_key(env->key);
720 if (r <= 0)
721 crypto_log_errors(LOG_WARN,"checking RSA key");
722 return r;
725 /** Return true iff <b>key</b> contains the private-key portion of the RSA
726 * key. */
728 crypto_pk_key_is_private(const crypto_pk_env_t *key)
730 tor_assert(key);
731 return PRIVATE_KEY_OK(key);
734 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
735 * if a==b, and 1 if a\>b.
738 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
740 int result;
742 if (!a || !b)
743 return -1;
745 if (!a->key || !b->key)
746 return -1;
748 tor_assert(PUBLIC_KEY_OK(a));
749 tor_assert(PUBLIC_KEY_OK(b));
750 result = BN_cmp((a->key)->n, (b->key)->n);
751 if (result)
752 return result;
753 return BN_cmp((a->key)->e, (b->key)->e);
756 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
757 size_t
758 crypto_pk_keysize(crypto_pk_env_t *env)
760 tor_assert(env);
761 tor_assert(env->key);
763 return (size_t) RSA_size(env->key);
766 /** Increase the reference count of <b>env</b>, and return it.
768 crypto_pk_env_t *
769 crypto_pk_dup_key(crypto_pk_env_t *env)
771 tor_assert(env);
772 tor_assert(env->key);
774 env->refs++;
775 return env;
778 /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
779 crypto_pk_env_t *
780 crypto_pk_copy_full(crypto_pk_env_t *env)
782 RSA *new_key;
783 int privatekey = 0;
784 tor_assert(env);
785 tor_assert(env->key);
787 if (PRIVATE_KEY_OK(env)) {
788 new_key = RSAPrivateKey_dup(env->key);
789 privatekey = 1;
790 } else {
791 new_key = RSAPublicKey_dup(env->key);
793 if (!new_key) {
794 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
795 privatekey?"private":"public");
796 crypto_log_errors(LOG_ERR,
797 privatekey ? "Duplicating a private key" :
798 "Duplicating a public key");
799 tor_fragile_assert();
800 return NULL;
803 return _crypto_new_pk_env_rsa(new_key);
806 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
807 * in <b>env</b>, using the padding method <b>padding</b>. On success,
808 * write the result to <b>to</b>, and return the number of bytes
809 * written. On failure, return -1.
811 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
812 * at least the length of the modulus of <b>env</b>.
815 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to, size_t tolen,
816 const char *from, size_t fromlen, int padding)
818 int r;
819 tor_assert(env);
820 tor_assert(from);
821 tor_assert(to);
822 tor_assert(fromlen<INT_MAX);
823 tor_assert(tolen >= crypto_pk_keysize(env));
825 r = RSA_public_encrypt((int)fromlen,
826 (unsigned char*)from, (unsigned char*)to,
827 env->key, crypto_get_rsa_padding(padding));
828 if (r<0) {
829 crypto_log_errors(LOG_WARN, "performing RSA encryption");
830 return -1;
832 return r;
835 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
836 * in <b>env</b>, using the padding method <b>padding</b>. On success,
837 * write the result to <b>to</b>, and return the number of bytes
838 * written. On failure, return -1.
840 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
841 * at least the length of the modulus of <b>env</b>.
844 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
845 size_t tolen,
846 const char *from, size_t fromlen,
847 int padding, int warnOnFailure)
849 int r;
850 tor_assert(env);
851 tor_assert(from);
852 tor_assert(to);
853 tor_assert(env->key);
854 tor_assert(fromlen<INT_MAX);
855 tor_assert(tolen >= crypto_pk_keysize(env));
856 if (!env->key->p)
857 /* Not a private key */
858 return -1;
860 r = RSA_private_decrypt((int)fromlen,
861 (unsigned char*)from, (unsigned char*)to,
862 env->key, crypto_get_rsa_padding(padding));
864 if (r<0) {
865 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
866 "performing RSA decryption");
867 return -1;
869 return r;
872 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
873 * public key in <b>env</b>, using PKCS1 padding. On success, write the
874 * signed data to <b>to</b>, and return the number of bytes written.
875 * On failure, return -1.
877 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
878 * at least the length of the modulus of <b>env</b>.
881 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
882 size_t tolen,
883 const char *from, size_t fromlen)
885 int r;
886 tor_assert(env);
887 tor_assert(from);
888 tor_assert(to);
889 tor_assert(fromlen < INT_MAX);
890 tor_assert(tolen >= crypto_pk_keysize(env));
891 r = RSA_public_decrypt((int)fromlen,
892 (unsigned char*)from, (unsigned char*)to,
893 env->key, RSA_PKCS1_PADDING);
895 if (r<0) {
896 crypto_log_errors(LOG_WARN, "checking RSA signature");
897 return -1;
899 return r;
902 /** Check a siglen-byte long signature at <b>sig</b> against
903 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
904 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
905 * SHA1(data). Else return -1.
908 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
909 size_t datalen, const char *sig, size_t siglen)
911 char digest[DIGEST_LEN];
912 char *buf;
913 size_t buflen;
914 int r;
916 tor_assert(env);
917 tor_assert(data);
918 tor_assert(sig);
919 tor_assert(datalen < SIZE_T_CEILING);
920 tor_assert(siglen < SIZE_T_CEILING);
922 if (crypto_digest(digest,data,datalen)<0) {
923 log_warn(LD_BUG, "couldn't compute digest");
924 return -1;
926 buflen = crypto_pk_keysize(env)+1;
927 buf = tor_malloc(buflen);
928 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
929 if (r != DIGEST_LEN) {
930 log_warn(LD_CRYPTO, "Invalid signature");
931 tor_free(buf);
932 return -1;
934 if (memcmp(buf, digest, DIGEST_LEN)) {
935 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
936 tor_free(buf);
937 return -1;
939 tor_free(buf);
941 return 0;
944 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
945 * <b>env</b>, using PKCS1 padding. On success, write the signature to
946 * <b>to</b>, and return the number of bytes written. On failure, return
947 * -1.
949 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
950 * at least the length of the modulus of <b>env</b>.
953 crypto_pk_private_sign(crypto_pk_env_t *env, char *to, size_t tolen,
954 const char *from, size_t fromlen)
956 int r;
957 tor_assert(env);
958 tor_assert(from);
959 tor_assert(to);
960 tor_assert(fromlen < INT_MAX);
961 tor_assert(tolen >= crypto_pk_keysize(env));
962 if (!env->key->p)
963 /* Not a private key */
964 return -1;
966 r = RSA_private_encrypt((int)fromlen,
967 (unsigned char*)from, (unsigned char*)to,
968 env->key, RSA_PKCS1_PADDING);
969 if (r<0) {
970 crypto_log_errors(LOG_WARN, "generating RSA signature");
971 return -1;
973 return r;
976 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
977 * <b>from</b>; sign the data with the private key in <b>env</b>, and
978 * store it in <b>to</b>. Return the number of bytes written on
979 * success, and -1 on failure.
981 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
982 * at least the length of the modulus of <b>env</b>.
985 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to, size_t tolen,
986 const char *from, size_t fromlen)
988 int r;
989 char digest[DIGEST_LEN];
990 if (crypto_digest(digest,from,fromlen)<0)
991 return -1;
992 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
993 memset(digest, 0, sizeof(digest));
994 return r;
997 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
998 * bytes of data from <b>from</b>, with padding type 'padding',
999 * storing the results on <b>to</b>.
1001 * If no padding is used, the public key must be at least as large as
1002 * <b>from</b>.
1004 * Returns the number of bytes written on success, -1 on failure.
1006 * The encrypted data consists of:
1007 * - The source data, padded and encrypted with the public key, if the
1008 * padded source data is no longer than the public key, and <b>force</b>
1009 * is false, OR
1010 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1011 * padded and encrypted with the public key; followed by the rest of
1012 * the source data encrypted in AES-CTR mode with the symmetric key.
1015 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
1016 char *to, size_t tolen,
1017 const char *from,
1018 size_t fromlen,
1019 int padding, int force)
1021 int overhead, outlen, r;
1022 size_t pkeylen, symlen;
1023 crypto_cipher_env_t *cipher = NULL;
1024 char *buf = NULL;
1026 tor_assert(env);
1027 tor_assert(from);
1028 tor_assert(to);
1029 tor_assert(fromlen < SIZE_T_CEILING);
1031 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1032 pkeylen = crypto_pk_keysize(env);
1034 if (padding == PK_NO_PADDING && fromlen < pkeylen)
1035 return -1;
1037 if (!force && fromlen+overhead <= pkeylen) {
1038 /* It all fits in a single encrypt. */
1039 return crypto_pk_public_encrypt(env,to,
1040 tolen,
1041 from,fromlen,padding);
1043 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1044 tor_assert(tolen >= pkeylen);
1046 cipher = crypto_new_cipher_env();
1047 if (!cipher) return -1;
1048 if (crypto_cipher_generate_key(cipher)<0)
1049 goto err;
1050 /* You can't just run around RSA-encrypting any bitstream: if it's
1051 * greater than the RSA key, then OpenSSL will happily encrypt, and
1052 * later decrypt to the wrong value. So we set the first bit of
1053 * 'cipher->key' to 0 if we aren't padding. This means that our
1054 * symmetric key is really only 127 bits.
1056 if (padding == PK_NO_PADDING)
1057 cipher->key[0] &= 0x7f;
1058 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
1059 goto err;
1060 buf = tor_malloc(pkeylen+1);
1061 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1062 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1064 /* Length of symmetrically encrypted data. */
1065 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1067 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1068 if (outlen!=(int)pkeylen) {
1069 goto err;
1071 r = crypto_cipher_encrypt(cipher, to+outlen,
1072 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1074 if (r<0) goto err;
1075 memset(buf, 0, pkeylen);
1076 tor_free(buf);
1077 crypto_free_cipher_env(cipher);
1078 tor_assert(outlen+symlen < INT_MAX);
1079 return (int)(outlen + symlen);
1080 err:
1081 if (buf) {
1082 memset(buf, 0, pkeylen);
1083 tor_free(buf);
1085 if (cipher) crypto_free_cipher_env(cipher);
1086 return -1;
1089 /** Invert crypto_pk_public_hybrid_encrypt. */
1091 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1092 char *to,
1093 size_t tolen,
1094 const char *from,
1095 size_t fromlen,
1096 int padding, int warnOnFailure)
1098 int outlen, r;
1099 size_t pkeylen;
1100 crypto_cipher_env_t *cipher = NULL;
1101 char *buf = NULL;
1103 tor_assert(fromlen < SIZE_T_CEILING);
1104 pkeylen = crypto_pk_keysize(env);
1106 if (fromlen <= pkeylen) {
1107 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1108 warnOnFailure);
1111 buf = tor_malloc(pkeylen+1);
1112 outlen = crypto_pk_private_decrypt(env,buf,pkeylen+1,from,pkeylen,padding,
1113 warnOnFailure);
1114 if (outlen<0) {
1115 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1116 "Error decrypting public-key data");
1117 goto err;
1119 if (outlen < CIPHER_KEY_LEN) {
1120 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1121 "No room for a symmetric key");
1122 goto err;
1124 cipher = crypto_create_init_cipher(buf, 0);
1125 if (!cipher) {
1126 goto err;
1128 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1129 outlen -= CIPHER_KEY_LEN;
1130 tor_assert(tolen - outlen >= fromlen - pkeylen);
1131 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1132 if (r<0)
1133 goto err;
1134 memset(buf,0,pkeylen);
1135 tor_free(buf);
1136 crypto_free_cipher_env(cipher);
1137 tor_assert(outlen + fromlen < INT_MAX);
1138 return (int)(outlen + (fromlen-pkeylen));
1139 err:
1140 memset(buf,0,pkeylen);
1141 tor_free(buf);
1142 if (cipher) crypto_free_cipher_env(cipher);
1143 return -1;
1146 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1147 * Return -1 on error, or the number of characters used on success.
1150 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1152 int len;
1153 unsigned char *buf, *cp;
1154 len = i2d_RSAPublicKey(pk->key, NULL);
1155 if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
1156 return -1;
1157 cp = buf = tor_malloc(len+1);
1158 len = i2d_RSAPublicKey(pk->key, &cp);
1159 if (len < 0) {
1160 crypto_log_errors(LOG_WARN,"encoding public key");
1161 tor_free(buf);
1162 return -1;
1164 /* We don't encode directly into 'dest', because that would be illegal
1165 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1167 memcpy(dest,buf,len);
1168 tor_free(buf);
1169 return len;
1172 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1173 * success and NULL on failure.
1175 crypto_pk_env_t *
1176 crypto_pk_asn1_decode(const char *str, size_t len)
1178 RSA *rsa;
1179 unsigned char *buf;
1180 /* This ifdef suppresses a type warning. Take out the first case once
1181 * everybody is using OpenSSL 0.9.7 or later.
1183 const unsigned char *cp;
1184 cp = buf = tor_malloc(len);
1185 memcpy(buf,str,len);
1186 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1187 tor_free(buf);
1188 if (!rsa) {
1189 crypto_log_errors(LOG_WARN,"decoding public key");
1190 return NULL;
1192 return _crypto_new_pk_env_rsa(rsa);
1195 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1196 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1197 * Return 0 on success, -1 on failure.
1200 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1202 unsigned char *buf, *bufp;
1203 int len;
1205 len = i2d_RSAPublicKey(pk->key, NULL);
1206 if (len < 0)
1207 return -1;
1208 buf = bufp = tor_malloc(len+1);
1209 len = i2d_RSAPublicKey(pk->key, &bufp);
1210 if (len < 0) {
1211 crypto_log_errors(LOG_WARN,"encoding public key");
1212 tor_free(buf);
1213 return -1;
1215 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1216 tor_free(buf);
1217 return -1;
1219 tor_free(buf);
1220 return 0;
1223 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1224 * every four spaces. */
1225 /* static */ void
1226 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1228 int n = 0;
1229 char *end = out+outlen;
1230 tor_assert(outlen < SIZE_T_CEILING);
1232 while (*in && out<end) {
1233 *out++ = *in++;
1234 if (++n == 4 && *in && out<end) {
1235 n = 0;
1236 *out++ = ' ';
1239 tor_assert(out<end);
1240 *out = '\0';
1243 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1244 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1245 * space). Return 0 on success, -1 on failure.
1247 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1248 * of the public key, converted to hexadecimal, in upper case, with a
1249 * space after every four digits.
1251 * If <b>add_space</b> is false, omit the spaces.
1254 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1256 char digest[DIGEST_LEN];
1257 char hexdigest[HEX_DIGEST_LEN+1];
1258 if (crypto_pk_get_digest(pk, digest)) {
1259 return -1;
1261 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1262 if (add_space) {
1263 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1264 } else {
1265 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1267 return 0;
1270 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1273 crypto_pk_check_fingerprint_syntax(const char *s)
1275 int i;
1276 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1277 if ((i%5) == 4) {
1278 if (!TOR_ISSPACE(s[i])) return 0;
1279 } else {
1280 if (!TOR_ISXDIGIT(s[i])) return 0;
1283 if (s[FINGERPRINT_LEN]) return 0;
1284 return 1;
1287 /* symmetric crypto */
1289 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1290 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1293 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1295 tor_assert(env);
1297 return crypto_rand(env->key, CIPHER_KEY_LEN);
1300 /** Set the symmetric key for the cipher in <b>env</b> to the first
1301 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1303 void
1304 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1306 tor_assert(env);
1307 tor_assert(key);
1309 memcpy(env->key, key, CIPHER_KEY_LEN);
1312 /** Generate an initialization vector for our AES-CTR cipher; store it
1313 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1314 void
1315 crypto_cipher_generate_iv(char *iv_out)
1317 crypto_rand(iv_out, CIPHER_IV_LEN);
1320 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1321 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1322 * <b>iv</b>. */
1324 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1326 tor_assert(env);
1327 tor_assert(iv);
1328 aes_set_iv(env->cipher, iv);
1329 return 0;
1332 /** Return a pointer to the key set for the cipher in <b>env</b>.
1334 const char *
1335 crypto_cipher_get_key(crypto_cipher_env_t *env)
1337 return env->key;
1340 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1341 * success, -1 on failure.
1344 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1346 tor_assert(env);
1348 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1349 return 0;
1352 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1353 * success, -1 on failure.
1356 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1358 tor_assert(env);
1360 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1361 return 0;
1364 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1365 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1366 * On failure, return -1.
1369 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1370 const char *from, size_t fromlen)
1372 tor_assert(env);
1373 tor_assert(env->cipher);
1374 tor_assert(from);
1375 tor_assert(fromlen);
1376 tor_assert(to);
1377 tor_assert(fromlen < SIZE_T_CEILING);
1379 aes_crypt(env->cipher, from, fromlen, to);
1380 return 0;
1383 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1384 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1385 * On failure, return -1.
1388 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1389 const char *from, size_t fromlen)
1391 tor_assert(env);
1392 tor_assert(from);
1393 tor_assert(to);
1394 tor_assert(fromlen < SIZE_T_CEILING);
1396 aes_crypt(env->cipher, from, fromlen, to);
1397 return 0;
1400 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1401 * on success, return 0. On failure, return -1.
1404 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1406 tor_assert(len < SIZE_T_CEILING);
1407 aes_crypt_inplace(env->cipher, buf, len);
1408 return 0;
1411 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1412 * <b>cipher</b> to the buffer in <b>to</b> of length
1413 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1414 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1415 * number of bytes written, on failure, return -1.
1417 * This function adjusts the current position of the counter in <b>cipher</b>
1418 * to immediately after the encrypted data.
1421 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1422 char *to, size_t tolen,
1423 const char *from, size_t fromlen)
1425 tor_assert(cipher);
1426 tor_assert(from);
1427 tor_assert(to);
1428 tor_assert(fromlen < INT_MAX);
1430 if (fromlen < 1)
1431 return -1;
1432 if (tolen < fromlen + CIPHER_IV_LEN)
1433 return -1;
1435 crypto_cipher_generate_iv(to);
1436 if (crypto_cipher_set_iv(cipher, to)<0)
1437 return -1;
1438 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1439 return (int)(fromlen + CIPHER_IV_LEN);
1442 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1443 * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
1444 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1445 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1446 * number of bytes written, on failure, return -1.
1448 * This function adjusts the current position of the counter in <b>cipher</b>
1449 * to immediately after the decrypted data.
1452 crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
1453 char *to, size_t tolen,
1454 const char *from, size_t fromlen)
1456 tor_assert(cipher);
1457 tor_assert(from);
1458 tor_assert(to);
1459 tor_assert(fromlen < INT_MAX);
1461 if (fromlen <= CIPHER_IV_LEN)
1462 return -1;
1463 if (tolen < fromlen - CIPHER_IV_LEN)
1464 return -1;
1466 if (crypto_cipher_set_iv(cipher, from)<0)
1467 return -1;
1468 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1469 return (int)(fromlen - CIPHER_IV_LEN);
1472 /* SHA-1 */
1474 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1475 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1476 * Return 0 on success, -1 on failure.
1479 crypto_digest(char *digest, const char *m, size_t len)
1481 tor_assert(m);
1482 tor_assert(digest);
1483 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1487 crypto_digest256(char *digest, const char *m, size_t len,
1488 digest_algorithm_t algorithm)
1490 tor_assert(m);
1491 tor_assert(digest);
1492 tor_assert(algorithm == DIGEST_SHA256);
1493 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1496 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1497 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1498 * success, -1 on failure. */
1500 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1502 digest_algorithm_t i;
1503 tor_assert(ds_out);
1504 memset(ds_out, 0, sizeof(*ds_out));
1505 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1506 return -1;
1507 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1508 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1509 return -1;
1511 return 0;
1514 /** Return the name of an algorithm, as used in directory documents. */
1515 const char *
1516 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1518 switch (alg) {
1519 case DIGEST_SHA1:
1520 return "sha1";
1521 case DIGEST_SHA256:
1522 return "sha256";
1523 default:
1524 tor_fragile_assert();
1525 return "??unknown_digest??";
1529 /** Given the name of a digest algorithm, return its integer value, or -1 if
1530 * the name is not recognized. */
1532 crypto_digest_algorithm_parse_name(const char *name)
1534 if (!strcmp(name, "sha1"))
1535 return DIGEST_SHA1;
1536 else if (!strcmp(name, "sha256"))
1537 return DIGEST_SHA256;
1538 else
1539 return -1;
1542 /** Intermediate information about the digest of a stream of data. */
1543 struct crypto_digest_env_t {
1544 union {
1545 SHA_CTX sha1;
1546 SHA256_CTX sha2;
1547 } d;
1548 digest_algorithm_t algorithm : 8;
1551 /** Allocate and return a new digest object.
1553 crypto_digest_env_t *
1554 crypto_new_digest_env(void)
1556 crypto_digest_env_t *r;
1557 r = tor_malloc(sizeof(crypto_digest_env_t));
1558 SHA1_Init(&r->d.sha1);
1559 r->algorithm = DIGEST_SHA1;
1560 return r;
1563 crypto_digest_env_t *
1564 crypto_new_digest256_env(digest_algorithm_t algorithm)
1566 crypto_digest_env_t *r;
1567 tor_assert(algorithm == DIGEST_SHA256);
1568 r = tor_malloc(sizeof(crypto_digest_env_t));
1569 SHA256_Init(&r->d.sha2);
1570 r->algorithm = algorithm;
1571 return r;
1574 /** Deallocate a digest object.
1576 void
1577 crypto_free_digest_env(crypto_digest_env_t *digest)
1579 if (!digest)
1580 return;
1581 memset(digest, 0, sizeof(crypto_digest_env_t));
1582 tor_free(digest);
1585 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1587 void
1588 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1589 size_t len)
1591 tor_assert(digest);
1592 tor_assert(data);
1593 /* Using the SHA*_*() calls directly means we don't support doing
1594 * SHA in hardware. But so far the delay of getting the question
1595 * to the hardware, and hearing the answer, is likely higher than
1596 * just doing it ourselves. Hashes are fast.
1598 switch (digest->algorithm) {
1599 case DIGEST_SHA1:
1600 SHA1_Update(&digest->d.sha1, (void*)data, len);
1601 break;
1602 case DIGEST_SHA256:
1603 SHA256_Update(&digest->d.sha2, (void*)data, len);
1604 break;
1605 default:
1606 tor_fragile_assert();
1607 break;
1611 /** Compute the hash of the data that has been passed to the digest
1612 * object; write the first out_len bytes of the result to <b>out</b>.
1613 * <b>out_len</b> must be \<= DIGEST256_LEN.
1615 void
1616 crypto_digest_get_digest(crypto_digest_env_t *digest,
1617 char *out, size_t out_len)
1619 unsigned char r[DIGEST256_LEN];
1620 crypto_digest_env_t tmpenv;
1621 tor_assert(digest);
1622 tor_assert(out);
1623 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1624 memcpy(&tmpenv, digest, sizeof(crypto_digest_env_t));
1625 switch (digest->algorithm) {
1626 case DIGEST_SHA1:
1627 tor_assert(out_len <= DIGEST_LEN);
1628 SHA1_Final(r, &tmpenv.d.sha1);
1629 break;
1630 case DIGEST_SHA256:
1631 tor_assert(out_len <= DIGEST256_LEN);
1632 SHA256_Final(r, &tmpenv.d.sha2);
1633 break;
1634 default:
1635 tor_fragile_assert();
1636 break;
1638 memcpy(out, r, out_len);
1639 memset(r, 0, sizeof(r));
1642 /** Allocate and return a new digest object with the same state as
1643 * <b>digest</b>
1645 crypto_digest_env_t *
1646 crypto_digest_dup(const crypto_digest_env_t *digest)
1648 crypto_digest_env_t *r;
1649 tor_assert(digest);
1650 r = tor_malloc(sizeof(crypto_digest_env_t));
1651 memcpy(r,digest,sizeof(crypto_digest_env_t));
1652 return r;
1655 /** Replace the state of the digest object <b>into</b> with the state
1656 * of the digest object <b>from</b>.
1658 void
1659 crypto_digest_assign(crypto_digest_env_t *into,
1660 const crypto_digest_env_t *from)
1662 tor_assert(into);
1663 tor_assert(from);
1664 memcpy(into,from,sizeof(crypto_digest_env_t));
1667 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1668 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1669 * in <b>hmac_out</b>.
1671 void
1672 crypto_hmac_sha1(char *hmac_out,
1673 const char *key, size_t key_len,
1674 const char *msg, size_t msg_len)
1676 tor_assert(key_len < INT_MAX);
1677 tor_assert(msg_len < INT_MAX);
1678 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1679 (unsigned char*)hmac_out, NULL);
1682 /* DH */
1684 /** Shared P parameter for our DH key exchanged. */
1685 static BIGNUM *dh_param_p = NULL;
1686 /** Shared G parameter for our DH key exchanges. */
1687 static BIGNUM *dh_param_g = NULL;
1689 /** Initialize dh_param_p and dh_param_g if they are not already
1690 * set. */
1691 static void
1692 init_dh_param(void)
1694 BIGNUM *p, *g;
1695 int r;
1696 if (dh_param_p && dh_param_g)
1697 return;
1699 p = BN_new();
1700 g = BN_new();
1701 tor_assert(p);
1702 tor_assert(g);
1704 /* This is from rfc2409, section 6.2. It's a safe prime, and
1705 supposedly it equals:
1706 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1708 r = BN_hex2bn(&p,
1709 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1710 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1711 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1712 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1713 "49286651ECE65381FFFFFFFFFFFFFFFF");
1714 tor_assert(r);
1716 r = BN_set_word(g, 2);
1717 tor_assert(r);
1718 dh_param_p = p;
1719 dh_param_g = g;
1722 #define DH_PRIVATE_KEY_BITS 320
1724 /** Allocate and return a new DH object for a key exchange.
1726 crypto_dh_env_t *
1727 crypto_dh_new(void)
1729 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1731 if (!dh_param_p)
1732 init_dh_param();
1734 if (!(res->dh = DH_new()))
1735 goto err;
1737 if (!(res->dh->p = BN_dup(dh_param_p)))
1738 goto err;
1740 if (!(res->dh->g = BN_dup(dh_param_g)))
1741 goto err;
1743 res->dh->length = DH_PRIVATE_KEY_BITS;
1745 return res;
1746 err:
1747 crypto_log_errors(LOG_WARN, "creating DH object");
1748 if (res->dh) DH_free(res->dh); /* frees p and g too */
1749 tor_free(res);
1750 return NULL;
1753 /** Return the length of the DH key in <b>dh</b>, in bytes.
1756 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1758 tor_assert(dh);
1759 return DH_size(dh->dh);
1762 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1763 * success, -1 on failure.
1766 crypto_dh_generate_public(crypto_dh_env_t *dh)
1768 again:
1769 if (!DH_generate_key(dh->dh)) {
1770 crypto_log_errors(LOG_WARN, "generating DH key");
1771 return -1;
1773 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
1774 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1775 "the-universe chances really do happen. Trying again.");
1776 /* Free and clear the keys, so OpenSSL will actually try again. */
1777 BN_free(dh->dh->pub_key);
1778 BN_free(dh->dh->priv_key);
1779 dh->dh->pub_key = dh->dh->priv_key = NULL;
1780 goto again;
1782 return 0;
1785 /** Generate g^x as necessary, and write the g^x for the key exchange
1786 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1787 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1790 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1792 int bytes;
1793 tor_assert(dh);
1794 if (!dh->dh->pub_key) {
1795 if (crypto_dh_generate_public(dh)<0)
1796 return -1;
1799 tor_assert(dh->dh->pub_key);
1800 bytes = BN_num_bytes(dh->dh->pub_key);
1801 tor_assert(bytes >= 0);
1802 if (pubkey_len < (size_t)bytes) {
1803 log_warn(LD_CRYPTO,
1804 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1805 (int) pubkey_len, bytes);
1806 return -1;
1809 memset(pubkey, 0, pubkey_len);
1810 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1812 return 0;
1815 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1816 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1817 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1819 static int
1820 tor_check_dh_key(int severity, BIGNUM *bn)
1822 BIGNUM *x;
1823 char *s;
1824 tor_assert(bn);
1825 x = BN_new();
1826 tor_assert(x);
1827 if (!dh_param_p)
1828 init_dh_param();
1829 BN_set_word(x, 1);
1830 if (BN_cmp(bn,x)<=0) {
1831 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
1832 goto err;
1834 BN_copy(x,dh_param_p);
1835 BN_sub_word(x, 1);
1836 if (BN_cmp(bn,x)>=0) {
1837 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
1838 goto err;
1840 BN_free(x);
1841 return 0;
1842 err:
1843 BN_free(x);
1844 s = BN_bn2hex(bn);
1845 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1846 OPENSSL_free(s);
1847 return -1;
1850 #undef MIN
1851 #define MIN(a,b) ((a)<(b)?(a):(b))
1852 /** Given a DH key exchange object, and our peer's value of g^y (as a
1853 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1854 * <b>secret_bytes_out</b> bytes of shared key material and write them
1855 * to <b>secret_out</b>. Return the number of bytes generated on success,
1856 * or -1 on failure.
1858 * (We generate key material by computing
1859 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1860 * where || is concatenation.)
1862 ssize_t
1863 crypto_dh_compute_secret(int severity, crypto_dh_env_t *dh,
1864 const char *pubkey, size_t pubkey_len,
1865 char *secret_out, size_t secret_bytes_out)
1867 char *secret_tmp = NULL;
1868 BIGNUM *pubkey_bn = NULL;
1869 size_t secret_len=0;
1870 int result=0;
1871 tor_assert(dh);
1872 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1873 tor_assert(pubkey_len < INT_MAX);
1875 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1876 (int)pubkey_len, NULL)))
1877 goto error;
1878 if (tor_check_dh_key(severity, pubkey_bn)<0) {
1879 /* Check for invalid public keys. */
1880 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
1881 goto error;
1883 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1884 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1885 if (result < 0) {
1886 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1887 goto error;
1889 secret_len = result;
1890 if (crypto_expand_key_material(secret_tmp, secret_len,
1891 secret_out, secret_bytes_out)<0)
1892 goto error;
1893 secret_len = secret_bytes_out;
1895 goto done;
1896 error:
1897 result = -1;
1898 done:
1899 crypto_log_errors(LOG_WARN, "completing DH handshake");
1900 if (pubkey_bn)
1901 BN_free(pubkey_bn);
1902 tor_free(secret_tmp);
1903 if (result < 0)
1904 return result;
1905 else
1906 return secret_len;
1909 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1910 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1911 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1912 * H(K | [00]) | H(K | [01]) | ....
1914 * Return 0 on success, -1 on failure.
1917 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1918 char *key_out, size_t key_out_len)
1920 int i;
1921 char *cp, *tmp = tor_malloc(key_in_len+1);
1922 char digest[DIGEST_LEN];
1924 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1925 tor_assert(key_out_len <= DIGEST_LEN*256);
1927 memcpy(tmp, key_in, key_in_len);
1928 for (cp = key_out, i=0; cp < key_out+key_out_len;
1929 ++i, cp += DIGEST_LEN) {
1930 tmp[key_in_len] = i;
1931 if (crypto_digest(digest, tmp, key_in_len+1))
1932 goto err;
1933 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1935 memset(tmp, 0, key_in_len+1);
1936 tor_free(tmp);
1937 memset(digest, 0, sizeof(digest));
1938 return 0;
1940 err:
1941 memset(tmp, 0, key_in_len+1);
1942 tor_free(tmp);
1943 memset(digest, 0, sizeof(digest));
1944 return -1;
1947 /** Free a DH key exchange object.
1949 void
1950 crypto_dh_free(crypto_dh_env_t *dh)
1952 if (!dh)
1953 return;
1954 tor_assert(dh->dh);
1955 DH_free(dh->dh);
1956 tor_free(dh);
1959 /* random numbers */
1961 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1962 * work for us too. */
1963 #define ADD_ENTROPY 32
1965 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1966 "release".) */
1967 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1969 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1970 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1971 * that fd without checking whether it fit in the fd_set. Thus, if the
1972 * system has not just been started up, it is unsafe to call */
1973 #define RAND_POLL_IS_SAFE \
1974 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1975 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1976 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1978 static void
1979 seed_weak_rng(void)
1981 unsigned seed;
1982 crypto_rand((void*)&seed, sizeof(seed));
1983 tor_init_weak_random(seed);
1986 /** Seed OpenSSL's random number generator with bytes from the operating
1987 * system. <b>startup</b> should be true iff we have just started Tor and
1988 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1991 crypto_seed_rng(int startup)
1993 int rand_poll_status = 0;
1995 /* local variables */
1996 #ifdef MS_WINDOWS
1997 unsigned char buf[ADD_ENTROPY];
1998 static int provider_set = 0;
1999 static HCRYPTPROV provider;
2000 #else
2001 char buf[ADD_ENTROPY];
2002 static const char *filenames[] = {
2003 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2005 int fd, i;
2006 size_t n;
2007 #endif
2009 #if HAVE_RAND_POLL
2010 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
2011 * entropy than we do. We'll try calling that, *and* calling our own entropy
2012 * functions. If one succeeds, we'll accept the RNG as seeded. */
2013 if (startup || RAND_POLL_IS_SAFE) {
2014 rand_poll_status = RAND_poll();
2015 if (rand_poll_status == 0)
2016 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2018 #endif
2020 #ifdef MS_WINDOWS
2021 if (!provider_set) {
2022 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2023 CRYPT_VERIFYCONTEXT)) {
2024 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
2025 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2026 return rand_poll_status ? 0 : -1;
2029 provider_set = 1;
2031 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
2032 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2033 return rand_poll_status ? 0 : -1;
2035 RAND_seed(buf, sizeof(buf));
2036 memset(buf, 0, sizeof(buf));
2037 seed_weak_rng();
2038 return 0;
2039 #else
2040 for (i = 0; filenames[i]; ++i) {
2041 fd = open(filenames[i], O_RDONLY, 0);
2042 if (fd<0) continue;
2043 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
2044 n = read_all(fd, buf, sizeof(buf), 0);
2045 close(fd);
2046 if (n != sizeof(buf)) {
2047 log_warn(LD_CRYPTO,
2048 "Error reading from entropy source (read only %lu bytes).",
2049 (unsigned long)n);
2050 return -1;
2052 RAND_seed(buf, (int)sizeof(buf));
2053 memset(buf, 0, sizeof(buf));
2054 seed_weak_rng();
2055 return 0;
2058 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
2059 return rand_poll_status ? 0 : -1;
2060 #endif
2063 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2064 * success, -1 on failure.
2067 crypto_rand(char *to, size_t n)
2069 int r;
2070 tor_assert(n < INT_MAX);
2071 tor_assert(to);
2072 r = RAND_bytes((unsigned char*)to, (int)n);
2073 if (r == 0)
2074 crypto_log_errors(LOG_WARN, "generating random data");
2075 return (r == 1) ? 0 : -1;
2078 /** Return a pseudorandom integer, chosen uniformly from the values
2079 * between 0 and <b>max</b>-1. */
2081 crypto_rand_int(unsigned int max)
2083 unsigned int val;
2084 unsigned int cutoff;
2085 tor_assert(max < UINT_MAX);
2086 tor_assert(max > 0); /* don't div by 0 */
2088 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2089 * distribution with clipping at the upper end of unsigned int's
2090 * range.
2092 cutoff = UINT_MAX - (UINT_MAX%max);
2093 while (1) {
2094 crypto_rand((char*)&val, sizeof(val));
2095 if (val < cutoff)
2096 return val % max;
2100 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2101 * between 0 and <b>max</b>-1. */
2102 uint64_t
2103 crypto_rand_uint64(uint64_t max)
2105 uint64_t val;
2106 uint64_t cutoff;
2107 tor_assert(max < UINT64_MAX);
2108 tor_assert(max > 0); /* don't div by 0 */
2110 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2111 * distribution with clipping at the upper end of unsigned int's
2112 * range.
2114 cutoff = UINT64_MAX - (UINT64_MAX%max);
2115 while (1) {
2116 crypto_rand((char*)&val, sizeof(val));
2117 if (val < cutoff)
2118 return val % max;
2122 /** Return a pseudorandom double d, chosen uniformly from the range
2123 * 0.0 <= d < 1.0.
2125 double
2126 crypto_rand_double(void)
2128 /* We just use an unsigned int here; we don't really care about getting
2129 * more than 32 bits of resolution */
2130 unsigned int uint;
2131 crypto_rand((char*)&uint, sizeof(uint));
2132 #if SIZEOF_INT == 4
2133 #define UINT_MAX_AS_DOUBLE 4294967296.0
2134 #elif SIZEOF_INT == 8
2135 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2136 #else
2137 #error SIZEOF_INT is neither 4 nor 8
2138 #endif
2139 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2142 /** Generate and return a new random hostname starting with <b>prefix</b>,
2143 * ending with <b>suffix</b>, and containing no less than
2144 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2145 * characters between. */
2146 char *
2147 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2148 const char *suffix)
2150 char *result, *rand_bytes;
2151 int randlen, rand_bytes_len;
2152 size_t resultlen, prefixlen;
2154 tor_assert(max_rand_len >= min_rand_len);
2155 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2156 prefixlen = strlen(prefix);
2157 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2159 rand_bytes_len = ((randlen*5)+7)/8;
2160 if (rand_bytes_len % 5)
2161 rand_bytes_len += 5 - (rand_bytes_len%5);
2162 rand_bytes = tor_malloc(rand_bytes_len);
2163 crypto_rand(rand_bytes, rand_bytes_len);
2165 result = tor_malloc(resultlen);
2166 memcpy(result, prefix, prefixlen);
2167 base32_encode(result+prefixlen, resultlen-prefixlen,
2168 rand_bytes, rand_bytes_len);
2169 tor_free(rand_bytes);
2170 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2172 return result;
2175 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2176 * is empty. */
2177 void *
2178 smartlist_choose(const smartlist_t *sl)
2180 int len = smartlist_len(sl);
2181 if (len)
2182 return smartlist_get(sl,crypto_rand_int(len));
2183 return NULL; /* no elements to choose from */
2186 /** Scramble the elements of <b>sl</b> into a random order. */
2187 void
2188 smartlist_shuffle(smartlist_t *sl)
2190 int i;
2191 /* From the end of the list to the front, choose at random from the
2192 positions we haven't looked at yet, and swap that position into the
2193 current position. Remember to give "no swap" the same probability as
2194 any other swap. */
2195 for (i = smartlist_len(sl)-1; i > 0; --i) {
2196 int j = crypto_rand_int(i+1);
2197 smartlist_swap(sl, i, j);
2201 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2202 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2203 * bytes. Return the number of bytes written on success; -1 if
2204 * destlen is too short, or other failure.
2207 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2209 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2210 * it ever shows up in the profile. */
2211 EVP_ENCODE_CTX ctx;
2212 int len, ret;
2213 tor_assert(srclen < INT_MAX);
2215 /* 48 bytes of input -> 64 bytes of output plus newline.
2216 Plus one more byte, in case I'm wrong.
2218 if (destlen < ((srclen/48)+1)*66)
2219 return -1;
2220 if (destlen > SIZE_T_CEILING)
2221 return -1;
2223 EVP_EncodeInit(&ctx);
2224 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2225 (unsigned char*)src, (int)srclen);
2226 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2227 ret += len;
2228 return ret;
2231 #define X 255
2232 #define SP 64
2233 #define PAD 65
2234 /** Internal table mapping byte values to what they represent in base64.
2235 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2236 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2237 * end-of-string. */
2238 static const uint8_t base64_decode_table[256] = {
2239 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2240 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2241 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2242 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2243 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2244 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2245 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2246 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2247 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2248 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2249 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2250 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2251 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2252 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2253 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2254 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2257 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2258 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2259 * bytes. Return the number of bytes written on success; -1 if
2260 * destlen is too short, or other failure.
2262 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2263 * spaces or padding.
2265 * NOTE 2: This implementation does not check for the correct number of
2266 * padding "=" characters at the end of the string, and does not check
2267 * for internal padding characters.
2270 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2272 #ifdef USE_OPENSSL_BASE64
2273 EVP_ENCODE_CTX ctx;
2274 int len, ret;
2275 /* 64 bytes of input -> *up to* 48 bytes of output.
2276 Plus one more byte, in case I'm wrong.
2278 if (destlen < ((srclen/64)+1)*49)
2279 return -1;
2280 if (destlen > SIZE_T_CEILING)
2281 return -1;
2283 EVP_DecodeInit(&ctx);
2284 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2285 (unsigned char*)src, srclen);
2286 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2287 ret += len;
2288 return ret;
2289 #else
2290 const char *eos = src+srclen;
2291 uint32_t n=0;
2292 int n_idx=0;
2293 char *dest_orig = dest;
2295 /* Max number of bits == srclen*6.
2296 * Number of bytes required to hold all bits == (srclen*6)/8.
2297 * Yes, we want to round down: anything that hangs over the end of a
2298 * byte is padding. */
2299 if (destlen < (srclen*3)/4)
2300 return -1;
2301 if (destlen > SIZE_T_CEILING)
2302 return -1;
2304 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2305 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2306 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2308 for ( ; src < eos; ++src) {
2309 unsigned char c = (unsigned char) *src;
2310 uint8_t v = base64_decode_table[c];
2311 switch (v) {
2312 case X:
2313 /* This character isn't allowed in base64. */
2314 return -1;
2315 case SP:
2316 /* This character is whitespace, and has no effect. */
2317 continue;
2318 case PAD:
2319 /* We've hit an = character: the data is over. */
2320 goto end_of_loop;
2321 default:
2322 /* We have an actual 6-bit value. Append it to the bits in n. */
2323 n = (n<<6) | v;
2324 if ((++n_idx) == 4) {
2325 /* We've accumulated 24 bits in n. Flush them. */
2326 *dest++ = (n>>16);
2327 *dest++ = (n>>8) & 0xff;
2328 *dest++ = (n) & 0xff;
2329 n_idx = 0;
2330 n = 0;
2334 end_of_loop:
2335 /* If we have leftover bits, we need to cope. */
2336 switch (n_idx) {
2337 case 0:
2338 default:
2339 /* No leftover bits. We win. */
2340 break;
2341 case 1:
2342 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2343 return -1;
2344 case 2:
2345 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2346 *dest++ = n >> 4;
2347 break;
2348 case 3:
2349 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2350 *dest++ = n >> 10;
2351 *dest++ = n >> 2;
2354 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2355 tor_assert((dest-dest_orig) <= INT_MAX);
2357 return (int)(dest-dest_orig);
2358 #endif
2360 #undef X
2361 #undef SP
2362 #undef PAD
2364 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2365 * and newline characters, and store the nul-terminated result in the first
2366 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2368 digest_to_base64(char *d64, const char *digest)
2370 char buf[256];
2371 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2372 buf[BASE64_DIGEST_LEN] = '\0';
2373 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2374 return 0;
2377 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2378 * trailing newline or = characters), decode it and store the result in the
2379 * first DIGEST_LEN bytes at <b>digest</b>. */
2381 digest_from_base64(char *digest, const char *d64)
2383 #ifdef USE_OPENSSL_BASE64
2384 char buf_in[BASE64_DIGEST_LEN+3];
2385 char buf[256];
2386 if (strlen(d64) != BASE64_DIGEST_LEN)
2387 return -1;
2388 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2389 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2390 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2391 return -1;
2392 memcpy(digest, buf, DIGEST_LEN);
2393 return 0;
2394 #else
2395 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2396 return 0;
2397 else
2398 return -1;
2399 #endif
2402 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2403 * trailing = and newline characters, and store the nul-terminated result in
2404 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2406 digest256_to_base64(char *d64, const char *digest)
2408 char buf[256];
2409 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2410 buf[BASE64_DIGEST256_LEN] = '\0';
2411 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2412 return 0;
2415 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2416 * trailing newline or = characters), decode it and store the result in the
2417 * first DIGEST256_LEN bytes at <b>digest</b>. */
2419 digest256_from_base64(char *digest, const char *d64)
2421 #ifdef USE_OPENSSL_BASE64
2422 char buf_in[BASE64_DIGEST256_LEN+3];
2423 char buf[256];
2424 if (strlen(d64) != BASE64_DIGEST256_LEN)
2425 return -1;
2426 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2427 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2428 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2429 return -1;
2430 memcpy(digest, buf, DIGEST256_LEN);
2431 return 0;
2432 #else
2433 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2434 return 0;
2435 else
2436 return -1;
2437 #endif
2440 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2441 * that srclen*8 is a multiple of 5.
2443 void
2444 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2446 unsigned int i, v, u;
2447 size_t nbits = srclen * 8, bit;
2449 tor_assert(srclen < SIZE_T_CEILING/8);
2450 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2451 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2452 tor_assert(destlen < SIZE_T_CEILING);
2454 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2455 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2456 v = ((uint8_t)src[bit/8]) << 8;
2457 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2458 /* set u to the 5-bit value at the bit'th bit of src. */
2459 u = (v >> (11-(bit%8))) & 0x1F;
2460 dest[i] = BASE32_CHARS[u];
2462 dest[i] = '\0';
2465 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2466 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2469 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2471 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2472 * it ever shows up in the profile. */
2473 unsigned int i;
2474 size_t nbits, j, bit;
2475 char *tmp;
2476 nbits = srclen * 5;
2478 tor_assert(srclen < SIZE_T_CEILING / 5);
2479 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2480 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2481 tor_assert(destlen < SIZE_T_CEILING);
2483 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2484 tmp = tor_malloc_zero(srclen);
2485 for (j = 0; j < srclen; ++j) {
2486 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2487 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2488 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2489 else {
2490 log_warn(LD_BUG, "illegal character in base32 encoded string");
2491 tor_free(tmp);
2492 return -1;
2496 /* Assemble result byte-wise by applying five possible cases. */
2497 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2498 switch (bit % 40) {
2499 case 0:
2500 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2501 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2502 break;
2503 case 8:
2504 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2505 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2506 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2507 break;
2508 case 16:
2509 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2510 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2511 break;
2512 case 24:
2513 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2514 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2515 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2516 break;
2517 case 32:
2518 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2519 ((uint8_t)tmp[(bit/5)+1]);
2520 break;
2524 memset(tmp, 0, srclen);
2525 tor_free(tmp);
2526 tmp = NULL;
2527 return 0;
2530 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2531 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2532 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2533 * are a salt; the 9th byte describes how much iteration to do.
2534 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2536 void
2537 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2538 size_t secret_len, const char *s2k_specifier)
2540 crypto_digest_env_t *d;
2541 uint8_t c;
2542 size_t count, tmplen;
2543 char *tmp;
2544 tor_assert(key_out_len < SIZE_T_CEILING);
2546 #define EXPBIAS 6
2547 c = s2k_specifier[8];
2548 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2549 #undef EXPBIAS
2551 tor_assert(key_out_len <= DIGEST_LEN);
2553 d = crypto_new_digest_env();
2554 tmplen = 8+secret_len;
2555 tmp = tor_malloc(tmplen);
2556 memcpy(tmp,s2k_specifier,8);
2557 memcpy(tmp+8,secret,secret_len);
2558 secret_len += 8;
2559 while (count) {
2560 if (count >= secret_len) {
2561 crypto_digest_add_bytes(d, tmp, secret_len);
2562 count -= secret_len;
2563 } else {
2564 crypto_digest_add_bytes(d, tmp, count);
2565 count = 0;
2568 crypto_digest_get_digest(d, key_out, key_out_len);
2569 memset(tmp, 0, tmplen);
2570 tor_free(tmp);
2571 crypto_free_digest_env(d);
2574 #ifdef TOR_IS_MULTITHREADED
2575 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2576 static void
2577 _openssl_locking_cb(int mode, int n, const char *file, int line)
2579 (void)file;
2580 (void)line;
2581 if (!_openssl_mutexes)
2582 /* This is not a really good fix for the
2583 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2584 * it can't hurt. */
2585 return;
2586 if (mode & CRYPTO_LOCK)
2587 tor_mutex_acquire(_openssl_mutexes[n]);
2588 else
2589 tor_mutex_release(_openssl_mutexes[n]);
2592 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2593 * as a lock. */
2594 struct CRYPTO_dynlock_value {
2595 tor_mutex_t *lock;
2598 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2599 * documentation in OpenSSL's docs for more info. */
2600 static struct CRYPTO_dynlock_value *
2601 _openssl_dynlock_create_cb(const char *file, int line)
2603 struct CRYPTO_dynlock_value *v;
2604 (void)file;
2605 (void)line;
2606 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2607 v->lock = tor_mutex_new();
2608 return v;
2611 /** OpenSSL callback function to acquire or release a lock: see
2612 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2613 static void
2614 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2615 const char *file, int line)
2617 (void)file;
2618 (void)line;
2619 if (mode & CRYPTO_LOCK)
2620 tor_mutex_acquire(v->lock);
2621 else
2622 tor_mutex_release(v->lock);
2625 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2626 * documentation in OpenSSL's docs for more info. */
2627 static void
2628 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2629 const char *file, int line)
2631 (void)file;
2632 (void)line;
2633 tor_mutex_free(v->lock);
2634 tor_free(v);
2637 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2638 * multithreaded. */
2639 static int
2640 setup_openssl_threading(void)
2642 int i;
2643 int n = CRYPTO_num_locks();
2644 _n_openssl_mutexes = n;
2645 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2646 for (i=0; i < n; ++i)
2647 _openssl_mutexes[i] = tor_mutex_new();
2648 CRYPTO_set_locking_callback(_openssl_locking_cb);
2649 CRYPTO_set_id_callback(tor_get_thread_id);
2650 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2651 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2652 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2653 return 0;
2655 #else
2656 static int
2657 setup_openssl_threading(void)
2659 return 0;
2661 #endif