Fix up size and sign issues in base32 code
[tor/rransom.git] / src / common / crypto.c
blob71cf6d43d82fa3b7164aa156d8460f30ecc88ded
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.
812 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
813 const char *from, size_t fromlen, int padding)
815 int r;
816 tor_assert(env);
817 tor_assert(from);
818 tor_assert(to);
819 tor_assert(fromlen<INT_MAX);
821 r = RSA_public_encrypt((int)fromlen,
822 (unsigned char*)from, (unsigned char*)to,
823 env->key, crypto_get_rsa_padding(padding));
824 if (r<0) {
825 crypto_log_errors(LOG_WARN, "performing RSA encryption");
826 return -1;
828 return r;
831 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
832 * in <b>env</b>, using the padding method <b>padding</b>. On success,
833 * write the result to <b>to</b>, and return the number of bytes
834 * written. On failure, return -1.
837 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
838 const char *from, size_t fromlen,
839 int padding, int warnOnFailure)
841 int r;
842 tor_assert(env);
843 tor_assert(from);
844 tor_assert(to);
845 tor_assert(env->key);
846 tor_assert(fromlen<INT_MAX);
847 if (!env->key->p)
848 /* Not a private key */
849 return -1;
851 r = RSA_private_decrypt((int)fromlen,
852 (unsigned char*)from, (unsigned char*)to,
853 env->key, crypto_get_rsa_padding(padding));
855 if (r<0) {
856 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
857 "performing RSA decryption");
858 return -1;
860 return r;
863 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
864 * public key in <b>env</b>, using PKCS1 padding. On success, write the
865 * signed data to <b>to</b>, and return the number of bytes written.
866 * On failure, return -1.
869 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
870 const char *from, size_t fromlen)
872 int r;
873 tor_assert(env);
874 tor_assert(from);
875 tor_assert(to);
876 tor_assert(fromlen < INT_MAX);
877 r = RSA_public_decrypt((int)fromlen,
878 (unsigned char*)from, (unsigned char*)to,
879 env->key, RSA_PKCS1_PADDING);
881 if (r<0) {
882 crypto_log_errors(LOG_WARN, "checking RSA signature");
883 return -1;
885 return r;
888 /** Check a siglen-byte long signature at <b>sig</b> against
889 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
890 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
891 * SHA1(data). Else return -1.
894 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
895 size_t datalen, const char *sig, size_t siglen)
897 char digest[DIGEST_LEN];
898 char *buf;
899 int r;
901 tor_assert(env);
902 tor_assert(data);
903 tor_assert(sig);
904 tor_assert(datalen < SIZE_T_CEILING);
905 tor_assert(siglen < SIZE_T_CEILING);
907 if (crypto_digest(digest,data,datalen)<0) {
908 log_warn(LD_BUG, "couldn't compute digest");
909 return -1;
911 buf = tor_malloc(crypto_pk_keysize(env)+1);
912 r = crypto_pk_public_checksig(env,buf,sig,siglen);
913 if (r != DIGEST_LEN) {
914 log_warn(LD_CRYPTO, "Invalid signature");
915 tor_free(buf);
916 return -1;
918 if (memcmp(buf, digest, DIGEST_LEN)) {
919 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
920 tor_free(buf);
921 return -1;
923 tor_free(buf);
925 return 0;
928 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
929 * <b>env</b>, using PKCS1 padding. On success, write the signature to
930 * <b>to</b>, and return the number of bytes written. On failure, return
931 * -1.
934 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
935 const char *from, size_t fromlen)
937 int r;
938 tor_assert(env);
939 tor_assert(from);
940 tor_assert(to);
941 tor_assert(fromlen < INT_MAX);
942 if (!env->key->p)
943 /* Not a private key */
944 return -1;
946 r = RSA_private_encrypt((int)fromlen,
947 (unsigned char*)from, (unsigned char*)to,
948 env->key, RSA_PKCS1_PADDING);
949 if (r<0) {
950 crypto_log_errors(LOG_WARN, "generating RSA signature");
951 return -1;
953 return r;
956 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
957 * <b>from</b>; sign the data with the private key in <b>env</b>, and
958 * store it in <b>to</b>. Return the number of bytes written on
959 * success, and -1 on failure.
962 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
963 const char *from, size_t fromlen)
965 int r;
966 char digest[DIGEST_LEN];
967 if (crypto_digest(digest,from,fromlen)<0)
968 return -1;
969 r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
970 memset(digest, 0, sizeof(digest));
971 return r;
974 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
975 * bytes of data from <b>from</b>, with padding type 'padding',
976 * storing the results on <b>to</b>.
978 * If no padding is used, the public key must be at least as large as
979 * <b>from</b>.
981 * Returns the number of bytes written on success, -1 on failure.
983 * The encrypted data consists of:
984 * - The source data, padded and encrypted with the public key, if the
985 * padded source data is no longer than the public key, and <b>force</b>
986 * is false, OR
987 * - The beginning of the source data prefixed with a 16-byte symmetric key,
988 * padded and encrypted with the public key; followed by the rest of
989 * the source data encrypted in AES-CTR mode with the symmetric key.
992 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
993 char *to,
994 const char *from,
995 size_t fromlen,
996 int padding, int force)
998 int overhead, outlen, r;
999 size_t pkeylen, symlen;
1000 crypto_cipher_env_t *cipher = NULL;
1001 char *buf = NULL;
1003 tor_assert(env);
1004 tor_assert(from);
1005 tor_assert(to);
1006 tor_assert(fromlen < SIZE_T_CEILING);
1008 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1009 pkeylen = crypto_pk_keysize(env);
1011 if (padding == PK_NO_PADDING && fromlen < pkeylen)
1012 return -1;
1014 if (!force && fromlen+overhead <= pkeylen) {
1015 /* It all fits in a single encrypt. */
1016 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
1018 cipher = crypto_new_cipher_env();
1019 if (!cipher) return -1;
1020 if (crypto_cipher_generate_key(cipher)<0)
1021 goto err;
1022 /* You can't just run around RSA-encrypting any bitstream: if it's
1023 * greater than the RSA key, then OpenSSL will happily encrypt, and
1024 * later decrypt to the wrong value. So we set the first bit of
1025 * 'cipher->key' to 0 if we aren't padding. This means that our
1026 * symmetric key is really only 127 bits.
1028 if (padding == PK_NO_PADDING)
1029 cipher->key[0] &= 0x7f;
1030 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
1031 goto err;
1032 buf = tor_malloc(pkeylen+1);
1033 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1034 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1036 /* Length of symmetrically encrypted data. */
1037 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1039 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
1040 if (outlen!=(int)pkeylen) {
1041 goto err;
1043 r = crypto_cipher_encrypt(cipher, to+outlen,
1044 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1046 if (r<0) goto err;
1047 memset(buf, 0, pkeylen);
1048 tor_free(buf);
1049 crypto_free_cipher_env(cipher);
1050 tor_assert(outlen+symlen < INT_MAX);
1051 return (int)(outlen + symlen);
1052 err:
1053 if (buf) {
1054 memset(buf, 0, pkeylen);
1055 tor_free(buf);
1057 if (cipher) crypto_free_cipher_env(cipher);
1058 return -1;
1061 /** Invert crypto_pk_public_hybrid_encrypt. */
1063 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
1064 char *to,
1065 const char *from,
1066 size_t fromlen,
1067 int padding, int warnOnFailure)
1069 int outlen, r;
1070 size_t pkeylen;
1071 crypto_cipher_env_t *cipher = NULL;
1072 char *buf = NULL;
1074 tor_assert(fromlen < SIZE_T_CEILING);
1075 pkeylen = crypto_pk_keysize(env);
1077 if (fromlen <= pkeylen) {
1078 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
1079 warnOnFailure);
1081 buf = tor_malloc(pkeylen+1);
1082 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
1083 warnOnFailure);
1084 if (outlen<0) {
1085 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1086 "Error decrypting public-key data");
1087 goto err;
1089 if (outlen < CIPHER_KEY_LEN) {
1090 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1091 "No room for a symmetric key");
1092 goto err;
1094 cipher = crypto_create_init_cipher(buf, 0);
1095 if (!cipher) {
1096 goto err;
1098 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1099 outlen -= CIPHER_KEY_LEN;
1100 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1101 if (r<0)
1102 goto err;
1103 memset(buf,0,pkeylen);
1104 tor_free(buf);
1105 crypto_free_cipher_env(cipher);
1106 tor_assert(outlen + fromlen < INT_MAX);
1107 return (int)(outlen + (fromlen-pkeylen));
1108 err:
1109 memset(buf,0,pkeylen);
1110 tor_free(buf);
1111 if (cipher) crypto_free_cipher_env(cipher);
1112 return -1;
1115 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1116 * Return -1 on error, or the number of characters used on success.
1119 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
1121 int len;
1122 unsigned char *buf, *cp;
1123 len = i2d_RSAPublicKey(pk->key, NULL);
1124 if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
1125 return -1;
1126 cp = buf = tor_malloc(len+1);
1127 len = i2d_RSAPublicKey(pk->key, &cp);
1128 if (len < 0) {
1129 crypto_log_errors(LOG_WARN,"encoding public key");
1130 tor_free(buf);
1131 return -1;
1133 /* We don't encode directly into 'dest', because that would be illegal
1134 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1136 memcpy(dest,buf,len);
1137 tor_free(buf);
1138 return len;
1141 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1142 * success and NULL on failure.
1144 crypto_pk_env_t *
1145 crypto_pk_asn1_decode(const char *str, size_t len)
1147 RSA *rsa;
1148 unsigned char *buf;
1149 /* This ifdef suppresses a type warning. Take out the first case once
1150 * everybody is using OpenSSL 0.9.7 or later.
1152 const unsigned char *cp;
1153 cp = buf = tor_malloc(len);
1154 memcpy(buf,str,len);
1155 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1156 tor_free(buf);
1157 if (!rsa) {
1158 crypto_log_errors(LOG_WARN,"decoding public key");
1159 return NULL;
1161 return _crypto_new_pk_env_rsa(rsa);
1164 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1165 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1166 * Return 0 on success, -1 on failure.
1169 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1171 unsigned char *buf, *bufp;
1172 int len;
1174 len = i2d_RSAPublicKey(pk->key, NULL);
1175 if (len < 0)
1176 return -1;
1177 buf = bufp = tor_malloc(len+1);
1178 len = i2d_RSAPublicKey(pk->key, &bufp);
1179 if (len < 0) {
1180 crypto_log_errors(LOG_WARN,"encoding public key");
1181 tor_free(buf);
1182 return -1;
1184 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1185 tor_free(buf);
1186 return -1;
1188 tor_free(buf);
1189 return 0;
1192 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1193 * every four spaces. */
1194 /* static */ void
1195 add_spaces_to_fp(char *out, size_t outlen, const char *in)
1197 int n = 0;
1198 char *end = out+outlen;
1199 tor_assert(outlen < SIZE_T_CEILING);
1201 while (*in && out<end) {
1202 *out++ = *in++;
1203 if (++n == 4 && *in && out<end) {
1204 n = 0;
1205 *out++ = ' ';
1208 tor_assert(out<end);
1209 *out = '\0';
1212 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1213 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1214 * space). Return 0 on success, -1 on failure.
1216 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1217 * of the public key, converted to hexadecimal, in upper case, with a
1218 * space after every four digits.
1220 * If <b>add_space</b> is false, omit the spaces.
1223 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1225 char digest[DIGEST_LEN];
1226 char hexdigest[HEX_DIGEST_LEN+1];
1227 if (crypto_pk_get_digest(pk, digest)) {
1228 return -1;
1230 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1231 if (add_space) {
1232 add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1233 } else {
1234 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1236 return 0;
1239 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1242 crypto_pk_check_fingerprint_syntax(const char *s)
1244 int i;
1245 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1246 if ((i%5) == 4) {
1247 if (!TOR_ISSPACE(s[i])) return 0;
1248 } else {
1249 if (!TOR_ISXDIGIT(s[i])) return 0;
1252 if (s[FINGERPRINT_LEN]) return 0;
1253 return 1;
1256 /* symmetric crypto */
1258 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1259 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1262 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1264 tor_assert(env);
1266 return crypto_rand(env->key, CIPHER_KEY_LEN);
1269 /** Set the symmetric key for the cipher in <b>env</b> to the first
1270 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1272 void
1273 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1275 tor_assert(env);
1276 tor_assert(key);
1278 memcpy(env->key, key, CIPHER_KEY_LEN);
1281 /** Generate an initialization vector for our AES-CTR cipher; store it
1282 * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
1283 void
1284 crypto_cipher_generate_iv(char *iv_out)
1286 crypto_rand(iv_out, CIPHER_IV_LEN);
1289 /** Adjust the counter of <b>env</b> to point to the first byte of the block
1290 * corresponding to the encryption of the CIPHER_IV_LEN bytes at
1291 * <b>iv</b>. */
1293 crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
1295 tor_assert(env);
1296 tor_assert(iv);
1297 aes_set_iv(env->cipher, iv);
1298 return 0;
1301 /** Return a pointer to the key set for the cipher in <b>env</b>.
1303 const char *
1304 crypto_cipher_get_key(crypto_cipher_env_t *env)
1306 return env->key;
1309 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1310 * success, -1 on failure.
1313 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1315 tor_assert(env);
1317 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1318 return 0;
1321 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1322 * success, -1 on failure.
1325 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1327 tor_assert(env);
1329 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1330 return 0;
1333 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1334 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1335 * On failure, return -1.
1338 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1339 const char *from, size_t fromlen)
1341 tor_assert(env);
1342 tor_assert(env->cipher);
1343 tor_assert(from);
1344 tor_assert(fromlen);
1345 tor_assert(to);
1346 tor_assert(fromlen < SIZE_T_CEILING);
1348 aes_crypt(env->cipher, from, fromlen, to);
1349 return 0;
1352 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1353 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1354 * On failure, return -1.
1357 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1358 const char *from, size_t fromlen)
1360 tor_assert(env);
1361 tor_assert(from);
1362 tor_assert(to);
1363 tor_assert(fromlen < SIZE_T_CEILING);
1365 aes_crypt(env->cipher, from, fromlen, to);
1366 return 0;
1369 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1370 * on success, return 0. On failure, return -1.
1373 crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
1375 tor_assert(len < SIZE_T_CEILING);
1376 aes_crypt_inplace(env->cipher, buf, len);
1377 return 0;
1380 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1381 * <b>cipher</b> to the buffer in <b>to</b> of length
1382 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1383 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1384 * number of bytes written, on failure, return -1.
1386 * This function adjusts the current position of the counter in <b>cipher</b>
1387 * to immediately after the encrypted data.
1390 crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
1391 char *to, size_t tolen,
1392 const char *from, size_t fromlen)
1394 tor_assert(cipher);
1395 tor_assert(from);
1396 tor_assert(to);
1397 tor_assert(fromlen < INT_MAX);
1399 if (fromlen < 1)
1400 return -1;
1401 if (tolen < fromlen + CIPHER_IV_LEN)
1402 return -1;
1404 crypto_cipher_generate_iv(to);
1405 if (crypto_cipher_set_iv(cipher, to)<0)
1406 return -1;
1407 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1408 return (int)(fromlen + CIPHER_IV_LEN);
1411 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1412 * with the key in <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> minus
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 decrypted data.
1421 crypto_cipher_decrypt_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 <= CIPHER_IV_LEN)
1431 return -1;
1432 if (tolen < fromlen - CIPHER_IV_LEN)
1433 return -1;
1435 if (crypto_cipher_set_iv(cipher, from)<0)
1436 return -1;
1437 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1438 return (int)(fromlen - CIPHER_IV_LEN);
1441 /* SHA-1 */
1443 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1444 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1445 * Return 0 on success, -1 on failure.
1448 crypto_digest(char *digest, const char *m, size_t len)
1450 tor_assert(m);
1451 tor_assert(digest);
1452 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1456 crypto_digest256(char *digest, const char *m, size_t len,
1457 digest_algorithm_t algorithm)
1459 tor_assert(m);
1460 tor_assert(digest);
1461 tor_assert(algorithm == DIGEST_SHA256);
1462 return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1465 /** Set the digests_t in <b>ds_out</b> to contain every digest on the
1466 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1467 * success, -1 on failure. */
1469 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
1471 digest_algorithm_t i;
1472 tor_assert(ds_out);
1473 memset(ds_out, 0, sizeof(*ds_out));
1474 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1475 return -1;
1476 for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
1477 if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
1478 return -1;
1480 return 0;
1483 /** Return the name of an algorithm, as used in directory documents. */
1484 const char *
1485 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1487 switch (alg) {
1488 case DIGEST_SHA1:
1489 return "sha1";
1490 case DIGEST_SHA256:
1491 return "sha256";
1492 default:
1493 tor_fragile_assert();
1494 return "??unknown_digest??";
1498 /** Given the name of a digest algorithm, return its integer value, or -1 if
1499 * the name is not recognized. */
1501 crypto_digest_algorithm_parse_name(const char *name)
1503 if (!strcmp(name, "sha1"))
1504 return DIGEST_SHA1;
1505 else if (!strcmp(name, "sha256"))
1506 return DIGEST_SHA256;
1507 else
1508 return -1;
1511 /** Intermediate information about the digest of a stream of data. */
1512 struct crypto_digest_env_t {
1513 union {
1514 SHA_CTX sha1;
1515 SHA256_CTX sha2;
1516 } d;
1517 digest_algorithm_t algorithm : 8;
1520 /** Allocate and return a new digest object.
1522 crypto_digest_env_t *
1523 crypto_new_digest_env(void)
1525 crypto_digest_env_t *r;
1526 r = tor_malloc(sizeof(crypto_digest_env_t));
1527 SHA1_Init(&r->d.sha1);
1528 r->algorithm = DIGEST_SHA1;
1529 return r;
1532 crypto_digest_env_t *
1533 crypto_new_digest256_env(digest_algorithm_t algorithm)
1535 crypto_digest_env_t *r;
1536 tor_assert(algorithm == DIGEST_SHA256);
1537 r = tor_malloc(sizeof(crypto_digest_env_t));
1538 SHA256_Init(&r->d.sha2);
1539 r->algorithm = algorithm;
1540 return r;
1543 /** Deallocate a digest object.
1545 void
1546 crypto_free_digest_env(crypto_digest_env_t *digest)
1548 if (!digest)
1549 return;
1550 memset(digest, 0, sizeof(crypto_digest_env_t));
1551 tor_free(digest);
1554 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1556 void
1557 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1558 size_t len)
1560 tor_assert(digest);
1561 tor_assert(data);
1562 /* Using the SHA*_*() calls directly means we don't support doing
1563 * SHA in hardware. But so far the delay of getting the question
1564 * to the hardware, and hearing the answer, is likely higher than
1565 * just doing it ourselves. Hashes are fast.
1567 switch (digest->algorithm) {
1568 case DIGEST_SHA1:
1569 SHA1_Update(&digest->d.sha1, (void*)data, len);
1570 break;
1571 case DIGEST_SHA256:
1572 SHA256_Update(&digest->d.sha2, (void*)data, len);
1573 break;
1574 default:
1575 tor_fragile_assert();
1576 break;
1580 /** Compute the hash of the data that has been passed to the digest
1581 * object; write the first out_len bytes of the result to <b>out</b>.
1582 * <b>out_len</b> must be \<= DIGEST256_LEN.
1584 void
1585 crypto_digest_get_digest(crypto_digest_env_t *digest,
1586 char *out, size_t out_len)
1588 unsigned char r[DIGEST256_LEN];
1589 crypto_digest_env_t tmpenv;
1590 tor_assert(digest);
1591 tor_assert(out);
1592 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1593 memcpy(&tmpenv, digest, sizeof(crypto_digest_env_t));
1594 switch (digest->algorithm) {
1595 case DIGEST_SHA1:
1596 tor_assert(out_len <= DIGEST_LEN);
1597 SHA1_Final(r, &tmpenv.d.sha1);
1598 break;
1599 case DIGEST_SHA256:
1600 tor_assert(out_len <= DIGEST256_LEN);
1601 SHA256_Final(r, &tmpenv.d.sha2);
1602 break;
1603 default:
1604 tor_fragile_assert();
1605 break;
1607 memcpy(out, r, out_len);
1608 memset(r, 0, sizeof(r));
1611 /** Allocate and return a new digest object with the same state as
1612 * <b>digest</b>
1614 crypto_digest_env_t *
1615 crypto_digest_dup(const crypto_digest_env_t *digest)
1617 crypto_digest_env_t *r;
1618 tor_assert(digest);
1619 r = tor_malloc(sizeof(crypto_digest_env_t));
1620 memcpy(r,digest,sizeof(crypto_digest_env_t));
1621 return r;
1624 /** Replace the state of the digest object <b>into</b> with the state
1625 * of the digest object <b>from</b>.
1627 void
1628 crypto_digest_assign(crypto_digest_env_t *into,
1629 const crypto_digest_env_t *from)
1631 tor_assert(into);
1632 tor_assert(from);
1633 memcpy(into,from,sizeof(crypto_digest_env_t));
1636 /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
1637 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
1638 * in <b>hmac_out</b>.
1640 void
1641 crypto_hmac_sha1(char *hmac_out,
1642 const char *key, size_t key_len,
1643 const char *msg, size_t msg_len)
1645 tor_assert(key_len < INT_MAX);
1646 tor_assert(msg_len < INT_MAX);
1647 HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
1648 (unsigned char*)hmac_out, NULL);
1651 /* DH */
1653 /** Shared P parameter for our DH key exchanged. */
1654 static BIGNUM *dh_param_p = NULL;
1655 /** Shared G parameter for our DH key exchanges. */
1656 static BIGNUM *dh_param_g = NULL;
1658 /** Initialize dh_param_p and dh_param_g if they are not already
1659 * set. */
1660 static void
1661 init_dh_param(void)
1663 BIGNUM *p, *g;
1664 int r;
1665 if (dh_param_p && dh_param_g)
1666 return;
1668 p = BN_new();
1669 g = BN_new();
1670 tor_assert(p);
1671 tor_assert(g);
1673 /* This is from rfc2409, section 6.2. It's a safe prime, and
1674 supposedly it equals:
1675 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1677 r = BN_hex2bn(&p,
1678 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1679 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1680 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1681 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1682 "49286651ECE65381FFFFFFFFFFFFFFFF");
1683 tor_assert(r);
1685 r = BN_set_word(g, 2);
1686 tor_assert(r);
1687 dh_param_p = p;
1688 dh_param_g = g;
1691 #define DH_PRIVATE_KEY_BITS 320
1693 /** Allocate and return a new DH object for a key exchange.
1695 crypto_dh_env_t *
1696 crypto_dh_new(void)
1698 crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1700 if (!dh_param_p)
1701 init_dh_param();
1703 if (!(res->dh = DH_new()))
1704 goto err;
1706 if (!(res->dh->p = BN_dup(dh_param_p)))
1707 goto err;
1709 if (!(res->dh->g = BN_dup(dh_param_g)))
1710 goto err;
1712 res->dh->length = DH_PRIVATE_KEY_BITS;
1714 return res;
1715 err:
1716 crypto_log_errors(LOG_WARN, "creating DH object");
1717 if (res->dh) DH_free(res->dh); /* frees p and g too */
1718 tor_free(res);
1719 return NULL;
1722 /** Return the length of the DH key in <b>dh</b>, in bytes.
1725 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1727 tor_assert(dh);
1728 return DH_size(dh->dh);
1731 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1732 * success, -1 on failure.
1735 crypto_dh_generate_public(crypto_dh_env_t *dh)
1737 again:
1738 if (!DH_generate_key(dh->dh)) {
1739 crypto_log_errors(LOG_WARN, "generating DH key");
1740 return -1;
1742 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
1743 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1744 "the-universe chances really do happen. Trying again.");
1745 /* Free and clear the keys, so OpenSSL will actually try again. */
1746 BN_free(dh->dh->pub_key);
1747 BN_free(dh->dh->priv_key);
1748 dh->dh->pub_key = dh->dh->priv_key = NULL;
1749 goto again;
1751 return 0;
1754 /** Generate g^x as necessary, and write the g^x for the key exchange
1755 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1756 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1759 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1761 int bytes;
1762 tor_assert(dh);
1763 if (!dh->dh->pub_key) {
1764 if (crypto_dh_generate_public(dh)<0)
1765 return -1;
1768 tor_assert(dh->dh->pub_key);
1769 bytes = BN_num_bytes(dh->dh->pub_key);
1770 tor_assert(bytes >= 0);
1771 if (pubkey_len < (size_t)bytes) {
1772 log_warn(LD_CRYPTO,
1773 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1774 (int) pubkey_len, bytes);
1775 return -1;
1778 memset(pubkey, 0, pubkey_len);
1779 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1781 return 0;
1784 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
1785 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1786 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1788 static int
1789 tor_check_dh_key(int severity, BIGNUM *bn)
1791 BIGNUM *x;
1792 char *s;
1793 tor_assert(bn);
1794 x = BN_new();
1795 tor_assert(x);
1796 if (!dh_param_p)
1797 init_dh_param();
1798 BN_set_word(x, 1);
1799 if (BN_cmp(bn,x)<=0) {
1800 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
1801 goto err;
1803 BN_copy(x,dh_param_p);
1804 BN_sub_word(x, 1);
1805 if (BN_cmp(bn,x)>=0) {
1806 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
1807 goto err;
1809 BN_free(x);
1810 return 0;
1811 err:
1812 BN_free(x);
1813 s = BN_bn2hex(bn);
1814 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1815 OPENSSL_free(s);
1816 return -1;
1819 #undef MIN
1820 #define MIN(a,b) ((a)<(b)?(a):(b))
1821 /** Given a DH key exchange object, and our peer's value of g^y (as a
1822 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1823 * <b>secret_bytes_out</b> bytes of shared key material and write them
1824 * to <b>secret_out</b>. Return the number of bytes generated on success,
1825 * or -1 on failure.
1827 * (We generate key material by computing
1828 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1829 * where || is concatenation.)
1831 ssize_t
1832 crypto_dh_compute_secret(int severity, crypto_dh_env_t *dh,
1833 const char *pubkey, size_t pubkey_len,
1834 char *secret_out, size_t secret_bytes_out)
1836 char *secret_tmp = NULL;
1837 BIGNUM *pubkey_bn = NULL;
1838 size_t secret_len=0;
1839 int result=0;
1840 tor_assert(dh);
1841 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1842 tor_assert(pubkey_len < INT_MAX);
1844 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
1845 (int)pubkey_len, NULL)))
1846 goto error;
1847 if (tor_check_dh_key(severity, pubkey_bn)<0) {
1848 /* Check for invalid public keys. */
1849 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
1850 goto error;
1852 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1853 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1854 if (result < 0) {
1855 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1856 goto error;
1858 secret_len = result;
1859 if (crypto_expand_key_material(secret_tmp, secret_len,
1860 secret_out, secret_bytes_out)<0)
1861 goto error;
1862 secret_len = secret_bytes_out;
1864 goto done;
1865 error:
1866 result = -1;
1867 done:
1868 crypto_log_errors(LOG_WARN, "completing DH handshake");
1869 if (pubkey_bn)
1870 BN_free(pubkey_bn);
1871 tor_free(secret_tmp);
1872 if (result < 0)
1873 return result;
1874 else
1875 return secret_len;
1878 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1879 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1880 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
1881 * H(K | [00]) | H(K | [01]) | ....
1883 * Return 0 on success, -1 on failure.
1886 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1887 char *key_out, size_t key_out_len)
1889 int i;
1890 char *cp, *tmp = tor_malloc(key_in_len+1);
1891 char digest[DIGEST_LEN];
1893 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1894 tor_assert(key_out_len <= DIGEST_LEN*256);
1896 memcpy(tmp, key_in, key_in_len);
1897 for (cp = key_out, i=0; cp < key_out+key_out_len;
1898 ++i, cp += DIGEST_LEN) {
1899 tmp[key_in_len] = i;
1900 if (crypto_digest(digest, tmp, key_in_len+1))
1901 goto err;
1902 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
1904 memset(tmp, 0, key_in_len+1);
1905 tor_free(tmp);
1906 memset(digest, 0, sizeof(digest));
1907 return 0;
1909 err:
1910 memset(tmp, 0, key_in_len+1);
1911 tor_free(tmp);
1912 memset(digest, 0, sizeof(digest));
1913 return -1;
1916 /** Free a DH key exchange object.
1918 void
1919 crypto_dh_free(crypto_dh_env_t *dh)
1921 if (!dh)
1922 return;
1923 tor_assert(dh->dh);
1924 DH_free(dh->dh);
1925 tor_free(dh);
1928 /* random numbers */
1930 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1931 * work for us too. */
1932 #define ADD_ENTROPY 32
1934 /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
1935 "release".) */
1936 #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1938 /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
1939 * would allocate an fd_set on the stack, open a new file, and try to FD_SET
1940 * that fd without checking whether it fit in the fd_set. Thus, if the
1941 * system has not just been started up, it is unsafe to call */
1942 #define RAND_POLL_IS_SAFE \
1943 ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
1944 OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
1945 (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
1947 static void
1948 seed_weak_rng(void)
1950 unsigned seed;
1951 crypto_rand((void*)&seed, sizeof(seed));
1952 tor_init_weak_random(seed);
1955 /** Seed OpenSSL's random number generator with bytes from the operating
1956 * system. <b>startup</b> should be true iff we have just started Tor and
1957 * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
1960 crypto_seed_rng(int startup)
1962 int rand_poll_status = 0;
1964 /* local variables */
1965 #ifdef MS_WINDOWS
1966 unsigned char buf[ADD_ENTROPY];
1967 static int provider_set = 0;
1968 static HCRYPTPROV provider;
1969 #else
1970 char buf[ADD_ENTROPY];
1971 static const char *filenames[] = {
1972 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1974 int fd, i;
1975 size_t n;
1976 #endif
1978 #if HAVE_RAND_POLL
1979 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1980 * entropy than we do. We'll try calling that, *and* calling our own entropy
1981 * functions. If one succeeds, we'll accept the RNG as seeded. */
1982 if (startup || RAND_POLL_IS_SAFE) {
1983 rand_poll_status = RAND_poll();
1984 if (rand_poll_status == 0)
1985 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1987 #endif
1989 #ifdef MS_WINDOWS
1990 if (!provider_set) {
1991 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1992 CRYPT_VERIFYCONTEXT)) {
1993 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1994 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1995 return rand_poll_status ? 0 : -1;
1998 provider_set = 1;
2000 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
2001 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2002 return rand_poll_status ? 0 : -1;
2004 RAND_seed(buf, sizeof(buf));
2005 memset(buf, 0, sizeof(buf));
2006 seed_weak_rng();
2007 return 0;
2008 #else
2009 for (i = 0; filenames[i]; ++i) {
2010 fd = open(filenames[i], O_RDONLY, 0);
2011 if (fd<0) continue;
2012 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
2013 n = read_all(fd, buf, sizeof(buf), 0);
2014 close(fd);
2015 if (n != sizeof(buf)) {
2016 log_warn(LD_CRYPTO,
2017 "Error reading from entropy source (read only %lu bytes).",
2018 (unsigned long)n);
2019 return -1;
2021 RAND_seed(buf, (int)sizeof(buf));
2022 memset(buf, 0, sizeof(buf));
2023 seed_weak_rng();
2024 return 0;
2027 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
2028 return rand_poll_status ? 0 : -1;
2029 #endif
2032 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
2033 * success, -1 on failure.
2036 crypto_rand(char *to, size_t n)
2038 int r;
2039 tor_assert(n < INT_MAX);
2040 tor_assert(to);
2041 r = RAND_bytes((unsigned char*)to, (int)n);
2042 if (r == 0)
2043 crypto_log_errors(LOG_WARN, "generating random data");
2044 return (r == 1) ? 0 : -1;
2047 /** Return a pseudorandom integer, chosen uniformly from the values
2048 * between 0 and <b>max</b>-1. */
2050 crypto_rand_int(unsigned int max)
2052 unsigned int val;
2053 unsigned int cutoff;
2054 tor_assert(max < UINT_MAX);
2055 tor_assert(max > 0); /* don't div by 0 */
2057 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2058 * distribution with clipping at the upper end of unsigned int's
2059 * range.
2061 cutoff = UINT_MAX - (UINT_MAX%max);
2062 while (1) {
2063 crypto_rand((char*)&val, sizeof(val));
2064 if (val < cutoff)
2065 return val % max;
2069 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2070 * between 0 and <b>max</b>-1. */
2071 uint64_t
2072 crypto_rand_uint64(uint64_t max)
2074 uint64_t val;
2075 uint64_t cutoff;
2076 tor_assert(max < UINT64_MAX);
2077 tor_assert(max > 0); /* don't div by 0 */
2079 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2080 * distribution with clipping at the upper end of unsigned int's
2081 * range.
2083 cutoff = UINT64_MAX - (UINT64_MAX%max);
2084 while (1) {
2085 crypto_rand((char*)&val, sizeof(val));
2086 if (val < cutoff)
2087 return val % max;
2091 /** Return a pseudorandom double d, chosen uniformly from the range
2092 * 0.0 <= d < 1.0.
2094 double
2095 crypto_rand_double(void)
2097 /* We just use an unsigned int here; we don't really care about getting
2098 * more than 32 bits of resolution */
2099 unsigned int uint;
2100 crypto_rand((char*)&uint, sizeof(uint));
2101 #if SIZEOF_INT == 4
2102 #define UINT_MAX_AS_DOUBLE 4294967296.0
2103 #elif SIZEOF_INT == 8
2104 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2105 #else
2106 #error SIZEOF_INT is neither 4 nor 8
2107 #endif
2108 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2111 /** Generate and return a new random hostname starting with <b>prefix</b>,
2112 * ending with <b>suffix</b>, and containing no less than
2113 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2114 * characters between. */
2115 char *
2116 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2117 const char *suffix)
2119 char *result, *rand_bytes;
2120 int randlen, rand_bytes_len;
2121 size_t resultlen, prefixlen;
2123 tor_assert(max_rand_len >= min_rand_len);
2124 randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
2125 prefixlen = strlen(prefix);
2126 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2128 rand_bytes_len = ((randlen*5)+7)/8;
2129 if (rand_bytes_len % 5)
2130 rand_bytes_len += 5 - (rand_bytes_len%5);
2131 rand_bytes = tor_malloc(rand_bytes_len);
2132 crypto_rand(rand_bytes, rand_bytes_len);
2134 result = tor_malloc(resultlen);
2135 memcpy(result, prefix, prefixlen);
2136 base32_encode(result+prefixlen, resultlen-prefixlen,
2137 rand_bytes, rand_bytes_len);
2138 tor_free(rand_bytes);
2139 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2141 return result;
2144 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2145 * is empty. */
2146 void *
2147 smartlist_choose(const smartlist_t *sl)
2149 int len = smartlist_len(sl);
2150 if (len)
2151 return smartlist_get(sl,crypto_rand_int(len));
2152 return NULL; /* no elements to choose from */
2155 /** Scramble the elements of <b>sl</b> into a random order. */
2156 void
2157 smartlist_shuffle(smartlist_t *sl)
2159 int i;
2160 /* From the end of the list to the front, choose at random from the
2161 positions we haven't looked at yet, and swap that position into the
2162 current position. Remember to give "no swap" the same probability as
2163 any other swap. */
2164 for (i = smartlist_len(sl)-1; i > 0; --i) {
2165 int j = crypto_rand_int(i+1);
2166 smartlist_swap(sl, i, j);
2170 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
2171 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2172 * bytes. Return the number of bytes written on success; -1 if
2173 * destlen is too short, or other failure.
2176 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2178 /* FFFF we might want to rewrite this along the lines of base64_decode, if
2179 * it ever shows up in the profile. */
2180 EVP_ENCODE_CTX ctx;
2181 int len, ret;
2182 tor_assert(srclen < INT_MAX);
2184 /* 48 bytes of input -> 64 bytes of output plus newline.
2185 Plus one more byte, in case I'm wrong.
2187 if (destlen < ((srclen/48)+1)*66)
2188 return -1;
2189 if (destlen > SIZE_T_CEILING)
2190 return -1;
2192 EVP_EncodeInit(&ctx);
2193 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
2194 (unsigned char*)src, (int)srclen);
2195 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
2196 ret += len;
2197 return ret;
2200 #define X 255
2201 #define SP 64
2202 #define PAD 65
2203 /** Internal table mapping byte values to what they represent in base64.
2204 * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
2205 * skipped. Xs are invalid and must not appear in base64. PAD indicates
2206 * end-of-string. */
2207 static const uint8_t base64_decode_table[256] = {
2208 X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
2209 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2210 SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
2211 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
2212 X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2213 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
2214 X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2215 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
2216 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2217 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2218 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2219 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2220 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2221 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2222 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2223 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
2226 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
2227 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
2228 * bytes. Return the number of bytes written on success; -1 if
2229 * destlen is too short, or other failure.
2231 * NOTE 1: destlen is checked conservatively, as though srclen contained no
2232 * spaces or padding.
2234 * NOTE 2: This implementation does not check for the correct number of
2235 * padding "=" characters at the end of the string, and does not check
2236 * for internal padding characters.
2239 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2241 #ifdef USE_OPENSSL_BASE64
2242 EVP_ENCODE_CTX ctx;
2243 int len, ret;
2244 /* 64 bytes of input -> *up to* 48 bytes of output.
2245 Plus one more byte, in case I'm wrong.
2247 if (destlen < ((srclen/64)+1)*49)
2248 return -1;
2249 if (destlen > SIZE_T_CEILING)
2250 return -1;
2252 EVP_DecodeInit(&ctx);
2253 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
2254 (unsigned char*)src, srclen);
2255 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
2256 ret += len;
2257 return ret;
2258 #else
2259 const char *eos = src+srclen;
2260 uint32_t n=0;
2261 int n_idx=0;
2262 char *dest_orig = dest;
2264 /* Max number of bits == srclen*6.
2265 * Number of bytes required to hold all bits == (srclen*6)/8.
2266 * Yes, we want to round down: anything that hangs over the end of a
2267 * byte is padding. */
2268 if (destlen < (srclen*3)/4)
2269 return -1;
2270 if (destlen > SIZE_T_CEILING)
2271 return -1;
2273 /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
2274 * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
2275 * 24 bits, batch them into 3 bytes and flush those bytes to dest.
2277 for ( ; src < eos; ++src) {
2278 unsigned char c = (unsigned char) *src;
2279 uint8_t v = base64_decode_table[c];
2280 switch (v) {
2281 case X:
2282 /* This character isn't allowed in base64. */
2283 return -1;
2284 case SP:
2285 /* This character is whitespace, and has no effect. */
2286 continue;
2287 case PAD:
2288 /* We've hit an = character: the data is over. */
2289 goto end_of_loop;
2290 default:
2291 /* We have an actual 6-bit value. Append it to the bits in n. */
2292 n = (n<<6) | v;
2293 if ((++n_idx) == 4) {
2294 /* We've accumulated 24 bits in n. Flush them. */
2295 *dest++ = (n>>16);
2296 *dest++ = (n>>8) & 0xff;
2297 *dest++ = (n) & 0xff;
2298 n_idx = 0;
2299 n = 0;
2303 end_of_loop:
2304 /* If we have leftover bits, we need to cope. */
2305 switch (n_idx) {
2306 case 0:
2307 default:
2308 /* No leftover bits. We win. */
2309 break;
2310 case 1:
2311 /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
2312 return -1;
2313 case 2:
2314 /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
2315 *dest++ = n >> 4;
2316 break;
2317 case 3:
2318 /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
2319 *dest++ = n >> 10;
2320 *dest++ = n >> 2;
2323 tor_assert((dest-dest_orig) <= (ssize_t)destlen);
2324 tor_assert((dest-dest_orig) <= INT_MAX);
2326 return (int)(dest-dest_orig);
2327 #endif
2329 #undef X
2330 #undef SP
2331 #undef PAD
2333 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
2334 * and newline characters, and store the nul-terminated result in the first
2335 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
2337 digest_to_base64(char *d64, const char *digest)
2339 char buf[256];
2340 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
2341 buf[BASE64_DIGEST_LEN] = '\0';
2342 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
2343 return 0;
2346 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2347 * trailing newline or = characters), decode it and store the result in the
2348 * first DIGEST_LEN bytes at <b>digest</b>. */
2350 digest_from_base64(char *digest, const char *d64)
2352 #ifdef USE_OPENSSL_BASE64
2353 char buf_in[BASE64_DIGEST_LEN+3];
2354 char buf[256];
2355 if (strlen(d64) != BASE64_DIGEST_LEN)
2356 return -1;
2357 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
2358 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
2359 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
2360 return -1;
2361 memcpy(digest, buf, DIGEST_LEN);
2362 return 0;
2363 #else
2364 if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
2365 return 0;
2366 else
2367 return -1;
2368 #endif
2371 /** Base-64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
2372 * trailing = and newline characters, and store the nul-terminated result in
2373 * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
2375 digest256_to_base64(char *d64, const char *digest)
2377 char buf[256];
2378 base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
2379 buf[BASE64_DIGEST256_LEN] = '\0';
2380 memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
2381 return 0;
2384 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
2385 * trailing newline or = characters), decode it and store the result in the
2386 * first DIGEST256_LEN bytes at <b>digest</b>. */
2388 digest256_from_base64(char *digest, const char *d64)
2390 #ifdef USE_OPENSSL_BASE64
2391 char buf_in[BASE64_DIGEST256_LEN+3];
2392 char buf[256];
2393 if (strlen(d64) != BASE64_DIGEST256_LEN)
2394 return -1;
2395 memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
2396 memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
2397 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
2398 return -1;
2399 memcpy(digest, buf, DIGEST256_LEN);
2400 return 0;
2401 #else
2402 if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
2403 return 0;
2404 else
2405 return -1;
2406 #endif
2409 /** Implements base32 encoding as in rfc3548. Limitation: Requires
2410 * that srclen*8 is a multiple of 5.
2412 void
2413 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
2415 unsigned int i, v, u;
2416 size_t nbits = srclen * 8, bit;
2418 tor_assert(srclen < SIZE_T_CEILING/8);
2419 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
2420 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
2421 tor_assert(destlen < SIZE_T_CEILING);
2423 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
2424 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
2425 v = ((uint8_t)src[bit/8]) << 8;
2426 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
2427 /* set u to the 5-bit value at the bit'th bit of src. */
2428 u = (v >> (11-(bit%8))) & 0x1F;
2429 dest[i] = BASE32_CHARS[u];
2431 dest[i] = '\0';
2434 /** Implements base32 decoding as in rfc3548. Limitation: Requires
2435 * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
2438 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
2440 /* XXXX we might want to rewrite this along the lines of base64_decode, if
2441 * it ever shows up in the profile. */
2442 unsigned int i, bit;
2443 size_t nbits, j;
2444 char *tmp;
2445 nbits = srclen * 5;
2447 tor_assert(srclen < SIZE_T_CEILING / 5);
2448 tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
2449 tor_assert((nbits/8) <= destlen); /* We need enough space. */
2450 tor_assert(destlen < SIZE_T_CEILING);
2452 /* Convert base32 encoded chars to the 5-bit values that they represent. */
2453 tmp = tor_malloc_zero(srclen);
2454 for (j = 0; j < srclen; ++j) {
2455 if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
2456 else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
2457 else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
2458 else {
2459 log_warn(LD_BUG, "illegal character in base32 encoded string");
2460 tor_free(tmp);
2461 return -1;
2465 /* Assemble result byte-wise by applying five possible cases. */
2466 for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
2467 switch (bit % 40) {
2468 case 0:
2469 dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
2470 (((uint8_t)tmp[(bit/5)+1]) >> 2);
2471 break;
2472 case 8:
2473 dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
2474 (((uint8_t)tmp[(bit/5)+1]) << 1) +
2475 (((uint8_t)tmp[(bit/5)+2]) >> 4);
2476 break;
2477 case 16:
2478 dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
2479 (((uint8_t)tmp[(bit/5)+1]) >> 1);
2480 break;
2481 case 24:
2482 dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
2483 (((uint8_t)tmp[(bit/5)+1]) << 2) +
2484 (((uint8_t)tmp[(bit/5)+2]) >> 3);
2485 break;
2486 case 32:
2487 dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
2488 ((uint8_t)tmp[(bit/5)+1]);
2489 break;
2493 memset(tmp, 0, srclen);
2494 tor_free(tmp);
2495 tmp = NULL;
2496 return 0;
2499 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
2500 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
2501 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
2502 * are a salt; the 9th byte describes how much iteration to do.
2503 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
2505 void
2506 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
2507 size_t secret_len, const char *s2k_specifier)
2509 crypto_digest_env_t *d;
2510 uint8_t c;
2511 size_t count, tmplen;
2512 char *tmp;
2513 tor_assert(key_out_len < SIZE_T_CEILING);
2515 #define EXPBIAS 6
2516 c = s2k_specifier[8];
2517 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
2518 #undef EXPBIAS
2520 tor_assert(key_out_len <= DIGEST_LEN);
2522 d = crypto_new_digest_env();
2523 tmplen = 8+secret_len;
2524 tmp = tor_malloc(tmplen);
2525 memcpy(tmp,s2k_specifier,8);
2526 memcpy(tmp+8,secret,secret_len);
2527 secret_len += 8;
2528 while (count) {
2529 if (count >= secret_len) {
2530 crypto_digest_add_bytes(d, tmp, secret_len);
2531 count -= secret_len;
2532 } else {
2533 crypto_digest_add_bytes(d, tmp, count);
2534 count = 0;
2537 crypto_digest_get_digest(d, key_out, key_out_len);
2538 memset(tmp, 0, tmplen);
2539 tor_free(tmp);
2540 crypto_free_digest_env(d);
2543 #ifdef TOR_IS_MULTITHREADED
2544 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
2545 static void
2546 _openssl_locking_cb(int mode, int n, const char *file, int line)
2548 (void)file;
2549 (void)line;
2550 if (!_openssl_mutexes)
2551 /* This is not a really good fix for the
2552 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
2553 * it can't hurt. */
2554 return;
2555 if (mode & CRYPTO_LOCK)
2556 tor_mutex_acquire(_openssl_mutexes[n]);
2557 else
2558 tor_mutex_release(_openssl_mutexes[n]);
2561 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
2562 * as a lock. */
2563 struct CRYPTO_dynlock_value {
2564 tor_mutex_t *lock;
2567 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
2568 * documentation in OpenSSL's docs for more info. */
2569 static struct CRYPTO_dynlock_value *
2570 _openssl_dynlock_create_cb(const char *file, int line)
2572 struct CRYPTO_dynlock_value *v;
2573 (void)file;
2574 (void)line;
2575 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
2576 v->lock = tor_mutex_new();
2577 return v;
2580 /** OpenSSL callback function to acquire or release a lock: see
2581 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
2582 static void
2583 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
2584 const char *file, int line)
2586 (void)file;
2587 (void)line;
2588 if (mode & CRYPTO_LOCK)
2589 tor_mutex_acquire(v->lock);
2590 else
2591 tor_mutex_release(v->lock);
2594 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
2595 * documentation in OpenSSL's docs for more info. */
2596 static void
2597 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
2598 const char *file, int line)
2600 (void)file;
2601 (void)line;
2602 tor_mutex_free(v->lock);
2603 tor_free(v);
2606 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
2607 * multithreaded. */
2608 static int
2609 setup_openssl_threading(void)
2611 int i;
2612 int n = CRYPTO_num_locks();
2613 _n_openssl_mutexes = n;
2614 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
2615 for (i=0; i < n; ++i)
2616 _openssl_mutexes[i] = tor_mutex_new();
2617 CRYPTO_set_locking_callback(_openssl_locking_cb);
2618 CRYPTO_set_id_callback(tor_get_thread_id);
2619 CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
2620 CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
2621 CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
2622 return 0;
2624 #else
2625 static int
2626 setup_openssl_threading(void)
2628 return 0;
2630 #endif