Call ERR_remove_state() on the main thread on shutdown,too
[tor.git] / src / common / crypto.c
blob10b74b82ece946132b3eb7902fef5882839660a2
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar.
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char crypto_c_id[] = "$Id$";
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 #endif
23 #include <string.h>
25 #include <openssl/err.h>
26 #include <openssl/rsa.h>
27 #include <openssl/pem.h>
28 #include <openssl/evp.h>
29 #include <openssl/rand.h>
30 #include <openssl/opensslv.h>
31 #include <openssl/bn.h>
32 #include <openssl/dh.h>
33 #include <openssl/rsa.h>
34 #include <openssl/dh.h>
35 #include <openssl/conf.h>
37 #include <stdlib.h>
38 #include <assert.h>
39 #include <stdio.h>
40 #include <limits.h>
42 #ifdef HAVE_CTYPE_H
43 #include <ctype.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef HAVE_SYS_FCNTL_H
52 #include <sys/fcntl.h>
53 #endif
55 #include "crypto.h"
56 #include "log.h"
57 #include "aes.h"
58 #include "util.h"
59 #include "container.h"
60 #include "compat.h"
62 #if OPENSSL_VERSION_NUMBER < 0x00905000l
63 #error "We require openssl >= 0.9.5"
64 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
65 #define OPENSSL_095
66 #endif
68 #if OPENSSL_VERSION_NUMBER < 0x00907000l
69 #define NO_ENGINES
70 #else
71 #include <openssl/engine.h>
72 #endif
74 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
75 * (and don't indicate errors) in OpenSSL version 0.9.5.
77 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
79 #ifdef OPENSSL_095
80 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
81 #else
82 #define RETURN_SSL_OUTCOME(exp) return !(exp)
83 #endif
85 /** Macro: is k a valid RSA public or private key? */
86 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
87 /** Macro: is k a valid RSA private key? */
88 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
90 #ifdef TOR_IS_MULTITHREADED
91 static tor_mutex_t **_openssl_mutexes = NULL;
92 static int _n_openssl_mutexes = -1;
93 #endif
95 /** A public key, or a public/private keypair. */
96 struct crypto_pk_env_t
98 int refs; /* reference counting so we don't have to copy keys */
99 RSA *key;
102 /** Key and stream information for a stream cipher. */
103 struct crypto_cipher_env_t
105 char key[CIPHER_KEY_LEN];
106 aes_cnt_cipher_t *cipher;
109 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
110 * while we're waiting for the second.*/
111 struct crypto_dh_env_t {
112 DH *dh;
115 /* Prototypes for functions only used by tortls.c */
116 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
117 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
118 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
119 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
121 static int setup_openssl_threading(void);
122 static int tor_check_dh_key(BIGNUM *bn);
124 /** Return the number of bytes added by padding method <b>padding</b>.
126 static INLINE int
127 crypto_get_rsa_padding_overhead(int padding)
129 switch (padding)
131 case RSA_NO_PADDING: return 0;
132 case RSA_PKCS1_OAEP_PADDING: return 42;
133 case RSA_PKCS1_PADDING: return 11;
134 default: tor_assert(0); return -1;
138 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
140 static INLINE int
141 crypto_get_rsa_padding(int padding)
143 switch (padding)
145 case PK_NO_PADDING: return RSA_NO_PADDING;
146 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
147 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
148 default: tor_assert(0); return -1;
152 /** Boolean: has OpenSSL's crypto been initialized? */
153 static int _crypto_global_initialized = 0;
155 /** Log all pending crypto errors at level <b>severity</b>. Use
156 * <b>doing</b> to describe our current activities.
158 static void
159 crypto_log_errors(int severity, const char *doing)
161 unsigned int err;
162 const char *msg, *lib, *func;
163 while ((err = ERR_get_error()) != 0) {
164 msg = (const char*)ERR_reason_error_string(err);
165 lib = (const char*)ERR_lib_error_string(err);
166 func = (const char*)ERR_func_error_string(err);
167 if (!msg) msg = "(null)";
168 if (doing) {
169 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)", doing, msg, lib, func);
170 } else {
171 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
176 #ifndef NO_ENGINES
177 static void
178 log_engine(const char *fn, ENGINE *e)
180 if (e) {
181 const char *name, *id;
182 name = ENGINE_get_name(e);
183 id = ENGINE_get_id(e);
184 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
185 name?name:"?", id?id:"?", fn);
186 } else {
187 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
190 #endif
192 /** Initialize the crypto library. Return 0 on success, -1 on failure.
195 crypto_global_init(int useAccel)
197 if (!_crypto_global_initialized) {
198 ERR_load_crypto_strings();
199 OpenSSL_add_all_algorithms();
200 _crypto_global_initialized = 1;
201 setup_openssl_threading();
202 #ifndef NO_ENGINES
203 if (useAccel) {
204 if (useAccel < 0)
205 warn(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
206 info(LD_CRYPTO, "Initializing OpenSSL engine support.");
207 ENGINE_load_builtin_engines();
208 if (!ENGINE_register_all_complete())
209 return -1;
211 /* XXXX make sure this isn't leaking. */
212 log_engine("RSA", ENGINE_get_default_RSA());
213 log_engine("DH", ENGINE_get_default_DH());
214 log_engine("RAND", ENGINE_get_default_RAND());
215 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
216 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
217 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
219 #endif
221 return 0;
224 /** Free crypto resources held by this thread. */
225 void
226 crypto_thread_cleanup(void)
228 ERR_remove_state(0);
231 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
234 crypto_global_cleanup(void)
236 EVP_cleanup();
237 ERR_remove_state(0);
238 ERR_free_strings();
239 #ifndef NO_ENGINES
240 ENGINE_cleanup();
241 #endif
242 CONF_modules_unload(1);
243 CRYPTO_cleanup_all_ex_data();
244 #ifdef TOR_IS_MULTITHREADED
245 if (_n_openssl_mutexes) {
246 int n = _n_openssl_mutexes;
247 tor_mutex_t **ms = _openssl_mutexes;
248 int i;
249 _openssl_mutexes = NULL;
250 _n_openssl_mutexes = 0;
251 for (i=0;i<n;++i) {
252 tor_mutex_free(ms[i]);
254 tor_free(ms);
256 #endif
257 return 0;
260 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
261 crypto_pk_env_t *
262 _crypto_new_pk_env_rsa(RSA *rsa)
264 crypto_pk_env_t *env;
265 tor_assert(rsa);
266 env = tor_malloc(sizeof(crypto_pk_env_t));
267 env->refs = 1;
268 env->key = rsa;
269 return env;
272 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
273 RSA *
274 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
276 return env->key;
279 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
280 * private is set, include the private-key portion of the key. */
281 EVP_PKEY *
282 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
284 RSA *key = NULL;
285 EVP_PKEY *pkey = NULL;
286 tor_assert(env->key);
287 if (private) {
288 if (!(key = RSAPrivateKey_dup(env->key)))
289 goto error;
290 } else {
291 if (!(key = RSAPublicKey_dup(env->key)))
292 goto error;
294 if (!(pkey = EVP_PKEY_new()))
295 goto error;
296 if (!(EVP_PKEY_assign_RSA(pkey, key)))
297 goto error;
298 return pkey;
299 error:
300 if (pkey)
301 EVP_PKEY_free(pkey);
302 if (key)
303 RSA_free(key);
304 return NULL;
307 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
309 DH *
310 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
312 return dh->dh;
315 /** Allocate and return storage for a public key. The key itself will not yet
316 * be set.
318 crypto_pk_env_t *
319 crypto_new_pk_env(void)
321 RSA *rsa;
323 rsa = RSA_new();
324 if (!rsa) return NULL;
325 return _crypto_new_pk_env_rsa(rsa);
328 /** Release a reference to an asymmetric key; when all the references
329 * are released, free the key.
331 void
332 crypto_free_pk_env(crypto_pk_env_t *env)
334 tor_assert(env);
336 if (--env->refs > 0)
337 return;
339 if (env->key)
340 RSA_free(env->key);
342 tor_free(env);
345 /** Create a new symmetric cipher for a given key and encryption flag
346 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
347 * on failure.
349 crypto_cipher_env_t *
350 crypto_create_init_cipher(const char *key, int encrypt_mode)
352 int r;
353 crypto_cipher_env_t *crypto = NULL;
355 if (! (crypto = crypto_new_cipher_env())) {
356 warn(LD_CRYPTO, "Unable to allocate crypto object");
357 return NULL;
360 if (crypto_cipher_set_key(crypto, key)) {
361 crypto_log_errors(LOG_WARN, "setting symmetric key");
362 goto error;
365 if (encrypt_mode)
366 r = crypto_cipher_encrypt_init_cipher(crypto);
367 else
368 r = crypto_cipher_decrypt_init_cipher(crypto);
370 if (r)
371 goto error;
372 return crypto;
374 error:
375 if (crypto)
376 crypto_free_cipher_env(crypto);
377 return NULL;
380 /** Allocate and return a new symmetric cipher.
382 crypto_cipher_env_t *
383 crypto_new_cipher_env(void)
385 crypto_cipher_env_t *env;
387 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
388 env->cipher = aes_new_cipher();
389 return env;
392 /** Free a symmetric cipher.
394 void
395 crypto_free_cipher_env(crypto_cipher_env_t *env)
397 tor_assert(env);
399 tor_assert(env->cipher);
400 aes_free_cipher(env->cipher);
401 tor_free(env);
404 /* public key crypto */
406 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
407 * success, -1 on failure.
410 crypto_pk_generate_key(crypto_pk_env_t *env)
412 tor_assert(env);
414 if (env->key)
415 RSA_free(env->key);
416 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
417 if (!env->key) {
418 crypto_log_errors(LOG_WARN, "generating RSA key");
419 return -1;
422 return 0;
425 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
426 * Return 0 on success, -1 on failure.
428 static int
429 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
430 const char *s)
432 BIO *b;
434 tor_assert(env);
435 tor_assert(s);
437 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
438 b = BIO_new_mem_buf((char*)s, -1);
440 if (env->key)
441 RSA_free(env->key);
443 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
445 BIO_free(b);
447 if (!env->key) {
448 crypto_log_errors(LOG_WARN, "Error parsing private key");
449 return -1;
451 return 0;
454 /** Read a PEM-encoded private key from the file named by
455 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
458 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
460 char *contents;
461 int r;
463 /* Read the file into a string. */
464 contents = read_file_to_str(keyfile, 0);
465 if (!contents) {
466 warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
467 return -1;
470 /* Try to parse it. */
471 r = crypto_pk_read_private_key_from_string(env, contents);
472 tor_free(contents);
473 if (r)
474 return -1; /* read_private_key_from_string already warned, so we don't.*/
476 /* Make sure it's valid. */
477 if (crypto_pk_check_key(env) <= 0)
478 return -1;
480 return 0;
483 /** PEM-encode the public key portion of <b>env</b> and write it to a
484 * newly allocated string. On success, set *<b>dest</b> to the new
485 * string, *<b>len</b> to the string's length, and return 0. On
486 * failure, return -1.
489 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, size_t *len)
491 BUF_MEM *buf;
492 BIO *b;
494 tor_assert(env);
495 tor_assert(env->key);
496 tor_assert(dest);
498 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
500 /* Now you can treat b as if it were a file. Just use the
501 * PEM_*_bio_* functions instead of the non-bio variants.
503 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
504 crypto_log_errors(LOG_WARN, "writing public key to string");
505 return -1;
508 BIO_get_mem_ptr(b, &buf);
509 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
510 BIO_free(b);
512 tor_assert(buf->length >= 0);
513 *dest = tor_malloc(buf->length+1);
514 memcpy(*dest, buf->data, buf->length);
515 (*dest)[buf->length] = 0; /* null terminate it */
516 *len = buf->length;
517 BUF_MEM_free(buf);
519 return 0;
522 /** Read a PEM-encoded public key from the first <b>len</b> characters of
523 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
524 * failure.
527 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, size_t len)
529 BIO *b;
531 tor_assert(env);
532 tor_assert(src);
534 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
536 BIO_write(b, src, len);
538 if (env->key)
539 RSA_free(env->key);
540 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
541 BIO_free(b);
542 if (!env->key) {
543 crypto_log_errors(LOG_WARN, "reading public key from string");
544 return -1;
547 return 0;
550 /* Write the private key from 'env' into the file named by 'fname',
551 * PEM-encoded. Return 0 on success, -1 on failure.
554 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
555 const char *fname)
557 BIO *bio;
558 char *cp;
559 long len;
560 char *s;
561 int r;
563 tor_assert(PRIVATE_KEY_OK(env));
565 if (!(bio = BIO_new(BIO_s_mem())))
566 return -1;
567 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
568 == 0) {
569 crypto_log_errors(LOG_WARN, "writing private key");
570 BIO_free(bio);
571 return -1;
573 len = BIO_get_mem_data(bio, &cp);
574 tor_assert(len >= 0);
575 s = tor_malloc(len+1);
576 memcpy(s, cp, len);
577 s[len]='\0';
578 r = write_str_to_file(fname, s, 0);
579 BIO_free(bio);
580 tor_free(s);
581 return r;
584 /** Allocate a new string in *<b>out</b>, containing the public portion of the
585 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
586 * length of the encoded representation on success, and -1 on failure.
588 * <i>This function is for temporary use only. We need a simple
589 * one-line representation for keys to work around a bug in parsing
590 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
591 * in versions of Tor up to 0.0.9pre2.</i>
594 crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
596 int len;
597 char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
598 tor_assert(env);
599 tor_assert(out);
600 len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
601 if (len < 0) {
602 return -1;
604 *out = tor_malloc(len * 2); /* too long, but safe. */
605 if (base64_encode(*out, len*2, buf, len) < 0) {
606 warn(LD_CRYPTO, "Error base64-encoding DER-encoded key");
607 tor_free(*out);
608 return -1;
610 /* Remove spaces */
611 tor_strstrip(*out, " \r\n\t");
612 return strlen(*out);
615 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
616 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
618 * <i>This function is for temporary use only. We need a simple
619 * one-line representation for keys to work around a bug in parsing
620 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
621 * in versions of Tor up to 0.0.9pre2.</i>
623 crypto_pk_env_t *
624 crypto_pk_DER64_decode_public_key(const char *in)
626 char partitioned[PK_BYTES*2 + 16];
627 char buf[PK_BYTES*2];
628 int len;
629 tor_assert(in);
630 len = strlen(in);
632 if (strlen(in) > PK_BYTES*2) {
633 return NULL;
635 /* base64_decode doesn't work unless we insert linebreaks every 64
636 * characters. how dumb. */
637 if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
638 ALWAYS_TERMINATE))
639 return NULL;
640 len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
641 if (len<0) {
642 warn(LD_CRYPTO,"Error base-64 decoding key");
643 return NULL;
645 return crypto_pk_asn1_decode(buf, len);
648 /** Return true iff <b>env</b> has a valid key.
651 crypto_pk_check_key(crypto_pk_env_t *env)
653 int r;
654 tor_assert(env);
656 r = RSA_check_key(env->key);
657 if (r <= 0)
658 crypto_log_errors(LOG_WARN,"checking RSA key");
659 return r;
662 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
663 * if a==b, and 1 if a\>b.
666 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
668 int result;
670 if (!a || !b)
671 return -1;
673 if (!a->key || !b->key)
674 return -1;
676 tor_assert(PUBLIC_KEY_OK(a));
677 tor_assert(PUBLIC_KEY_OK(b));
678 result = BN_cmp((a->key)->n, (b->key)->n);
679 if (result)
680 return result;
681 return BN_cmp((a->key)->e, (b->key)->e);
684 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
685 size_t
686 crypto_pk_keysize(crypto_pk_env_t *env)
688 tor_assert(env);
689 tor_assert(env->key);
691 return (size_t) RSA_size(env->key);
694 /** Increase the reference count of <b>env</b>, and return it.
696 crypto_pk_env_t *
697 crypto_pk_dup_key(crypto_pk_env_t *env)
699 tor_assert(env);
700 tor_assert(env->key);
702 env->refs++;
703 return env;
706 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
707 * in <b>env</b>, using the padding method <b>padding</b>. On success,
708 * write the result to <b>to</b>, and return the number of bytes
709 * written. On failure, return -1.
712 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
713 const char *from, size_t fromlen, int padding)
715 int r;
716 tor_assert(env);
717 tor_assert(from);
718 tor_assert(to);
720 r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
721 env->key, crypto_get_rsa_padding(padding));
722 if (r<0) {
723 crypto_log_errors(LOG_WARN, "performing RSA encryption");
724 return -1;
726 return r;
729 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
730 * in <b>env</b>, using the padding method <b>padding</b>. On success,
731 * write the result to <b>to</b>, and return the number of bytes
732 * written. On failure, return -1.
735 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
736 const char *from, size_t fromlen,
737 int padding, int warnOnFailure)
739 int r;
740 tor_assert(env);
741 tor_assert(from);
742 tor_assert(to);
743 tor_assert(env->key);
744 if (!env->key->p)
745 /* Not a private key */
746 return -1;
748 r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
749 env->key, crypto_get_rsa_padding(padding));
751 if (r<0) {
752 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
753 "performing RSA decryption");
754 return -1;
756 return r;
759 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
760 * public key in <b>env</b>, using PKCS1 padding. On success, write the
761 * signed data to <b>to</b>, and return the number of bytes written.
762 * On failure, return -1.
765 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
766 const char *from, size_t fromlen)
768 int r;
769 tor_assert(env);
770 tor_assert(from);
771 tor_assert(to);
772 r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to, env->key, RSA_PKCS1_PADDING);
774 if (r<0) {
775 crypto_log_errors(LOG_WARN, "checking RSA signature");
776 return -1;
778 return r;
781 /** Check a siglen-byte long signature at <b>sig</b> against
782 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
783 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
784 * SHA1(data). Else return -1.
787 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
788 int datalen, const char *sig, int siglen)
790 char digest[DIGEST_LEN];
791 char buf[PK_BYTES+1];
792 int r;
794 tor_assert(env);
795 tor_assert(data);
796 tor_assert(sig);
798 if (crypto_digest(digest,data,datalen)<0) {
799 warn(LD_CRYPTO, "couldn't compute digest");
800 return -1;
802 r = crypto_pk_public_checksig(env,buf,sig,siglen);
803 if (r != DIGEST_LEN) {
804 warn(LD_CRYPTO, "Invalid signature");
805 return -1;
807 if (memcmp(buf, digest, DIGEST_LEN)) {
808 warn(LD_CRYPTO, "Signature mismatched with digest.");
809 return -1;
812 return 0;
815 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
816 * <b>env</b>, using PKCS1 padding. On success, write the signature to
817 * <b>to</b>, and return the number of bytes written. On failure, return
818 * -1.
821 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
822 const char *from, size_t fromlen)
824 int r;
825 tor_assert(env);
826 tor_assert(from);
827 tor_assert(to);
828 if (!env->key->p)
829 /* Not a private key */
830 return -1;
832 r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to, env->key, RSA_PKCS1_PADDING);
833 if (r<0) {
834 crypto_log_errors(LOG_WARN, "generating RSA signature");
835 return -1;
837 return r;
840 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
841 * <b>from</b>; sign the data with the private key in <b>env</b>, and
842 * store it in <b>to</b>. Return the number of bytes written on
843 * success, and -1 on failure.
846 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
847 const char *from, size_t fromlen)
849 char digest[DIGEST_LEN];
850 if (crypto_digest(digest,from,fromlen)<0)
851 return -1;
852 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
855 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
856 * bytes of data from <b>from</b>, with padding type 'padding',
857 * storing the results on <b>to</b>.
859 * If no padding is used, the public key must be at least as large as
860 * <b>from</b>.
862 * Returns the number of bytes written on success, -1 on failure.
864 * The encrypted data consists of:
865 * - The source data, padded and encrypted with the public key, if the
866 * padded source data is no longer than the public key, and <b>force</b>
867 * is false, OR
868 * - The beginning of the source data prefixed with a 16-byte symmetric key,
869 * padded and encrypted with the public key; followed by the rest of
870 * the source data encrypted in AES-CTR mode with the symmetric key.
873 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
874 char *to,
875 const char *from,
876 size_t fromlen,
877 int padding, int force)
879 int overhead, outlen, r, symlen;
880 size_t pkeylen;
881 crypto_cipher_env_t *cipher = NULL;
882 char buf[PK_BYTES+1];
884 tor_assert(env);
885 tor_assert(from);
886 tor_assert(to);
888 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
889 pkeylen = crypto_pk_keysize(env);
891 if (padding == PK_NO_PADDING && fromlen < pkeylen)
892 return -1;
894 if (!force && fromlen+overhead <= pkeylen) {
895 /* It all fits in a single encrypt. */
896 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
898 cipher = crypto_new_cipher_env();
899 if (!cipher) return -1;
900 if (crypto_cipher_generate_key(cipher)<0)
901 goto err;
902 /* You can't just run around RSA-encrypting any bitstream: if it's
903 * greater than the RSA key, then OpenSSL will happily encrypt, and
904 * later decrypt to the wrong value. So we set the first bit of
905 * 'cipher->key' to 0 if we aren't padding. This means that our
906 * symmetric key is really only 127 bits.
908 if (padding == PK_NO_PADDING)
909 cipher->key[0] &= 0x7f;
910 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
911 goto err;
912 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
913 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
915 /* Length of symmetrically encrypted data. */
916 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
918 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
919 if (outlen!=(int)pkeylen) {
920 goto err;
922 r = crypto_cipher_encrypt(cipher, to+outlen,
923 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
925 if (r<0) goto err;
926 memset(buf, 0, sizeof(buf));
927 crypto_free_cipher_env(cipher);
928 return outlen + symlen;
929 err:
930 memset(buf, 0, sizeof(buf));
931 if (cipher) crypto_free_cipher_env(cipher);
932 return -1;
935 /** Invert crypto_pk_public_hybrid_encrypt. */
937 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
938 char *to,
939 const char *from,
940 size_t fromlen,
941 int padding, int warnOnFailure)
943 int overhead, outlen, r;
944 size_t pkeylen;
945 crypto_cipher_env_t *cipher = NULL;
946 char buf[PK_BYTES+1];
948 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
949 pkeylen = crypto_pk_keysize(env);
951 if (fromlen <= pkeylen) {
952 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,warnOnFailure);
954 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,warnOnFailure);
955 if (outlen<0) {
956 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
957 "Error decrypting public-key data");
958 return -1;
960 if (outlen < CIPHER_KEY_LEN) {
961 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
962 "No room for a symmetric key");
963 return -1;
965 cipher = crypto_create_init_cipher(buf, 0);
966 if (!cipher) {
967 return -1;
969 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
970 outlen -= CIPHER_KEY_LEN;
971 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
972 if (r<0)
973 goto err;
974 memset(buf,0,sizeof(buf));
975 crypto_free_cipher_env(cipher);
976 return outlen + (fromlen-pkeylen);
977 err:
978 memset(buf,0,sizeof(buf));
979 if (cipher) crypto_free_cipher_env(cipher);
980 return -1;
983 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
984 * Return -1 on error, or the number of characters used on success.
987 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
989 int len;
990 unsigned char *buf, *cp;
991 len = i2d_RSAPublicKey(pk->key, NULL);
992 if (len < 0 || len > dest_len)
993 return -1;
994 cp = buf = tor_malloc(len+1);
995 len = i2d_RSAPublicKey(pk->key, &cp);
996 if (len < 0) {
997 crypto_log_errors(LOG_WARN,"encoding public key");
998 tor_free(buf);
999 return -1;
1001 /* We don't encode directly into 'dest', because that would be illegal
1002 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1004 memcpy(dest,buf,len);
1005 tor_free(buf);
1006 return len;
1009 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1010 * success and NULL on failure.
1012 crypto_pk_env_t *
1013 crypto_pk_asn1_decode(const char *str, size_t len)
1015 RSA *rsa;
1016 unsigned char *buf;
1017 /* This ifdef suppresses a type warning. Take out the first case once
1018 * everybody is using openssl 0.9.7 or later.
1020 #if OPENSSL_VERSION_NUMBER < 0x00907000l
1021 unsigned char *cp;
1022 #else
1023 const unsigned char *cp;
1024 #endif
1025 cp = buf = tor_malloc(len);
1026 memcpy(buf,str,len);
1027 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1028 tor_free(buf);
1029 if (!rsa) {
1030 crypto_log_errors(LOG_WARN,"decoding public key");
1031 return NULL;
1033 return _crypto_new_pk_env_rsa(rsa);
1036 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1037 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1038 * Return 0 on success, -1 on failure.
1041 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1043 unsigned char *buf, *bufp;
1044 int len;
1046 len = i2d_RSAPublicKey(pk->key, NULL);
1047 if (len < 0)
1048 return -1;
1049 buf = bufp = tor_malloc(len+1);
1050 len = i2d_RSAPublicKey(pk->key, &bufp);
1051 if (len < 0) {
1052 crypto_log_errors(LOG_WARN,"encoding public key");
1053 tor_free(buf);
1054 return -1;
1056 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1057 tor_free(buf);
1058 return -1;
1060 tor_free(buf);
1061 return 0;
1064 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1065 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1066 * space). Return 0 on success, -1 on failure.
1068 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1069 * of the public key, converted to hexadecimal, in upper case, with a
1070 * space after every four digits.
1072 * If <b>add_space</b> is false, omit the spaces.
1075 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1077 char digest[DIGEST_LEN];
1078 char hexdigest[HEX_DIGEST_LEN+1];
1079 if (crypto_pk_get_digest(pk, digest)) {
1080 return -1;
1082 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1083 if (add_space) {
1084 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
1085 NEVER_TERMINATE)<0)
1086 return -1;
1087 } else {
1088 strcpy(fp_out, hexdigest);
1090 return 0;
1093 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1096 crypto_pk_check_fingerprint_syntax(const char *s)
1098 int i;
1099 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1100 if ((i%5) == 4) {
1101 if (!TOR_ISSPACE(s[i])) return 0;
1102 } else {
1103 if (!TOR_ISXDIGIT(s[i])) return 0;
1106 if (s[FINGERPRINT_LEN]) return 0;
1107 return 1;
1110 /* symmetric crypto */
1112 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1113 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1116 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1118 tor_assert(env);
1120 return crypto_rand(env->key, CIPHER_KEY_LEN);
1123 /** Set the symmetric key for the cipher in <b>env</b> to the first
1124 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1125 * Return 0 on success, -1 on failure.
1128 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1130 tor_assert(env);
1131 tor_assert(key);
1133 if (!env->key)
1134 return -1;
1136 memcpy(env->key, key, CIPHER_KEY_LEN);
1138 return 0;
1141 /** Return a pointer to the key set for the cipher in <b>env</b>.
1143 const char *
1144 crypto_cipher_get_key(crypto_cipher_env_t *env)
1146 return env->key;
1149 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1150 * success, -1 on failure.
1153 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1155 tor_assert(env);
1157 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1158 return 0;
1161 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1162 * success, -1 on failure.
1165 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1167 tor_assert(env);
1169 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1170 return 0;
1173 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1174 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1175 * On failure, return -1.
1178 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1179 const char *from, size_t fromlen)
1181 tor_assert(env);
1182 tor_assert(env->cipher);
1183 tor_assert(from);
1184 tor_assert(fromlen);
1185 tor_assert(to);
1187 aes_crypt(env->cipher, from, fromlen, to);
1188 return 0;
1191 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1192 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1193 * On failure, return -1.
1196 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1197 const char *from, size_t fromlen)
1199 tor_assert(env);
1200 tor_assert(from);
1201 tor_assert(to);
1203 aes_crypt(env->cipher, from, fromlen, to);
1204 return 0;
1207 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1208 * Return 0 on success, -1 on failure.
1211 crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
1213 return crypto_cipher_advance(env, -delta);
1216 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1217 * Return 0 on success, -1 on failure.
1220 crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
1222 aes_adjust_counter(env->cipher, delta);
1223 return 0;
1226 /* SHA-1 */
1228 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1229 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1230 * Return 0 on success, -1 on failure.
1233 crypto_digest(char *digest, const char *m, size_t len)
1235 tor_assert(m);
1236 tor_assert(digest);
1237 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1240 /** Intermediate information about the digest of a stream of data. */
1241 struct crypto_digest_env_t {
1242 SHA_CTX d;
1245 /** Allocate and return a new digest object.
1247 crypto_digest_env_t *
1248 crypto_new_digest_env(void)
1250 crypto_digest_env_t *r;
1251 r = tor_malloc(sizeof(crypto_digest_env_t));
1252 SHA1_Init(&r->d);
1253 return r;
1256 /** Deallocate a digest object.
1258 void
1259 crypto_free_digest_env(crypto_digest_env_t *digest)
1261 tor_free(digest);
1264 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1266 void
1267 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1268 size_t len)
1270 tor_assert(digest);
1271 tor_assert(data);
1272 /* Using the SHA1_*() calls directly means we don't support doing
1273 * sha1 in hardware. But so far the delay of getting the question
1274 * to the hardware, and hearing the answer, is likely higher than
1275 * just doing it ourselves. Hashes are fast.
1277 SHA1_Update(&digest->d, (void*)data, len);
1280 /** Compute the hash of the data that has been passed to the digest
1281 * object; write the first out_len bytes of the result to <b>out</b>.
1282 * <b>out_len</b> must be \<= DIGEST_LEN.
1284 void
1285 crypto_digest_get_digest(crypto_digest_env_t *digest,
1286 char *out, size_t out_len)
1288 static unsigned char r[DIGEST_LEN];
1289 SHA_CTX tmpctx;
1290 tor_assert(digest);
1291 tor_assert(out);
1292 tor_assert(out_len <= DIGEST_LEN);
1293 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1294 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1295 SHA1_Final(r, &tmpctx);
1296 memcpy(out, r, out_len);
1299 /** Allocate and return a new digest object with the same state as
1300 * <b>digest</b>
1302 crypto_digest_env_t *
1303 crypto_digest_dup(const crypto_digest_env_t *digest)
1305 crypto_digest_env_t *r;
1306 tor_assert(digest);
1307 r = tor_malloc(sizeof(crypto_digest_env_t));
1308 memcpy(r,digest,sizeof(crypto_digest_env_t));
1309 return r;
1312 /** Replace the state of the digest object <b>into</b> with the state
1313 * of the digest object <b>from</b>.
1315 void
1316 crypto_digest_assign(crypto_digest_env_t *into,
1317 const crypto_digest_env_t *from)
1319 tor_assert(into);
1320 tor_assert(from);
1321 memcpy(into,from,sizeof(crypto_digest_env_t));
1324 /* DH */
1326 /** Shared P parameter for our DH key exchanged. */
1327 static BIGNUM *dh_param_p = NULL;
1328 /** Shared G parameter for our DH key exchanges. */
1329 static BIGNUM *dh_param_g = NULL;
1331 /** Initialize dh_param_p and dh_param_g if they are not already
1332 * set. */
1333 static void
1334 init_dh_param(void)
1336 BIGNUM *p, *g;
1337 int r;
1338 if (dh_param_p && dh_param_g)
1339 return;
1341 p = BN_new();
1342 g = BN_new();
1343 tor_assert(p);
1344 tor_assert(g);
1346 /* This is from rfc2409, section 6.2. It's a safe prime, and
1347 supposedly it equals:
1348 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1350 r = BN_hex2bn(&p,
1351 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1352 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1353 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1354 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1355 "49286651ECE65381FFFFFFFFFFFFFFFF");
1356 tor_assert(r);
1358 r = BN_set_word(g, 2);
1359 tor_assert(r);
1360 dh_param_p = p;
1361 dh_param_g = g;
1364 /** Allocate and return a new DH object for a key exchange.
1366 crypto_dh_env_t *
1367 crypto_dh_new(void)
1369 crypto_dh_env_t *res = NULL;
1371 if (!dh_param_p)
1372 init_dh_param();
1374 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1376 if (!(res->dh = DH_new()))
1377 goto err;
1379 if (!(res->dh->p = BN_dup(dh_param_p)))
1380 goto err;
1382 if (!(res->dh->g = BN_dup(dh_param_g)))
1383 goto err;
1385 return res;
1386 err:
1387 crypto_log_errors(LOG_WARN, "creating DH object");
1388 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1389 if (res) tor_free(res);
1390 return NULL;
1393 /** Return the length of the DH key in <b>dh</b>, in bytes.
1396 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1398 tor_assert(dh);
1399 return DH_size(dh->dh);
1402 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1403 * success, -1 on failure.
1406 crypto_dh_generate_public(crypto_dh_env_t *dh)
1408 again:
1409 if (!DH_generate_key(dh->dh)) {
1410 crypto_log_errors(LOG_WARN, "generating DH key");
1411 return -1;
1413 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1414 warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-the-universe chances really do happen. Trying again.");
1415 /* Free and clear the keys, so openssl will actually try again. */
1416 BN_free(dh->dh->pub_key);
1417 BN_free(dh->dh->priv_key);
1418 dh->dh->pub_key = dh->dh->priv_key = NULL;
1419 goto again;
1421 return 0;
1424 /** Generate g^x as necessary, and write the g^x for the key exchange
1425 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1426 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1429 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1431 int bytes;
1432 tor_assert(dh);
1433 if (!dh->dh->pub_key) {
1434 if (crypto_dh_generate_public(dh)<0)
1435 return -1;
1438 tor_assert(dh->dh->pub_key);
1439 bytes = BN_num_bytes(dh->dh->pub_key);
1440 tor_assert(bytes >= 0);
1441 if (pubkey_len < (size_t)bytes) {
1442 warn(LD_CRYPTO, "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)", (int) pubkey_len, bytes);
1443 return -1;
1446 memset(pubkey, 0, pubkey_len);
1447 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1449 return 0;
1452 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1453 * okay, or -1 if it's bad.
1454 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1456 static int
1457 tor_check_dh_key(BIGNUM *bn)
1459 /* There are about 2^116 ways to have a 1024-bit key with <= 16 bits set,
1460 * and similarly for <= 16 bits unset. This is negligible compared to the
1461 * 2^1024 entry keyspace. */
1462 #define MIN_DIFFERING_BITS 16
1463 /* This covers another 2^25 keys, which is still negligible. */
1464 #define MIN_DIST_FROM_EDGE (1<<24)
1465 int i, n_bits, n_set;
1466 BIGNUM *x = NULL;
1467 char *s;
1468 tor_assert(bn);
1469 x = BN_new();
1470 if (!dh_param_p)
1471 init_dh_param();
1472 if (bn->neg) {
1473 warn(LD_CRYPTO, "Rejecting DH key < 0");
1474 return -1;
1476 if (BN_cmp(bn, dh_param_p)>=0) {
1477 warn(LD_CRYPTO, "Rejecting DH key >= p");
1478 return -1;
1480 n_bits = BN_num_bits(bn);
1481 n_set = 0;
1482 for (i=0; i <= n_bits; ++i) {
1483 if (BN_is_bit_set(bn, i))
1484 ++n_set;
1486 if (n_set < MIN_DIFFERING_BITS || n_set >= n_bits-MIN_DIFFERING_BITS) {
1487 warn(LD_CRYPTO, "Too few/many bits in DH key (%d)", n_set);
1488 goto err;
1490 BN_set_word(x, MIN_DIST_FROM_EDGE);
1491 if (BN_cmp(bn,x)<=0) {
1492 warn(LD_CRYPTO, "DH key is too close to 0");
1493 goto err;
1495 BN_copy(x,dh_param_p);
1496 BN_sub_word(x, MIN_DIST_FROM_EDGE);
1497 if (BN_cmp(bn,x)>=0) {
1498 warn(LD_CRYPTO, "DH key is too close to p");
1499 goto err;
1501 BN_free(x);
1502 return 0;
1503 err:
1504 BN_free(x);
1505 s = BN_bn2hex(bn);
1506 warn(LD_CRYPTO, "Rejecting invalid DH key [%s]", s);
1507 OPENSSL_free(s);
1508 return -1;
1511 #undef MIN
1512 #define MIN(a,b) ((a)<(b)?(a):(b))
1513 /** Given a DH key exchange object, and our peer's value of g^y (as a
1514 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1515 * <b>secret_bytes_out</b> bytes of shared key material and write them
1516 * to <b>secret_out</b>. Return the number of bytes generated on success,
1517 * or -1 on failure.
1519 * (We generate key material by computing
1520 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1521 * where || is concatenation.)
1524 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1525 const char *pubkey, size_t pubkey_len,
1526 char *secret_out, size_t secret_bytes_out)
1528 char hash[DIGEST_LEN];
1529 char *secret_tmp = NULL;
1530 BIGNUM *pubkey_bn = NULL;
1531 size_t secret_len=0;
1532 unsigned int i;
1533 int result=0;
1534 tor_assert(dh);
1535 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1537 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
1538 goto error;
1539 if (tor_check_dh_key(pubkey_bn)<0) {
1540 /* Check for invalid public keys. */
1541 warn(LD_CRYPTO,"Rejected invalid g^x");
1542 goto error;
1544 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
1545 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1546 if (result < 0) {
1547 warn(LD_CRYPTO,"DH_compute_key() failed.");
1548 goto error;
1550 secret_len = result;
1551 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1552 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1553 * Leading zeros MUST be preserved, so that ZZ occupies as many
1554 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1555 * bytes long.
1556 * What are the security implications here?
1558 for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
1559 secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
1560 if (crypto_digest(hash, secret_tmp, secret_len+1))
1561 goto error;
1562 memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
1564 secret_len = secret_bytes_out;
1566 goto done;
1567 error:
1568 result = -1;
1569 done:
1570 crypto_log_errors(LOG_WARN, "completing DH handshake");
1571 if (pubkey_bn)
1572 BN_free(pubkey_bn);
1573 tor_free(secret_tmp);
1574 if (result < 0)
1575 return result;
1576 else
1577 return secret_len;
1580 /** Free a DH key exchange object.
1582 void
1583 crypto_dh_free(crypto_dh_env_t *dh)
1585 tor_assert(dh);
1586 tor_assert(dh->dh);
1587 DH_free(dh->dh);
1588 tor_free(dh);
1591 /* random numbers */
1593 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1594 * work for us too. */
1595 #define ADD_ENTROPY 32
1597 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1598 "release".) */
1599 #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1601 /** Seed OpenSSL's random number generator with bytes from the
1602 * operating system. Return 0 on success, -1 on failure.
1605 crypto_seed_rng(void)
1607 char buf[ADD_ENTROPY];
1608 int rand_poll_status;
1610 /* local variables */
1611 #ifdef MS_WINDOWS
1612 static int provider_set = 0;
1613 static HCRYPTPROV provider;
1614 #else
1615 static const char *filenames[] = {
1616 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1618 int fd;
1619 int i, n;
1620 #endif
1622 #if USE_RAND_POLL
1623 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1624 * entropy than we do. We'll try calling that, *and* calling our own entropy
1625 * functions. If one succeeds, we'll accept the RNG as seeded. */
1626 rand_poll_status = RAND_poll();
1627 if (rand_poll_status == 0)
1628 warn(LD_CRYPTO, "RAND_poll() failed.");
1629 #else
1630 rand_poll_status = 0;
1631 #endif
1633 #ifdef MS_WINDOWS
1634 if (!provider_set) {
1635 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
1636 if (GetLastError() != NTE_BAD_KEYSET) {
1637 warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1638 return rand_poll_status ? 0 : -1;
1641 provider_set = 1;
1643 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1644 warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1645 return rand_poll_status ? 0 : -1;
1647 RAND_seed(buf, sizeof(buf));
1648 return 0;
1649 #else
1650 for (i = 0; filenames[i]; ++i) {
1651 fd = open(filenames[i], O_RDONLY, 0);
1652 if (fd<0) continue;
1653 info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1654 n = read_all(fd, buf, sizeof(buf), 0);
1655 close(fd);
1656 if (n != sizeof(buf)) {
1657 warn(LD_CRYPTO, "Error reading from entropy source");
1658 return -1;
1660 RAND_seed(buf, sizeof(buf));
1661 return 0;
1664 warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1665 return rand_poll_status ? 0 : -1;
1666 #endif
1669 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1670 * success, -1 on failure.
1673 crypto_rand(char *to, size_t n)
1675 int r;
1676 tor_assert(to);
1677 r = RAND_bytes((unsigned char*)to, n);
1678 if (r == 0)
1679 crypto_log_errors(LOG_WARN, "generating random data");
1680 return (r == 1) ? 0 : -1;
1683 /** Return a pseudorandom integer, chosen uniformly from the values
1684 * between 0 and max-1. */
1686 crypto_rand_int(unsigned int max)
1688 unsigned int val;
1689 unsigned int cutoff;
1690 tor_assert(max < UINT_MAX);
1691 tor_assert(max > 0); /* don't div by 0 */
1693 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1694 * distribution with clipping at the upper end of unsigned int's
1695 * range.
1697 cutoff = UINT_MAX - (UINT_MAX%max);
1698 while (1) {
1699 crypto_rand((char*)&val, sizeof(val));
1700 if (val < cutoff)
1701 return val % max;
1705 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1707 void *
1708 smartlist_choose(const smartlist_t *sl)
1710 size_t len;
1711 len = smartlist_len(sl);
1712 if (len)
1713 return smartlist_get(sl,crypto_rand_int(len));
1714 return NULL; /* no elements to choose from */
1717 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1718 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1719 * bytes. Return the number of bytes written on success; -1 if
1720 * destlen is too short, or other failure.
1723 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1725 EVP_ENCODE_CTX ctx;
1726 int len, ret;
1728 /* 48 bytes of input -> 64 bytes of output plus newline.
1729 Plus one more byte, in case I'm wrong.
1731 if (destlen < ((srclen/48)+1)*66)
1732 return -1;
1733 if (destlen > SIZE_T_CEILING)
1734 return -1;
1736 EVP_EncodeInit(&ctx);
1737 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len, (unsigned char*)src, srclen);
1738 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1739 ret += len;
1740 return ret;
1743 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1744 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1745 * bytes. Return the number of bytes written on success; -1 if
1746 * destlen is too short, or other failure.
1748 * NOTE: destlen should be a little longer than the amount of data it
1749 * will contain, since we check for sufficient space conservatively.
1750 * Here, "a little" is around 64-ish bytes.
1753 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1755 EVP_ENCODE_CTX ctx;
1756 int len, ret;
1757 /* 64 bytes of input -> *up to* 48 bytes of output.
1758 Plus one more byte, in case I'm wrong.
1760 if (destlen < ((srclen/64)+1)*49)
1761 return -1;
1762 if (destlen > SIZE_T_CEILING)
1763 return -1;
1765 EVP_DecodeInit(&ctx);
1766 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len, (unsigned char*)src, srclen);
1767 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
1768 ret += len;
1769 return ret;
1773 digest_to_base64(char *d64, const char *digest)
1775 char buf[256];
1776 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
1777 buf[BASE64_DIGEST_LEN] = '\0';
1778 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
1779 return 0;
1783 digest_from_base64(char *digest, const char *d64)
1785 char buf_in[BASE64_DIGEST_LEN+3];
1786 char buf[256];
1787 if (strlen(d64) != BASE64_DIGEST_LEN)
1788 return -1;
1789 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
1790 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
1791 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
1792 return -1;
1793 memcpy(digest, buf, DIGEST_LEN);
1794 return 0;
1797 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1798 * that srclen*8 is a multiple of 5.
1800 void
1801 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1803 unsigned int nbits, i, bit, v, u;
1804 nbits = srclen * 8;
1806 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1807 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1808 tor_assert(destlen < SIZE_T_CEILING);
1810 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1811 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1812 v = ((uint8_t)src[bit/8]) << 8;
1813 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1814 /* set u to the 5-bit value at the bit'th bit of src. */
1815 u = (v >> (11-(bit%8))) & 0x1F;
1816 dest[i] = BASE32_CHARS[u];
1818 dest[i] = '\0';
1821 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1822 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1823 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1824 * are a salt; the 9th byte describes how much iteration to do.
1825 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1827 void
1828 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1829 size_t secret_len, const char *s2k_specifier)
1831 crypto_digest_env_t *d;
1832 uint8_t c;
1833 size_t count;
1834 char *tmp;
1835 tor_assert(key_out_len < SIZE_T_CEILING);
1837 #define EXPBIAS 6
1838 c = s2k_specifier[8];
1839 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1840 #undef EXPBIAS
1842 tor_assert(key_out_len <= DIGEST_LEN);
1844 d = crypto_new_digest_env();
1845 tmp = tor_malloc(8+secret_len);
1846 memcpy(tmp,s2k_specifier,8);
1847 memcpy(tmp+8,secret,secret_len);
1848 secret_len += 8;
1849 while (count) {
1850 if (count >= secret_len) {
1851 crypto_digest_add_bytes(d, tmp, secret_len);
1852 count -= secret_len;
1853 } else {
1854 crypto_digest_add_bytes(d, tmp, count);
1855 count = 0;
1858 crypto_digest_get_digest(d, key_out, key_out_len);
1859 tor_free(tmp);
1860 crypto_free_digest_env(d);
1863 #ifdef TOR_IS_MULTITHREADED
1864 static void
1865 _openssl_locking_cb(int mode, int n, const char *file, int line)
1867 if (!_openssl_mutexes)
1868 /* This is not a really good fix for the
1869 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1870 * it can't hurt. */
1871 return;
1872 if (mode & CRYPTO_LOCK)
1873 tor_mutex_acquire(_openssl_mutexes[n]);
1874 else
1875 tor_mutex_release(_openssl_mutexes[n]);
1878 static int
1879 setup_openssl_threading(void)
1881 int i;
1882 int n = CRYPTO_num_locks();
1883 _n_openssl_mutexes = n;
1884 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
1885 for (i=0; i < n; ++i)
1886 _openssl_mutexes[i] = tor_mutex_new();
1887 CRYPTO_set_locking_callback(_openssl_locking_cb);
1888 CRYPTO_set_id_callback(tor_get_thread_id);
1889 return 0;
1891 #else
1892 static int
1893 setup_openssl_threading(void)
1895 return 0;
1897 #endif