r12001@catbus: nickm | 2007-02-28 15:24:12 -0500
[tor.git] / src / common / crypto.c
blob0daf24310f757e2e4fa2d36091fc3008e1632404
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char crypto_c_id[] =
7 "$Id$";
9 /**
10 * \file crypto.c
11 * \brief Wrapper functions to present a consistent interface to
12 * public-key and symmetric cryptography operations from OpenSSL.
13 **/
15 #include "orconfig.h"
17 #ifdef MS_WINDOWS
18 #define WIN32_WINNT 0x400
19 #define _WIN32_WINNT 0x400
20 #define WIN32_LEAN_AND_MEAN
21 #include <windows.h>
22 #include <wincrypt.h>
23 #endif
25 #include <string.h>
27 #include <openssl/err.h>
28 #include <openssl/rsa.h>
29 #include <openssl/pem.h>
30 #include <openssl/evp.h>
31 #include <openssl/rand.h>
32 #include <openssl/opensslv.h>
33 #include <openssl/bn.h>
34 #include <openssl/dh.h>
35 #include <openssl/rsa.h>
36 #include <openssl/dh.h>
37 #include <openssl/conf.h>
39 #include <stdlib.h>
40 #include <assert.h>
41 #include <stdio.h>
42 #include <limits.h>
44 #ifdef HAVE_CTYPE_H
45 #include <ctype.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #ifdef HAVE_SYS_FCNTL_H
54 #include <sys/fcntl.h>
55 #endif
57 #include "crypto.h"
58 #include "log.h"
59 #include "aes.h"
60 #include "util.h"
61 #include "container.h"
62 #include "compat.h"
64 #if OPENSSL_VERSION_NUMBER < 0x00905000l
65 #error "We require openssl >= 0.9.5"
66 #endif
68 #if OPENSSL_VERSION_NUMBER < 0x00907000l
69 #define NO_ENGINES
70 #else
71 #include <openssl/engine.h>
72 #endif
74 /** Macro: is k a valid RSA public or private key? */
75 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
76 /** Macro: is k a valid RSA private key? */
77 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
79 #ifdef TOR_IS_MULTITHREADED
80 /** A number of prealloced mutexes for use by openssl. */
81 static tor_mutex_t **_openssl_mutexes = NULL;
82 /** How many mutexes have we allocated for use by openssl? */
83 static int _n_openssl_mutexes = 0;
84 #endif
86 /** A public key, or a public/private keypair. */
87 struct crypto_pk_env_t
89 int refs; /* reference counting so we don't have to copy keys */
90 RSA *key;
93 /** Key and stream information for a stream cipher. */
94 struct crypto_cipher_env_t
96 char key[CIPHER_KEY_LEN];
97 aes_cnt_cipher_t *cipher;
100 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
101 * while we're waiting for the second.*/
102 struct crypto_dh_env_t {
103 DH *dh;
106 /* Prototypes for functions only used by tortls.c */
107 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
108 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
109 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
111 static int setup_openssl_threading(void);
112 static int tor_check_dh_key(BIGNUM *bn);
114 /** Return the number of bytes added by padding method <b>padding</b>.
116 static INLINE int
117 crypto_get_rsa_padding_overhead(int padding)
119 switch (padding)
121 case RSA_NO_PADDING: return 0;
122 case RSA_PKCS1_OAEP_PADDING: return 42;
123 case RSA_PKCS1_PADDING: return 11;
124 default: tor_assert(0); return -1;
128 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
130 static INLINE int
131 crypto_get_rsa_padding(int padding)
133 switch (padding)
135 case PK_NO_PADDING: return RSA_NO_PADDING;
136 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
137 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
138 default: tor_assert(0); return -1;
142 /** Boolean: has OpenSSL's crypto been initialized? */
143 static int _crypto_global_initialized = 0;
145 /** Log all pending crypto errors at level <b>severity</b>. Use
146 * <b>doing</b> to describe our current activities.
148 static void
149 crypto_log_errors(int severity, const char *doing)
151 unsigned int err;
152 const char *msg, *lib, *func;
153 while ((err = ERR_get_error()) != 0) {
154 msg = (const char*)ERR_reason_error_string(err);
155 lib = (const char*)ERR_lib_error_string(err);
156 func = (const char*)ERR_func_error_string(err);
157 if (!msg) msg = "(null)";
158 if (!lib) lib = "(null)";
159 if (!func) func = "(null)";
160 if (doing) {
161 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
162 doing, msg, lib, func);
163 } else {
164 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
169 #ifndef NO_ENGINES
170 /** Log any OpenSSL engines we're using at NOTICE. */
171 static void
172 log_engine(const char *fn, ENGINE *e)
174 if (e) {
175 const char *name, *id;
176 name = ENGINE_get_name(e);
177 id = ENGINE_get_id(e);
178 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
179 name?name:"?", id?id:"?", fn);
180 } else {
181 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
184 #endif
186 /** Initialize the crypto library. Return 0 on success, -1 on failure.
189 crypto_global_init(int useAccel)
191 if (!_crypto_global_initialized) {
192 ERR_load_crypto_strings();
193 OpenSSL_add_all_algorithms();
194 _crypto_global_initialized = 1;
195 setup_openssl_threading();
196 /* XXX the below is a bug, since we can't know if we're supposed
197 * to be using hardware acceleration or not. we should arrange
198 * for this function to be called before init_keys. But make it
199 * not complain loudly, at least until we make acceleration work. */
200 if (useAccel < 0) {
201 log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
203 #ifndef NO_ENGINES
204 if (useAccel > 0) {
205 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
206 ENGINE_load_builtin_engines();
207 if (!ENGINE_register_all_complete())
208 return -1;
210 /* XXXX make sure this isn't leaking. */
211 log_engine("RSA", ENGINE_get_default_RSA());
212 log_engine("DH", ENGINE_get_default_DH());
213 log_engine("RAND", ENGINE_get_default_RAND());
214 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
215 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
216 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
218 #endif
220 return 0;
223 /** Free crypto resources held by this thread. */
224 void
225 crypto_thread_cleanup(void)
227 ERR_remove_state(0);
230 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
233 crypto_global_cleanup(void)
235 EVP_cleanup();
236 ERR_remove_state(0);
237 ERR_free_strings();
238 #ifndef NO_ENGINES
239 ENGINE_cleanup();
240 CONF_modules_unload(1);
241 CRYPTO_cleanup_all_ex_data();
242 #endif
243 #ifdef TOR_IS_MULTITHREADED
244 if (_n_openssl_mutexes) {
245 int n = _n_openssl_mutexes;
246 tor_mutex_t **ms = _openssl_mutexes;
247 int i;
248 _openssl_mutexes = NULL;
249 _n_openssl_mutexes = 0;
250 for (i=0;i<n;++i) {
251 tor_mutex_free(ms[i]);
253 tor_free(ms);
255 #endif
256 return 0;
259 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
260 crypto_pk_env_t *
261 _crypto_new_pk_env_rsa(RSA *rsa)
263 crypto_pk_env_t *env;
264 tor_assert(rsa);
265 env = tor_malloc(sizeof(crypto_pk_env_t));
266 env->refs = 1;
267 env->key = rsa;
268 return env;
271 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
272 * private is set, include the private-key portion of the key. */
273 EVP_PKEY *
274 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
276 RSA *key = NULL;
277 EVP_PKEY *pkey = NULL;
278 tor_assert(env->key);
279 if (private) {
280 if (!(key = RSAPrivateKey_dup(env->key)))
281 goto error;
282 } else {
283 if (!(key = RSAPublicKey_dup(env->key)))
284 goto error;
286 if (!(pkey = EVP_PKEY_new()))
287 goto error;
288 if (!(EVP_PKEY_assign_RSA(pkey, key)))
289 goto error;
290 return pkey;
291 error:
292 if (pkey)
293 EVP_PKEY_free(pkey);
294 if (key)
295 RSA_free(key);
296 return NULL;
299 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
301 DH *
302 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
304 return dh->dh;
307 /** Allocate and return storage for a public key. The key itself will not yet
308 * be set.
310 crypto_pk_env_t *
311 crypto_new_pk_env(void)
313 RSA *rsa;
315 rsa = RSA_new();
316 if (!rsa) return NULL;
317 return _crypto_new_pk_env_rsa(rsa);
320 /** Release a reference to an asymmetric key; when all the references
321 * are released, free the key.
323 void
324 crypto_free_pk_env(crypto_pk_env_t *env)
326 tor_assert(env);
328 if (--env->refs > 0)
329 return;
331 if (env->key)
332 RSA_free(env->key);
334 tor_free(env);
337 /** Create a new symmetric cipher for a given key and encryption flag
338 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
339 * on failure.
341 crypto_cipher_env_t *
342 crypto_create_init_cipher(const char *key, int encrypt_mode)
344 int r;
345 crypto_cipher_env_t *crypto = NULL;
347 if (! (crypto = crypto_new_cipher_env())) {
348 log_warn(LD_CRYPTO, "Unable to allocate crypto object");
349 return NULL;
352 if (crypto_cipher_set_key(crypto, key)) {
353 crypto_log_errors(LOG_WARN, "setting symmetric key");
354 goto error;
357 if (encrypt_mode)
358 r = crypto_cipher_encrypt_init_cipher(crypto);
359 else
360 r = crypto_cipher_decrypt_init_cipher(crypto);
362 if (r)
363 goto error;
364 return crypto;
366 error:
367 if (crypto)
368 crypto_free_cipher_env(crypto);
369 return NULL;
372 /** Allocate and return a new symmetric cipher.
374 crypto_cipher_env_t *
375 crypto_new_cipher_env(void)
377 crypto_cipher_env_t *env;
379 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
380 env->cipher = aes_new_cipher();
381 return env;
384 /** Free a symmetric cipher.
386 void
387 crypto_free_cipher_env(crypto_cipher_env_t *env)
389 tor_assert(env);
391 tor_assert(env->cipher);
392 aes_free_cipher(env->cipher);
393 tor_free(env);
396 /* public key crypto */
398 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
399 * success, -1 on failure.
402 crypto_pk_generate_key(crypto_pk_env_t *env)
404 tor_assert(env);
406 if (env->key)
407 RSA_free(env->key);
408 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
409 if (!env->key) {
410 crypto_log_errors(LOG_WARN, "generating RSA key");
411 return -1;
414 return 0;
417 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
418 * Return 0 on success, -1 on failure.
420 static int
421 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
422 const char *s)
424 BIO *b;
426 tor_assert(env);
427 tor_assert(s);
429 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
430 b = BIO_new_mem_buf((char*)s, -1);
432 if (env->key)
433 RSA_free(env->key);
435 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
437 BIO_free(b);
439 if (!env->key) {
440 crypto_log_errors(LOG_WARN, "Error parsing private key");
441 return -1;
443 return 0;
446 /** Read a PEM-encoded private key from the file named by
447 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
450 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
451 const char *keyfile)
453 char *contents;
454 int r;
456 /* Read the file into a string. */
457 contents = read_file_to_str(keyfile, 0, NULL);
458 if (!contents) {
459 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
460 return -1;
463 /* Try to parse it. */
464 r = crypto_pk_read_private_key_from_string(env, contents);
465 tor_free(contents);
466 if (r)
467 return -1; /* read_private_key_from_string already warned, so we don't.*/
469 /* Make sure it's valid. */
470 if (crypto_pk_check_key(env) <= 0)
471 return -1;
473 return 0;
476 /** PEM-encode the public key portion of <b>env</b> and write it to a
477 * newly allocated string. On success, set *<b>dest</b> to the new
478 * string, *<b>len</b> to the string's length, and return 0. On
479 * failure, return -1.
482 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
483 size_t *len)
485 BUF_MEM *buf;
486 BIO *b;
488 tor_assert(env);
489 tor_assert(env->key);
490 tor_assert(dest);
492 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
494 /* Now you can treat b as if it were a file. Just use the
495 * PEM_*_bio_* functions instead of the non-bio variants.
497 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
498 crypto_log_errors(LOG_WARN, "writing public key to string");
499 return -1;
502 BIO_get_mem_ptr(b, &buf);
503 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
504 BIO_free(b);
506 tor_assert(buf->length >= 0);
507 *dest = tor_malloc(buf->length+1);
508 memcpy(*dest, buf->data, buf->length);
509 (*dest)[buf->length] = 0; /* nul terminate it */
510 *len = buf->length;
511 BUF_MEM_free(buf);
513 return 0;
516 /** Read a PEM-encoded public key from the first <b>len</b> characters of
517 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
518 * failure.
521 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
522 size_t len)
524 BIO *b;
526 tor_assert(env);
527 tor_assert(src);
529 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
531 BIO_write(b, src, len);
533 if (env->key)
534 RSA_free(env->key);
535 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
536 BIO_free(b);
537 if (!env->key) {
538 crypto_log_errors(LOG_WARN, "reading public key from string");
539 return -1;
542 return 0;
545 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
546 * PEM-encoded. Return 0 on success, -1 on failure.
549 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
550 const char *fname)
552 BIO *bio;
553 char *cp;
554 long len;
555 char *s;
556 int r;
558 tor_assert(PRIVATE_KEY_OK(env));
560 if (!(bio = BIO_new(BIO_s_mem())))
561 return -1;
562 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
563 == 0) {
564 crypto_log_errors(LOG_WARN, "writing private key");
565 BIO_free(bio);
566 return -1;
568 len = BIO_get_mem_data(bio, &cp);
569 tor_assert(len >= 0);
570 s = tor_malloc(len+1);
571 memcpy(s, cp, len);
572 s[len]='\0';
573 r = write_str_to_file(fname, s, 0);
574 BIO_free(bio);
575 tor_free(s);
576 return r;
579 /** Return true iff <b>env</b> has a valid key.
582 crypto_pk_check_key(crypto_pk_env_t *env)
584 int r;
585 tor_assert(env);
587 r = RSA_check_key(env->key);
588 if (r <= 0)
589 crypto_log_errors(LOG_WARN,"checking RSA key");
590 return r;
593 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
594 * if a==b, and 1 if a\>b.
597 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
599 int result;
601 if (!a || !b)
602 return -1;
604 if (!a->key || !b->key)
605 return -1;
607 tor_assert(PUBLIC_KEY_OK(a));
608 tor_assert(PUBLIC_KEY_OK(b));
609 result = BN_cmp((a->key)->n, (b->key)->n);
610 if (result)
611 return result;
612 return BN_cmp((a->key)->e, (b->key)->e);
615 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
616 size_t
617 crypto_pk_keysize(crypto_pk_env_t *env)
619 tor_assert(env);
620 tor_assert(env->key);
622 return (size_t) RSA_size(env->key);
625 /** Increase the reference count of <b>env</b>, and return it.
627 crypto_pk_env_t *
628 crypto_pk_dup_key(crypto_pk_env_t *env)
630 tor_assert(env);
631 tor_assert(env->key);
633 env->refs++;
634 return env;
637 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
638 * in <b>env</b>, using the padding method <b>padding</b>. On success,
639 * write the result to <b>to</b>, and return the number of bytes
640 * written. On failure, return -1.
643 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
644 const char *from, size_t fromlen, int padding)
646 int r;
647 tor_assert(env);
648 tor_assert(from);
649 tor_assert(to);
651 r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
652 env->key, crypto_get_rsa_padding(padding));
653 if (r<0) {
654 crypto_log_errors(LOG_WARN, "performing RSA encryption");
655 return -1;
657 return r;
660 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
661 * in <b>env</b>, using the padding method <b>padding</b>. On success,
662 * write the result to <b>to</b>, and return the number of bytes
663 * written. On failure, return -1.
666 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
667 const char *from, size_t fromlen,
668 int padding, int warnOnFailure)
670 int r;
671 tor_assert(env);
672 tor_assert(from);
673 tor_assert(to);
674 tor_assert(env->key);
675 if (!env->key->p)
676 /* Not a private key */
677 return -1;
679 r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
680 env->key, crypto_get_rsa_padding(padding));
682 if (r<0) {
683 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
684 "performing RSA decryption");
685 return -1;
687 return r;
690 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
691 * public key in <b>env</b>, using PKCS1 padding. On success, write the
692 * signed data to <b>to</b>, and return the number of bytes written.
693 * On failure, return -1.
696 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
697 const char *from, size_t fromlen)
699 int r;
700 tor_assert(env);
701 tor_assert(from);
702 tor_assert(to);
703 r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
704 env->key, RSA_PKCS1_PADDING);
706 if (r<0) {
707 crypto_log_errors(LOG_WARN, "checking RSA signature");
708 return -1;
710 return r;
713 /** Check a siglen-byte long signature at <b>sig</b> against
714 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
715 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
716 * SHA1(data). Else return -1.
719 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
720 int datalen, const char *sig, int siglen)
722 char digest[DIGEST_LEN];
723 char buf[PK_BYTES+1];
724 int r;
726 tor_assert(env);
727 tor_assert(data);
728 tor_assert(sig);
730 if (crypto_digest(digest,data,datalen)<0) {
731 log_warn(LD_BUG, "couldn't compute digest");
732 return -1;
734 r = crypto_pk_public_checksig(env,buf,sig,siglen);
735 if (r != DIGEST_LEN) {
736 log_warn(LD_CRYPTO, "Invalid signature");
737 return -1;
739 if (memcmp(buf, digest, DIGEST_LEN)) {
740 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
741 return -1;
744 return 0;
747 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
748 * <b>env</b>, using PKCS1 padding. On success, write the signature to
749 * <b>to</b>, and return the number of bytes written. On failure, return
750 * -1.
753 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
754 const char *from, size_t fromlen)
756 int r;
757 tor_assert(env);
758 tor_assert(from);
759 tor_assert(to);
760 if (!env->key->p)
761 /* Not a private key */
762 return -1;
764 r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
765 env->key, RSA_PKCS1_PADDING);
766 if (r<0) {
767 crypto_log_errors(LOG_WARN, "generating RSA signature");
768 return -1;
770 return r;
773 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
774 * <b>from</b>; sign the data with the private key in <b>env</b>, and
775 * store it in <b>to</b>. Return the number of bytes written on
776 * success, and -1 on failure.
779 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
780 const char *from, size_t fromlen)
782 char digest[DIGEST_LEN];
783 if (crypto_digest(digest,from,fromlen)<0)
784 return -1;
785 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
788 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
789 * bytes of data from <b>from</b>, with padding type 'padding',
790 * storing the results on <b>to</b>.
792 * If no padding is used, the public key must be at least as large as
793 * <b>from</b>.
795 * Returns the number of bytes written on success, -1 on failure.
797 * The encrypted data consists of:
798 * - The source data, padded and encrypted with the public key, if the
799 * padded source data is no longer than the public key, and <b>force</b>
800 * is false, OR
801 * - The beginning of the source data prefixed with a 16-byte symmetric key,
802 * padded and encrypted with the public key; followed by the rest of
803 * the source data encrypted in AES-CTR mode with the symmetric key.
806 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
807 char *to,
808 const char *from,
809 size_t fromlen,
810 int padding, int force)
812 int overhead, outlen, r, symlen;
813 size_t pkeylen;
814 crypto_cipher_env_t *cipher = NULL;
815 char buf[PK_BYTES+1];
817 tor_assert(env);
818 tor_assert(from);
819 tor_assert(to);
821 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
822 pkeylen = crypto_pk_keysize(env);
824 if (padding == PK_NO_PADDING && fromlen < pkeylen)
825 return -1;
827 if (!force && fromlen+overhead <= pkeylen) {
828 /* It all fits in a single encrypt. */
829 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
831 cipher = crypto_new_cipher_env();
832 if (!cipher) return -1;
833 if (crypto_cipher_generate_key(cipher)<0)
834 goto err;
835 /* You can't just run around RSA-encrypting any bitstream: if it's
836 * greater than the RSA key, then OpenSSL will happily encrypt, and
837 * later decrypt to the wrong value. So we set the first bit of
838 * 'cipher->key' to 0 if we aren't padding. This means that our
839 * symmetric key is really only 127 bits.
841 if (padding == PK_NO_PADDING)
842 cipher->key[0] &= 0x7f;
843 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
844 goto err;
845 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
846 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
848 /* Length of symmetrically encrypted data. */
849 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
851 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
852 if (outlen!=(int)pkeylen) {
853 goto err;
855 r = crypto_cipher_encrypt(cipher, to+outlen,
856 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
858 if (r<0) goto err;
859 memset(buf, 0, sizeof(buf));
860 crypto_free_cipher_env(cipher);
861 return outlen + symlen;
862 err:
863 memset(buf, 0, sizeof(buf));
864 if (cipher) crypto_free_cipher_env(cipher);
865 return -1;
868 /** Invert crypto_pk_public_hybrid_encrypt. */
870 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
871 char *to,
872 const char *from,
873 size_t fromlen,
874 int padding, int warnOnFailure)
876 int outlen, r;
877 size_t pkeylen;
878 crypto_cipher_env_t *cipher = NULL;
879 char buf[PK_BYTES+1];
881 pkeylen = crypto_pk_keysize(env);
883 if (fromlen <= pkeylen) {
884 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
885 warnOnFailure);
887 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
888 warnOnFailure);
889 if (outlen<0) {
890 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
891 "Error decrypting public-key data");
892 return -1;
894 if (outlen < CIPHER_KEY_LEN) {
895 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
896 "No room for a symmetric key");
897 return -1;
899 cipher = crypto_create_init_cipher(buf, 0);
900 if (!cipher) {
901 return -1;
903 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
904 outlen -= CIPHER_KEY_LEN;
905 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
906 if (r<0)
907 goto err;
908 memset(buf,0,sizeof(buf));
909 crypto_free_cipher_env(cipher);
910 return outlen + (fromlen-pkeylen);
911 err:
912 memset(buf,0,sizeof(buf));
913 if (cipher) crypto_free_cipher_env(cipher);
914 return -1;
917 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
918 * Return -1 on error, or the number of characters used on success.
921 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
923 int len;
924 unsigned char *buf, *cp;
925 len = i2d_RSAPublicKey(pk->key, NULL);
926 if (len < 0 || len > dest_len)
927 return -1;
928 cp = buf = tor_malloc(len+1);
929 len = i2d_RSAPublicKey(pk->key, &cp);
930 if (len < 0) {
931 crypto_log_errors(LOG_WARN,"encoding public key");
932 tor_free(buf);
933 return -1;
935 /* We don't encode directly into 'dest', because that would be illegal
936 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
938 memcpy(dest,buf,len);
939 tor_free(buf);
940 return len;
943 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
944 * success and NULL on failure.
946 crypto_pk_env_t *
947 crypto_pk_asn1_decode(const char *str, size_t len)
949 RSA *rsa;
950 unsigned char *buf;
951 /* This ifdef suppresses a type warning. Take out the first case once
952 * everybody is using openssl 0.9.7 or later.
954 #if OPENSSL_VERSION_NUMBER < 0x00907000l
955 unsigned char *cp;
956 #else
957 const unsigned char *cp;
958 #endif
959 cp = buf = tor_malloc(len);
960 memcpy(buf,str,len);
961 rsa = d2i_RSAPublicKey(NULL, &cp, len);
962 tor_free(buf);
963 if (!rsa) {
964 crypto_log_errors(LOG_WARN,"decoding public key");
965 return NULL;
967 return _crypto_new_pk_env_rsa(rsa);
970 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
971 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
972 * Return 0 on success, -1 on failure.
975 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
977 unsigned char *buf, *bufp;
978 int len;
980 len = i2d_RSAPublicKey(pk->key, NULL);
981 if (len < 0)
982 return -1;
983 buf = bufp = tor_malloc(len+1);
984 len = i2d_RSAPublicKey(pk->key, &bufp);
985 if (len < 0) {
986 crypto_log_errors(LOG_WARN,"encoding public key");
987 tor_free(buf);
988 return -1;
990 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
991 tor_free(buf);
992 return -1;
994 tor_free(buf);
995 return 0;
998 /** Given a private or public key <b>pk</b>, put a fingerprint of the
999 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1000 * space). Return 0 on success, -1 on failure.
1002 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1003 * of the public key, converted to hexadecimal, in upper case, with a
1004 * space after every four digits.
1006 * If <b>add_space</b> is false, omit the spaces.
1009 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1011 char digest[DIGEST_LEN];
1012 char hexdigest[HEX_DIGEST_LEN+1];
1013 if (crypto_pk_get_digest(pk, digest)) {
1014 return -1;
1016 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1017 if (add_space) {
1018 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4)<0)
1019 return -1;
1020 } else {
1021 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1023 return 0;
1026 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1029 crypto_pk_check_fingerprint_syntax(const char *s)
1031 int i;
1032 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1033 if ((i%5) == 4) {
1034 if (!TOR_ISSPACE(s[i])) return 0;
1035 } else {
1036 if (!TOR_ISXDIGIT(s[i])) return 0;
1039 if (s[FINGERPRINT_LEN]) return 0;
1040 return 1;
1043 /* symmetric crypto */
1045 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1046 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1049 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1051 tor_assert(env);
1053 return crypto_rand(env->key, CIPHER_KEY_LEN);
1056 /** Set the symmetric key for the cipher in <b>env</b> to the first
1057 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1058 * Return 0 on success, -1 on failure.
1061 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1063 tor_assert(env);
1064 tor_assert(key);
1066 if (!env->key)
1067 return -1;
1069 memcpy(env->key, key, CIPHER_KEY_LEN);
1071 return 0;
1074 /** Return a pointer to the key set for the cipher in <b>env</b>.
1076 const char *
1077 crypto_cipher_get_key(crypto_cipher_env_t *env)
1079 return env->key;
1082 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1083 * success, -1 on failure.
1086 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1088 tor_assert(env);
1090 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1091 return 0;
1094 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1095 * success, -1 on failure.
1098 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1100 tor_assert(env);
1102 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1103 return 0;
1106 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1107 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1108 * On failure, return -1.
1111 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1112 const char *from, size_t fromlen)
1114 tor_assert(env);
1115 tor_assert(env->cipher);
1116 tor_assert(from);
1117 tor_assert(fromlen);
1118 tor_assert(to);
1120 aes_crypt(env->cipher, from, fromlen, to);
1121 return 0;
1124 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1125 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1126 * On failure, return -1.
1129 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1130 const char *from, size_t fromlen)
1132 tor_assert(env);
1133 tor_assert(from);
1134 tor_assert(to);
1136 aes_crypt(env->cipher, from, fromlen, to);
1137 return 0;
1140 /* SHA-1 */
1142 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1143 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1144 * Return 0 on success, -1 on failure.
1147 crypto_digest(char *digest, const char *m, size_t len)
1149 tor_assert(m);
1150 tor_assert(digest);
1151 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1154 /** Intermediate information about the digest of a stream of data. */
1155 struct crypto_digest_env_t {
1156 SHA_CTX d;
1159 /** Allocate and return a new digest object.
1161 crypto_digest_env_t *
1162 crypto_new_digest_env(void)
1164 crypto_digest_env_t *r;
1165 r = tor_malloc(sizeof(crypto_digest_env_t));
1166 SHA1_Init(&r->d);
1167 return r;
1170 /** Deallocate a digest object.
1172 void
1173 crypto_free_digest_env(crypto_digest_env_t *digest)
1175 tor_free(digest);
1178 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1180 void
1181 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1182 size_t len)
1184 tor_assert(digest);
1185 tor_assert(data);
1186 /* Using the SHA1_*() calls directly means we don't support doing
1187 * sha1 in hardware. But so far the delay of getting the question
1188 * to the hardware, and hearing the answer, is likely higher than
1189 * just doing it ourselves. Hashes are fast.
1191 SHA1_Update(&digest->d, (void*)data, len);
1194 /** Compute the hash of the data that has been passed to the digest
1195 * object; write the first out_len bytes of the result to <b>out</b>.
1196 * <b>out_len</b> must be \<= DIGEST_LEN.
1198 void
1199 crypto_digest_get_digest(crypto_digest_env_t *digest,
1200 char *out, size_t out_len)
1202 static unsigned char r[DIGEST_LEN];
1203 SHA_CTX tmpctx;
1204 tor_assert(digest);
1205 tor_assert(out);
1206 tor_assert(out_len <= DIGEST_LEN);
1207 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1208 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1209 SHA1_Final(r, &tmpctx);
1210 memcpy(out, r, out_len);
1213 /** Allocate and return a new digest object with the same state as
1214 * <b>digest</b>
1216 crypto_digest_env_t *
1217 crypto_digest_dup(const crypto_digest_env_t *digest)
1219 crypto_digest_env_t *r;
1220 tor_assert(digest);
1221 r = tor_malloc(sizeof(crypto_digest_env_t));
1222 memcpy(r,digest,sizeof(crypto_digest_env_t));
1223 return r;
1226 /** Replace the state of the digest object <b>into</b> with the state
1227 * of the digest object <b>from</b>.
1229 void
1230 crypto_digest_assign(crypto_digest_env_t *into,
1231 const crypto_digest_env_t *from)
1233 tor_assert(into);
1234 tor_assert(from);
1235 memcpy(into,from,sizeof(crypto_digest_env_t));
1238 /* DH */
1240 /** Shared P parameter for our DH key exchanged. */
1241 static BIGNUM *dh_param_p = NULL;
1242 /** Shared G parameter for our DH key exchanges. */
1243 static BIGNUM *dh_param_g = NULL;
1245 /** Initialize dh_param_p and dh_param_g if they are not already
1246 * set. */
1247 static void
1248 init_dh_param(void)
1250 BIGNUM *p, *g;
1251 int r;
1252 if (dh_param_p && dh_param_g)
1253 return;
1255 p = BN_new();
1256 g = BN_new();
1257 tor_assert(p);
1258 tor_assert(g);
1260 /* This is from rfc2409, section 6.2. It's a safe prime, and
1261 supposedly it equals:
1262 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1264 r = BN_hex2bn(&p,
1265 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1266 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1267 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1268 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1269 "49286651ECE65381FFFFFFFFFFFFFFFF");
1270 tor_assert(r);
1272 r = BN_set_word(g, 2);
1273 tor_assert(r);
1274 dh_param_p = p;
1275 dh_param_g = g;
1278 #define DH_PRIVATE_KEY_BITS 320
1280 /** Allocate and return a new DH object for a key exchange.
1282 crypto_dh_env_t *
1283 crypto_dh_new(void)
1285 crypto_dh_env_t *res = NULL;
1287 if (!dh_param_p)
1288 init_dh_param();
1290 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1292 if (!(res->dh = DH_new()))
1293 goto err;
1295 if (!(res->dh->p = BN_dup(dh_param_p)))
1296 goto err;
1298 if (!(res->dh->g = BN_dup(dh_param_g)))
1299 goto err;
1301 res->dh->length = DH_PRIVATE_KEY_BITS;
1303 return res;
1304 err:
1305 crypto_log_errors(LOG_WARN, "creating DH object");
1306 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1307 if (res) tor_free(res);
1308 return NULL;
1311 /** Return the length of the DH key in <b>dh</b>, in bytes.
1314 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1316 tor_assert(dh);
1317 return DH_size(dh->dh);
1320 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1321 * success, -1 on failure.
1324 crypto_dh_generate_public(crypto_dh_env_t *dh)
1326 again:
1327 if (!DH_generate_key(dh->dh)) {
1328 crypto_log_errors(LOG_WARN, "generating DH key");
1329 return -1;
1331 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1332 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1333 "the-universe chances really do happen. Trying again.");
1334 /* Free and clear the keys, so openssl will actually try again. */
1335 BN_free(dh->dh->pub_key);
1336 BN_free(dh->dh->priv_key);
1337 dh->dh->pub_key = dh->dh->priv_key = NULL;
1338 goto again;
1340 return 0;
1343 /** Generate g^x as necessary, and write the g^x for the key exchange
1344 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1345 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1348 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1350 int bytes;
1351 tor_assert(dh);
1352 if (!dh->dh->pub_key) {
1353 if (crypto_dh_generate_public(dh)<0)
1354 return -1;
1357 tor_assert(dh->dh->pub_key);
1358 bytes = BN_num_bytes(dh->dh->pub_key);
1359 tor_assert(bytes >= 0);
1360 if (pubkey_len < (size_t)bytes) {
1361 log_warn(LD_CRYPTO,
1362 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1363 (int) pubkey_len, bytes);
1364 return -1;
1367 memset(pubkey, 0, pubkey_len);
1368 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1370 return 0;
1373 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1374 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
1375 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1377 static int
1378 tor_check_dh_key(BIGNUM *bn)
1380 BIGNUM *x;
1381 char *s;
1382 tor_assert(bn);
1383 x = BN_new();
1384 tor_assert(x);
1385 if (!dh_param_p)
1386 init_dh_param();
1387 BN_set_word(x, 1);
1388 if (BN_cmp(bn,x)<=0) {
1389 log_warn(LD_CRYPTO, "DH key must be at least 2.");
1390 goto err;
1392 BN_copy(x,dh_param_p);
1393 BN_sub_word(x, 1);
1394 if (BN_cmp(bn,x)>=0) {
1395 log_warn(LD_CRYPTO, "DH key must be at most p-2.");
1396 goto err;
1398 BN_free(x);
1399 return 0;
1400 err:
1401 BN_free(x);
1402 s = BN_bn2hex(bn);
1403 log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1404 OPENSSL_free(s);
1405 return -1;
1408 #undef MIN
1409 #define MIN(a,b) ((a)<(b)?(a):(b))
1410 /** Given a DH key exchange object, and our peer's value of g^y (as a
1411 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1412 * <b>secret_bytes_out</b> bytes of shared key material and write them
1413 * to <b>secret_out</b>. Return the number of bytes generated on success,
1414 * or -1 on failure.
1416 * (We generate key material by computing
1417 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1418 * where || is concatenation.)
1421 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1422 const char *pubkey, size_t pubkey_len,
1423 char *secret_out, size_t secret_bytes_out)
1425 char *secret_tmp = NULL;
1426 BIGNUM *pubkey_bn = NULL;
1427 size_t secret_len=0;
1428 int result=0;
1429 tor_assert(dh);
1430 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1432 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
1433 goto error;
1434 if (tor_check_dh_key(pubkey_bn)<0) {
1435 /* Check for invalid public keys. */
1436 log_warn(LD_CRYPTO,"Rejected invalid g^x");
1437 goto error;
1439 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1440 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1441 if (result < 0) {
1442 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
1443 goto error;
1445 secret_len = result;
1446 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1447 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1448 * Leading zeros MUST be preserved, so that ZZ occupies as many
1449 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1450 * bytes long.
1451 * What are the security implications here?
1453 if (crypto_expand_key_material(secret_tmp, secret_len,
1454 secret_out, secret_bytes_out)<0)
1455 goto error;
1456 secret_len = secret_bytes_out;
1458 goto done;
1459 error:
1460 result = -1;
1461 done:
1462 crypto_log_errors(LOG_WARN, "completing DH handshake");
1463 if (pubkey_bn)
1464 BN_free(pubkey_bn);
1465 tor_free(secret_tmp);
1466 if (result < 0)
1467 return result;
1468 else
1469 return secret_len;
1472 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1473 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1474 * <b>key_out</b> by taking the first key_out_len bytes of
1475 * H(K | [00]) | H(K | [01]) | ....
1477 * Return 0 on success, -1 on failure.
1480 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1481 char *key_out, size_t key_out_len)
1483 int i;
1484 char *cp, *tmp = tor_malloc(key_in_len+1);
1485 char digest[DIGEST_LEN];
1487 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1488 tor_assert(key_out_len <= DIGEST_LEN*256);
1490 memcpy(tmp, key_in, key_in_len);
1491 for (cp = key_out, i=0; key_out_len; ++i, cp += DIGEST_LEN) {
1492 tmp[key_in_len] = i;
1493 if (crypto_digest(digest, tmp, key_in_len+1))
1494 goto err;
1495 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len));
1496 if (key_out_len < DIGEST_LEN)
1497 break;
1498 key_out_len -= DIGEST_LEN;
1500 memset(tmp, 0, key_in_len+1);
1501 tor_free(tmp);
1502 return 0;
1504 err:
1505 memset(tmp, 0, key_in_len+1);
1506 tor_free(tmp);
1507 return -1;
1510 /** Free a DH key exchange object.
1512 void
1513 crypto_dh_free(crypto_dh_env_t *dh)
1515 tor_assert(dh);
1516 tor_assert(dh->dh);
1517 DH_free(dh->dh);
1518 tor_free(dh);
1521 /* random numbers */
1523 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1524 * work for us too. */
1525 #define ADD_ENTROPY 32
1527 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1528 "release".) */
1529 //#define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1530 #define USE_RAND_POLL 0
1531 /* XXX Somehow setting USE_RAND_POLL on causes stack smashes. We're
1532 * not sure where. This was the big bug with Tor 0.1.1.9-alpha. */
1534 /** Seed OpenSSL's random number generator with bytes from the
1535 * operating system. Return 0 on success, -1 on failure.
1538 crypto_seed_rng(void)
1540 char buf[ADD_ENTROPY];
1541 int rand_poll_status;
1543 /* local variables */
1544 #ifdef MS_WINDOWS
1545 static int provider_set = 0;
1546 static HCRYPTPROV provider;
1547 #else
1548 static const char *filenames[] = {
1549 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1551 int fd;
1552 int i, n;
1553 #endif
1555 #if USE_RAND_POLL
1556 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1557 * entropy than we do. We'll try calling that, *and* calling our own entropy
1558 * functions. If one succeeds, we'll accept the RNG as seeded. */
1559 rand_poll_status = RAND_poll();
1560 if (rand_poll_status == 0)
1561 log_warn(LD_CRYPTO, "RAND_poll() failed.");
1562 #else
1563 rand_poll_status = 0;
1564 #endif
1566 #ifdef MS_WINDOWS
1567 if (!provider_set) {
1568 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1569 CRYPT_VERIFYCONTEXT)) {
1570 if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
1571 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1572 return rand_poll_status ? 0 : -1;
1575 provider_set = 1;
1577 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1578 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1579 return rand_poll_status ? 0 : -1;
1581 RAND_seed(buf, sizeof(buf));
1582 return 0;
1583 #else
1584 for (i = 0; filenames[i]; ++i) {
1585 fd = open(filenames[i], O_RDONLY, 0);
1586 if (fd<0) continue;
1587 log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1588 n = read_all(fd, buf, sizeof(buf), 0);
1589 close(fd);
1590 if (n != sizeof(buf)) {
1591 log_warn(LD_CRYPTO,
1592 "Error reading from entropy source (read only %d bytes).", n);
1593 return -1;
1595 RAND_seed(buf, sizeof(buf));
1596 return 0;
1599 log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1600 return rand_poll_status ? 0 : -1;
1601 #endif
1604 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1605 * success, -1 on failure.
1608 crypto_rand(char *to, size_t n)
1610 int r;
1611 tor_assert(to);
1612 r = RAND_bytes((unsigned char*)to, n);
1613 if (r == 0)
1614 crypto_log_errors(LOG_WARN, "generating random data");
1615 return (r == 1) ? 0 : -1;
1618 /** Return a pseudorandom integer, chosen uniformly from the values
1619 * between 0 and max-1. */
1621 crypto_rand_int(unsigned int max)
1623 unsigned int val;
1624 unsigned int cutoff;
1625 tor_assert(max < UINT_MAX);
1626 tor_assert(max > 0); /* don't div by 0 */
1628 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1629 * distribution with clipping at the upper end of unsigned int's
1630 * range.
1632 cutoff = UINT_MAX - (UINT_MAX%max);
1633 while (1) {
1634 crypto_rand((char*)&val, sizeof(val));
1635 if (val < cutoff)
1636 return val % max;
1640 /** Return a pseudorandom integer, chosen uniformly from the values
1641 * between 0 and max-1. */
1642 uint64_t
1643 crypto_rand_uint64(uint64_t max)
1645 uint64_t val;
1646 uint64_t cutoff;
1647 tor_assert(max < UINT64_MAX);
1648 tor_assert(max > 0); /* don't div by 0 */
1650 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1651 * distribution with clipping at the upper end of unsigned int's
1652 * range.
1654 cutoff = UINT64_MAX - (UINT64_MAX%max);
1655 while (1) {
1656 crypto_rand((char*)&val, sizeof(val));
1657 if (val < cutoff)
1658 return val % max;
1662 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1664 void *
1665 smartlist_choose(const smartlist_t *sl)
1667 size_t len;
1668 len = smartlist_len(sl);
1669 if (len)
1670 return smartlist_get(sl,crypto_rand_int(len));
1671 return NULL; /* no elements to choose from */
1674 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1675 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1676 * bytes. Return the number of bytes written on success; -1 if
1677 * destlen is too short, or other failure.
1680 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1682 EVP_ENCODE_CTX ctx;
1683 int len, ret;
1685 /* 48 bytes of input -> 64 bytes of output plus newline.
1686 Plus one more byte, in case I'm wrong.
1688 if (destlen < ((srclen/48)+1)*66)
1689 return -1;
1690 if (destlen > SIZE_T_CEILING)
1691 return -1;
1693 EVP_EncodeInit(&ctx);
1694 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
1695 (unsigned char*)src, srclen);
1696 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1697 ret += len;
1698 return ret;
1701 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1702 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1703 * bytes. Return the number of bytes written on success; -1 if
1704 * destlen is too short, or other failure.
1706 * NOTE: destlen should be a little longer than the amount of data it
1707 * will contain, since we check for sufficient space conservatively.
1708 * Here, "a little" is around 64-ish bytes.
1711 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1713 EVP_ENCODE_CTX ctx;
1714 int len, ret;
1715 /* 64 bytes of input -> *up to* 48 bytes of output.
1716 Plus one more byte, in case I'm wrong.
1718 if (destlen < ((srclen/64)+1)*49)
1719 return -1;
1720 if (destlen > SIZE_T_CEILING)
1721 return -1;
1723 EVP_DecodeInit(&ctx);
1724 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
1725 (unsigned char*)src, srclen);
1726 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
1727 ret += len;
1728 return ret;
1731 /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
1732 * and newline characters, and store the nul-terminated result in the first
1733 * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
1735 digest_to_base64(char *d64, const char *digest)
1737 char buf[256];
1738 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
1739 buf[BASE64_DIGEST_LEN] = '\0';
1740 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
1741 return 0;
1744 /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
1745 * trailing newline or = characters), decode it and store the result in the
1746 * first DIGEST_LEN bytes at <b>digest</b>. */
1748 digest_from_base64(char *digest, const char *d64)
1750 char buf_in[BASE64_DIGEST_LEN+3];
1751 char buf[256];
1752 if (strlen(d64) != BASE64_DIGEST_LEN)
1753 return -1;
1754 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
1755 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
1756 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
1757 return -1;
1758 memcpy(digest, buf, DIGEST_LEN);
1759 return 0;
1762 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1763 * that srclen*8 is a multiple of 5.
1765 void
1766 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1768 unsigned int nbits, i, bit, v, u;
1769 nbits = srclen * 8;
1771 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1772 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1773 tor_assert(destlen < SIZE_T_CEILING);
1775 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1776 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1777 v = ((uint8_t)src[bit/8]) << 8;
1778 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1779 /* set u to the 5-bit value at the bit'th bit of src. */
1780 u = (v >> (11-(bit%8))) & 0x1F;
1781 dest[i] = BASE32_CHARS[u];
1783 dest[i] = '\0';
1786 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1787 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1788 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1789 * are a salt; the 9th byte describes how much iteration to do.
1790 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1792 void
1793 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1794 size_t secret_len, const char *s2k_specifier)
1796 crypto_digest_env_t *d;
1797 uint8_t c;
1798 size_t count;
1799 char *tmp;
1800 tor_assert(key_out_len < SIZE_T_CEILING);
1802 #define EXPBIAS 6
1803 c = s2k_specifier[8];
1804 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1805 #undef EXPBIAS
1807 tor_assert(key_out_len <= DIGEST_LEN);
1809 d = crypto_new_digest_env();
1810 tmp = tor_malloc(8+secret_len);
1811 memcpy(tmp,s2k_specifier,8);
1812 memcpy(tmp+8,secret,secret_len);
1813 secret_len += 8;
1814 while (count) {
1815 if (count >= secret_len) {
1816 crypto_digest_add_bytes(d, tmp, secret_len);
1817 count -= secret_len;
1818 } else {
1819 crypto_digest_add_bytes(d, tmp, count);
1820 count = 0;
1823 crypto_digest_get_digest(d, key_out, key_out_len);
1824 tor_free(tmp);
1825 crypto_free_digest_env(d);
1828 #ifdef TOR_IS_MULTITHREADED
1829 /** Helper: openssl uses this callback to manipulate mutexes. */
1830 static void
1831 _openssl_locking_cb(int mode, int n, const char *file, int line)
1833 (void)file;
1834 (void)line;
1835 if (!_openssl_mutexes)
1836 /* This is not a really good fix for the
1837 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1838 * it can't hurt. */
1839 return;
1840 if (mode & CRYPTO_LOCK)
1841 tor_mutex_acquire(_openssl_mutexes[n]);
1842 else
1843 tor_mutex_release(_openssl_mutexes[n]);
1846 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
1847 * multithreaded. */
1848 static int
1849 setup_openssl_threading(void)
1851 int i;
1852 int n = CRYPTO_num_locks();
1853 _n_openssl_mutexes = n;
1854 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
1855 for (i=0; i < n; ++i)
1856 _openssl_mutexes[i] = tor_mutex_new();
1857 CRYPTO_set_locking_callback(_openssl_locking_cb);
1858 CRYPTO_set_id_callback(tor_get_thread_id);
1859 return 0;
1861 #else
1862 static int
1863 setup_openssl_threading(void)
1865 return 0;
1867 #endif