Try to build with OpenSSL 0.9.6. Lets pay attention to see if anybody complains.
[tor.git] / src / common / crypto.c
blob948e31a50da10bfd0ee20929bf26b8dee1ee9399
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 OPENSSL_PRE_097
70 #define NO_ENGINES
71 #else
72 #include <openssl/engine.h>
73 #endif
75 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
76 * (and don't indicate errors) in OpenSSL version 0.9.5.
78 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
80 #ifdef OPENSSL_095
81 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
82 #else
83 #define RETURN_SSL_OUTCOME(exp) return !(exp)
84 #endif
86 /** Macro: is k a valid RSA public or private key? */
87 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
88 /** Macro: is k a valid RSA private key? */
89 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
91 #ifdef TOR_IS_MULTITHREADED
92 static tor_mutex_t **_openssl_mutexes = NULL;
93 static int _n_openssl_mutexes = -1;
94 #endif
96 /** A public key, or a public/private keypair. */
97 struct crypto_pk_env_t
99 int refs; /* reference counting so we don't have to copy keys */
100 RSA *key;
103 /** Key and stream information for a stream cipher. */
104 struct crypto_cipher_env_t
106 char key[CIPHER_KEY_LEN];
107 aes_cnt_cipher_t *cipher;
110 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
111 * while we're waiting for the second.*/
112 struct crypto_dh_env_t {
113 DH *dh;
116 /* Prototypes for functions only used by tortls.c */
117 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
118 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
119 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
120 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
122 static int setup_openssl_threading(void);
123 static int tor_check_dh_key(BIGNUM *bn);
125 /** Return the number of bytes added by padding method <b>padding</b>.
127 static INLINE int
128 crypto_get_rsa_padding_overhead(int padding)
130 switch (padding)
132 case RSA_NO_PADDING: return 0;
133 case RSA_PKCS1_OAEP_PADDING: return 42;
134 case RSA_PKCS1_PADDING: return 11;
135 default: tor_assert(0); return -1;
139 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
141 static INLINE int
142 crypto_get_rsa_padding(int padding)
144 switch (padding)
146 case PK_NO_PADDING: return RSA_NO_PADDING;
147 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
148 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
149 default: tor_assert(0); return -1;
153 /** Boolean: has OpenSSL's crypto been initialized? */
154 static int _crypto_global_initialized = 0;
156 /** Log all pending crypto errors at level <b>severity</b>. Use
157 * <b>doing</b> to describe our current activities.
159 static void
160 crypto_log_errors(int severity, const char *doing)
162 unsigned int err;
163 const char *msg, *lib, *func;
164 while ((err = ERR_get_error()) != 0) {
165 msg = (const char*)ERR_reason_error_string(err);
166 lib = (const char*)ERR_lib_error_string(err);
167 func = (const char*)ERR_func_error_string(err);
168 if (!msg) msg = "(null)";
169 if (doing) {
170 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)", doing, msg, lib, func);
171 } else {
172 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
177 #ifndef NO_ENGINES
178 static void
179 log_engine(const char *fn, ENGINE *e)
181 if (e) {
182 const char *name, *id;
183 name = ENGINE_get_name(e);
184 id = ENGINE_get_id(e);
185 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
186 name?name:"?", id?id:"?", fn);
187 } else {
188 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
191 #endif
193 /** Initialize the crypto library. Return 0 on success, -1 on failure.
196 crypto_global_init(int useAccel)
198 if (!_crypto_global_initialized) {
199 ERR_load_crypto_strings();
200 OpenSSL_add_all_algorithms();
201 _crypto_global_initialized = 1;
202 setup_openssl_threading();
203 #ifndef NO_ENGINES
204 if (useAccel) {
205 if (useAccel < 0)
206 warn(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
207 info(LD_CRYPTO, "Initializing OpenSSL engine support.");
208 ENGINE_load_builtin_engines();
209 if (!ENGINE_register_all_complete())
210 return -1;
212 /* XXXX make sure this isn't leaking. */
213 log_engine("RSA", ENGINE_get_default_RSA());
214 log_engine("DH", ENGINE_get_default_DH());
215 log_engine("RAND", ENGINE_get_default_RAND());
216 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
217 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
218 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
220 #endif
222 return 0;
225 /** Free crypto resources held by this thread. */
226 void
227 crypto_thread_cleanup(void)
229 ERR_remove_state(0);
232 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
235 crypto_global_cleanup(void)
237 EVP_cleanup();
238 ERR_remove_state(0);
239 ERR_free_strings();
240 #ifndef NO_ENGINES
241 ENGINE_cleanup();
242 CONF_modules_unload(1);
243 CRYPTO_cleanup_all_ex_data();
244 #endif
245 #ifdef TOR_IS_MULTITHREADED
246 if (_n_openssl_mutexes) {
247 int n = _n_openssl_mutexes;
248 tor_mutex_t **ms = _openssl_mutexes;
249 int i;
250 _openssl_mutexes = NULL;
251 _n_openssl_mutexes = 0;
252 for (i=0;i<n;++i) {
253 tor_mutex_free(ms[i]);
255 tor_free(ms);
257 #endif
258 return 0;
261 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
262 crypto_pk_env_t *
263 _crypto_new_pk_env_rsa(RSA *rsa)
265 crypto_pk_env_t *env;
266 tor_assert(rsa);
267 env = tor_malloc(sizeof(crypto_pk_env_t));
268 env->refs = 1;
269 env->key = rsa;
270 return env;
273 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
274 RSA *
275 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
277 return env->key;
280 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
281 * private is set, include the private-key portion of the key. */
282 EVP_PKEY *
283 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
285 RSA *key = NULL;
286 EVP_PKEY *pkey = NULL;
287 tor_assert(env->key);
288 if (private) {
289 if (!(key = RSAPrivateKey_dup(env->key)))
290 goto error;
291 } else {
292 if (!(key = RSAPublicKey_dup(env->key)))
293 goto error;
295 if (!(pkey = EVP_PKEY_new()))
296 goto error;
297 if (!(EVP_PKEY_assign_RSA(pkey, key)))
298 goto error;
299 return pkey;
300 error:
301 if (pkey)
302 EVP_PKEY_free(pkey);
303 if (key)
304 RSA_free(key);
305 return NULL;
308 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
310 DH *
311 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
313 return dh->dh;
316 /** Allocate and return storage for a public key. The key itself will not yet
317 * be set.
319 crypto_pk_env_t *
320 crypto_new_pk_env(void)
322 RSA *rsa;
324 rsa = RSA_new();
325 if (!rsa) return NULL;
326 return _crypto_new_pk_env_rsa(rsa);
329 /** Release a reference to an asymmetric key; when all the references
330 * are released, free the key.
332 void
333 crypto_free_pk_env(crypto_pk_env_t *env)
335 tor_assert(env);
337 if (--env->refs > 0)
338 return;
340 if (env->key)
341 RSA_free(env->key);
343 tor_free(env);
346 /** Create a new symmetric cipher for a given key and encryption flag
347 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
348 * on failure.
350 crypto_cipher_env_t *
351 crypto_create_init_cipher(const char *key, int encrypt_mode)
353 int r;
354 crypto_cipher_env_t *crypto = NULL;
356 if (! (crypto = crypto_new_cipher_env())) {
357 warn(LD_CRYPTO, "Unable to allocate crypto object");
358 return NULL;
361 if (crypto_cipher_set_key(crypto, key)) {
362 crypto_log_errors(LOG_WARN, "setting symmetric key");
363 goto error;
366 if (encrypt_mode)
367 r = crypto_cipher_encrypt_init_cipher(crypto);
368 else
369 r = crypto_cipher_decrypt_init_cipher(crypto);
371 if (r)
372 goto error;
373 return crypto;
375 error:
376 if (crypto)
377 crypto_free_cipher_env(crypto);
378 return NULL;
381 /** Allocate and return a new symmetric cipher.
383 crypto_cipher_env_t *
384 crypto_new_cipher_env(void)
386 crypto_cipher_env_t *env;
388 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
389 env->cipher = aes_new_cipher();
390 return env;
393 /** Free a symmetric cipher.
395 void
396 crypto_free_cipher_env(crypto_cipher_env_t *env)
398 tor_assert(env);
400 tor_assert(env->cipher);
401 aes_free_cipher(env->cipher);
402 tor_free(env);
405 /* public key crypto */
407 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
408 * success, -1 on failure.
411 crypto_pk_generate_key(crypto_pk_env_t *env)
413 tor_assert(env);
415 if (env->key)
416 RSA_free(env->key);
417 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
418 if (!env->key) {
419 crypto_log_errors(LOG_WARN, "generating RSA key");
420 return -1;
423 return 0;
426 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
427 * Return 0 on success, -1 on failure.
429 static int
430 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
431 const char *s)
433 BIO *b;
435 tor_assert(env);
436 tor_assert(s);
438 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
439 b = BIO_new_mem_buf((char*)s, -1);
441 if (env->key)
442 RSA_free(env->key);
444 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
446 BIO_free(b);
448 if (!env->key) {
449 crypto_log_errors(LOG_WARN, "Error parsing private key");
450 return -1;
452 return 0;
455 /** Read a PEM-encoded private key from the file named by
456 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
459 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
461 char *contents;
462 int r;
464 /* Read the file into a string. */
465 contents = read_file_to_str(keyfile, 0);
466 if (!contents) {
467 warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
468 return -1;
471 /* Try to parse it. */
472 r = crypto_pk_read_private_key_from_string(env, contents);
473 tor_free(contents);
474 if (r)
475 return -1; /* read_private_key_from_string already warned, so we don't.*/
477 /* Make sure it's valid. */
478 if (crypto_pk_check_key(env) <= 0)
479 return -1;
481 return 0;
484 /** PEM-encode the public key portion of <b>env</b> and write it to a
485 * newly allocated string. On success, set *<b>dest</b> to the new
486 * string, *<b>len</b> to the string's length, and return 0. On
487 * failure, return -1.
490 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, size_t *len)
492 BUF_MEM *buf;
493 BIO *b;
495 tor_assert(env);
496 tor_assert(env->key);
497 tor_assert(dest);
499 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
501 /* Now you can treat b as if it were a file. Just use the
502 * PEM_*_bio_* functions instead of the non-bio variants.
504 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
505 crypto_log_errors(LOG_WARN, "writing public key to string");
506 return -1;
509 BIO_get_mem_ptr(b, &buf);
510 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
511 BIO_free(b);
513 tor_assert(buf->length >= 0);
514 *dest = tor_malloc(buf->length+1);
515 memcpy(*dest, buf->data, buf->length);
516 (*dest)[buf->length] = 0; /* null terminate it */
517 *len = buf->length;
518 BUF_MEM_free(buf);
520 return 0;
523 /** Read a PEM-encoded public key from the first <b>len</b> characters of
524 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
525 * failure.
528 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, size_t len)
530 BIO *b;
532 tor_assert(env);
533 tor_assert(src);
535 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
537 BIO_write(b, src, len);
539 if (env->key)
540 RSA_free(env->key);
541 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
542 BIO_free(b);
543 if (!env->key) {
544 crypto_log_errors(LOG_WARN, "reading public key from string");
545 return -1;
548 return 0;
551 /* Write the private key from 'env' into the file named by 'fname',
552 * PEM-encoded. Return 0 on success, -1 on failure.
555 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
556 const char *fname)
558 BIO *bio;
559 char *cp;
560 long len;
561 char *s;
562 int r;
564 tor_assert(PRIVATE_KEY_OK(env));
566 if (!(bio = BIO_new(BIO_s_mem())))
567 return -1;
568 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
569 == 0) {
570 crypto_log_errors(LOG_WARN, "writing private key");
571 BIO_free(bio);
572 return -1;
574 len = BIO_get_mem_data(bio, &cp);
575 tor_assert(len >= 0);
576 s = tor_malloc(len+1);
577 memcpy(s, cp, len);
578 s[len]='\0';
579 r = write_str_to_file(fname, s, 0);
580 BIO_free(bio);
581 tor_free(s);
582 return r;
585 /** Allocate a new string in *<b>out</b>, containing the public portion of the
586 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
587 * length of the encoded representation on success, and -1 on failure.
589 * <i>This function is for temporary use only. We need a simple
590 * one-line representation for keys to work around a bug in parsing
591 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
592 * in versions of Tor up to 0.0.9pre2.</i>
595 crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
597 int len;
598 char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
599 tor_assert(env);
600 tor_assert(out);
601 len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
602 if (len < 0) {
603 return -1;
605 *out = tor_malloc(len * 2); /* too long, but safe. */
606 if (base64_encode(*out, len*2, buf, len) < 0) {
607 warn(LD_CRYPTO, "Error base64-encoding DER-encoded key");
608 tor_free(*out);
609 return -1;
611 /* Remove spaces */
612 tor_strstrip(*out, " \r\n\t");
613 return strlen(*out);
616 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
617 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
619 * <i>This function is for temporary use only. We need a simple
620 * one-line representation for keys to work around a bug in parsing
621 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
622 * in versions of Tor up to 0.0.9pre2.</i>
624 crypto_pk_env_t *
625 crypto_pk_DER64_decode_public_key(const char *in)
627 char partitioned[PK_BYTES*2 + 16];
628 char buf[PK_BYTES*2];
629 int len;
630 tor_assert(in);
631 len = strlen(in);
633 if (strlen(in) > PK_BYTES*2) {
634 return NULL;
636 /* base64_decode doesn't work unless we insert linebreaks every 64
637 * characters. how dumb. */
638 if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
639 ALWAYS_TERMINATE))
640 return NULL;
641 len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
642 if (len<0) {
643 warn(LD_CRYPTO,"Error base-64 decoding key");
644 return NULL;
646 return crypto_pk_asn1_decode(buf, len);
649 /** Return true iff <b>env</b> has a valid key.
652 crypto_pk_check_key(crypto_pk_env_t *env)
654 int r;
655 tor_assert(env);
657 r = RSA_check_key(env->key);
658 if (r <= 0)
659 crypto_log_errors(LOG_WARN,"checking RSA key");
660 return r;
663 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
664 * if a==b, and 1 if a\>b.
667 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
669 int result;
671 if (!a || !b)
672 return -1;
674 if (!a->key || !b->key)
675 return -1;
677 tor_assert(PUBLIC_KEY_OK(a));
678 tor_assert(PUBLIC_KEY_OK(b));
679 result = BN_cmp((a->key)->n, (b->key)->n);
680 if (result)
681 return result;
682 return BN_cmp((a->key)->e, (b->key)->e);
685 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
686 size_t
687 crypto_pk_keysize(crypto_pk_env_t *env)
689 tor_assert(env);
690 tor_assert(env->key);
692 return (size_t) RSA_size(env->key);
695 /** Increase the reference count of <b>env</b>, and return it.
697 crypto_pk_env_t *
698 crypto_pk_dup_key(crypto_pk_env_t *env)
700 tor_assert(env);
701 tor_assert(env->key);
703 env->refs++;
704 return env;
707 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
708 * in <b>env</b>, using the padding method <b>padding</b>. On success,
709 * write the result to <b>to</b>, and return the number of bytes
710 * written. On failure, return -1.
713 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
714 const char *from, size_t fromlen, int padding)
716 int r;
717 tor_assert(env);
718 tor_assert(from);
719 tor_assert(to);
721 r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
722 env->key, crypto_get_rsa_padding(padding));
723 if (r<0) {
724 crypto_log_errors(LOG_WARN, "performing RSA encryption");
725 return -1;
727 return r;
730 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
731 * in <b>env</b>, using the padding method <b>padding</b>. On success,
732 * write the result to <b>to</b>, and return the number of bytes
733 * written. On failure, return -1.
736 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
737 const char *from, size_t fromlen,
738 int padding, int warnOnFailure)
740 int r;
741 tor_assert(env);
742 tor_assert(from);
743 tor_assert(to);
744 tor_assert(env->key);
745 if (!env->key->p)
746 /* Not a private key */
747 return -1;
749 r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
750 env->key, crypto_get_rsa_padding(padding));
752 if (r<0) {
753 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
754 "performing RSA decryption");
755 return -1;
757 return r;
760 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
761 * public key in <b>env</b>, using PKCS1 padding. On success, write the
762 * signed data to <b>to</b>, and return the number of bytes written.
763 * On failure, return -1.
766 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
767 const char *from, size_t fromlen)
769 int r;
770 tor_assert(env);
771 tor_assert(from);
772 tor_assert(to);
773 r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to, env->key, RSA_PKCS1_PADDING);
775 if (r<0) {
776 crypto_log_errors(LOG_WARN, "checking RSA signature");
777 return -1;
779 return r;
782 /** Check a siglen-byte long signature at <b>sig</b> against
783 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
784 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
785 * SHA1(data). Else return -1.
788 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
789 int datalen, const char *sig, int siglen)
791 char digest[DIGEST_LEN];
792 char buf[PK_BYTES+1];
793 int r;
795 tor_assert(env);
796 tor_assert(data);
797 tor_assert(sig);
799 if (crypto_digest(digest,data,datalen)<0) {
800 warn(LD_CRYPTO, "couldn't compute digest");
801 return -1;
803 r = crypto_pk_public_checksig(env,buf,sig,siglen);
804 if (r != DIGEST_LEN) {
805 warn(LD_CRYPTO, "Invalid signature");
806 return -1;
808 if (memcmp(buf, digest, DIGEST_LEN)) {
809 warn(LD_CRYPTO, "Signature mismatched with digest.");
810 return -1;
813 return 0;
816 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
817 * <b>env</b>, using PKCS1 padding. On success, write the signature to
818 * <b>to</b>, and return the number of bytes written. On failure, return
819 * -1.
822 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
823 const char *from, size_t fromlen)
825 int r;
826 tor_assert(env);
827 tor_assert(from);
828 tor_assert(to);
829 if (!env->key->p)
830 /* Not a private key */
831 return -1;
833 r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to, env->key, RSA_PKCS1_PADDING);
834 if (r<0) {
835 crypto_log_errors(LOG_WARN, "generating RSA signature");
836 return -1;
838 return r;
841 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
842 * <b>from</b>; sign the data with the private key in <b>env</b>, and
843 * store it in <b>to</b>. Return the number of bytes written on
844 * success, and -1 on failure.
847 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
848 const char *from, size_t fromlen)
850 char digest[DIGEST_LEN];
851 if (crypto_digest(digest,from,fromlen)<0)
852 return -1;
853 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
856 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
857 * bytes of data from <b>from</b>, with padding type 'padding',
858 * storing the results on <b>to</b>.
860 * If no padding is used, the public key must be at least as large as
861 * <b>from</b>.
863 * Returns the number of bytes written on success, -1 on failure.
865 * The encrypted data consists of:
866 * - The source data, padded and encrypted with the public key, if the
867 * padded source data is no longer than the public key, and <b>force</b>
868 * is false, OR
869 * - The beginning of the source data prefixed with a 16-byte symmetric key,
870 * padded and encrypted with the public key; followed by the rest of
871 * the source data encrypted in AES-CTR mode with the symmetric key.
874 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
875 char *to,
876 const char *from,
877 size_t fromlen,
878 int padding, int force)
880 int overhead, outlen, r, symlen;
881 size_t pkeylen;
882 crypto_cipher_env_t *cipher = NULL;
883 char buf[PK_BYTES+1];
885 tor_assert(env);
886 tor_assert(from);
887 tor_assert(to);
889 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
890 pkeylen = crypto_pk_keysize(env);
892 if (padding == PK_NO_PADDING && fromlen < pkeylen)
893 return -1;
895 if (!force && fromlen+overhead <= pkeylen) {
896 /* It all fits in a single encrypt. */
897 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
899 cipher = crypto_new_cipher_env();
900 if (!cipher) return -1;
901 if (crypto_cipher_generate_key(cipher)<0)
902 goto err;
903 /* You can't just run around RSA-encrypting any bitstream: if it's
904 * greater than the RSA key, then OpenSSL will happily encrypt, and
905 * later decrypt to the wrong value. So we set the first bit of
906 * 'cipher->key' to 0 if we aren't padding. This means that our
907 * symmetric key is really only 127 bits.
909 if (padding == PK_NO_PADDING)
910 cipher->key[0] &= 0x7f;
911 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
912 goto err;
913 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
914 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
916 /* Length of symmetrically encrypted data. */
917 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
919 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
920 if (outlen!=(int)pkeylen) {
921 goto err;
923 r = crypto_cipher_encrypt(cipher, to+outlen,
924 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
926 if (r<0) goto err;
927 memset(buf, 0, sizeof(buf));
928 crypto_free_cipher_env(cipher);
929 return outlen + symlen;
930 err:
931 memset(buf, 0, sizeof(buf));
932 if (cipher) crypto_free_cipher_env(cipher);
933 return -1;
936 /** Invert crypto_pk_public_hybrid_encrypt. */
938 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
939 char *to,
940 const char *from,
941 size_t fromlen,
942 int padding, int warnOnFailure)
944 int overhead, outlen, r;
945 size_t pkeylen;
946 crypto_cipher_env_t *cipher = NULL;
947 char buf[PK_BYTES+1];
949 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
950 pkeylen = crypto_pk_keysize(env);
952 if (fromlen <= pkeylen) {
953 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,warnOnFailure);
955 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,warnOnFailure);
956 if (outlen<0) {
957 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
958 "Error decrypting public-key data");
959 return -1;
961 if (outlen < CIPHER_KEY_LEN) {
962 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
963 "No room for a symmetric key");
964 return -1;
966 cipher = crypto_create_init_cipher(buf, 0);
967 if (!cipher) {
968 return -1;
970 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
971 outlen -= CIPHER_KEY_LEN;
972 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
973 if (r<0)
974 goto err;
975 memset(buf,0,sizeof(buf));
976 crypto_free_cipher_env(cipher);
977 return outlen + (fromlen-pkeylen);
978 err:
979 memset(buf,0,sizeof(buf));
980 if (cipher) crypto_free_cipher_env(cipher);
981 return -1;
984 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
985 * Return -1 on error, or the number of characters used on success.
988 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
990 int len;
991 unsigned char *buf, *cp;
992 len = i2d_RSAPublicKey(pk->key, NULL);
993 if (len < 0 || len > dest_len)
994 return -1;
995 cp = buf = tor_malloc(len+1);
996 len = i2d_RSAPublicKey(pk->key, &cp);
997 if (len < 0) {
998 crypto_log_errors(LOG_WARN,"encoding public key");
999 tor_free(buf);
1000 return -1;
1002 /* We don't encode directly into 'dest', because that would be illegal
1003 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1005 memcpy(dest,buf,len);
1006 tor_free(buf);
1007 return len;
1010 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1011 * success and NULL on failure.
1013 crypto_pk_env_t *
1014 crypto_pk_asn1_decode(const char *str, size_t len)
1016 RSA *rsa;
1017 unsigned char *buf;
1018 /* This ifdef suppresses a type warning. Take out the first case once
1019 * everybody is using openssl 0.9.7 or later.
1021 #if OPENSSL_VERSION_NUMBER < 0x00907000l
1022 unsigned char *cp;
1023 #else
1024 const unsigned char *cp;
1025 #endif
1026 cp = buf = tor_malloc(len);
1027 memcpy(buf,str,len);
1028 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1029 tor_free(buf);
1030 if (!rsa) {
1031 crypto_log_errors(LOG_WARN,"decoding public key");
1032 return NULL;
1034 return _crypto_new_pk_env_rsa(rsa);
1037 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1038 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1039 * Return 0 on success, -1 on failure.
1042 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1044 unsigned char *buf, *bufp;
1045 int len;
1047 len = i2d_RSAPublicKey(pk->key, NULL);
1048 if (len < 0)
1049 return -1;
1050 buf = bufp = tor_malloc(len+1);
1051 len = i2d_RSAPublicKey(pk->key, &bufp);
1052 if (len < 0) {
1053 crypto_log_errors(LOG_WARN,"encoding public key");
1054 tor_free(buf);
1055 return -1;
1057 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1058 tor_free(buf);
1059 return -1;
1061 tor_free(buf);
1062 return 0;
1065 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1066 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1067 * space). Return 0 on success, -1 on failure.
1069 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1070 * of the public key, converted to hexadecimal, in upper case, with a
1071 * space after every four digits.
1073 * If <b>add_space</b> is false, omit the spaces.
1076 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1078 char digest[DIGEST_LEN];
1079 char hexdigest[HEX_DIGEST_LEN+1];
1080 if (crypto_pk_get_digest(pk, digest)) {
1081 return -1;
1083 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1084 if (add_space) {
1085 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
1086 NEVER_TERMINATE)<0)
1087 return -1;
1088 } else {
1089 strcpy(fp_out, hexdigest);
1091 return 0;
1094 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1097 crypto_pk_check_fingerprint_syntax(const char *s)
1099 int i;
1100 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1101 if ((i%5) == 4) {
1102 if (!TOR_ISSPACE(s[i])) return 0;
1103 } else {
1104 if (!TOR_ISXDIGIT(s[i])) return 0;
1107 if (s[FINGERPRINT_LEN]) return 0;
1108 return 1;
1111 /* symmetric crypto */
1113 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1114 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1117 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1119 tor_assert(env);
1121 return crypto_rand(env->key, CIPHER_KEY_LEN);
1124 /** Set the symmetric key for the cipher in <b>env</b> to the first
1125 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1126 * Return 0 on success, -1 on failure.
1129 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1131 tor_assert(env);
1132 tor_assert(key);
1134 if (!env->key)
1135 return -1;
1137 memcpy(env->key, key, CIPHER_KEY_LEN);
1139 return 0;
1142 /** Return a pointer to the key set for the cipher in <b>env</b>.
1144 const char *
1145 crypto_cipher_get_key(crypto_cipher_env_t *env)
1147 return env->key;
1150 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1151 * success, -1 on failure.
1154 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1156 tor_assert(env);
1158 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1159 return 0;
1162 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1163 * success, -1 on failure.
1166 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1168 tor_assert(env);
1170 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1171 return 0;
1174 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1175 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1176 * On failure, return -1.
1179 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1180 const char *from, size_t fromlen)
1182 tor_assert(env);
1183 tor_assert(env->cipher);
1184 tor_assert(from);
1185 tor_assert(fromlen);
1186 tor_assert(to);
1188 aes_crypt(env->cipher, from, fromlen, to);
1189 return 0;
1192 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1193 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1194 * On failure, return -1.
1197 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1198 const char *from, size_t fromlen)
1200 tor_assert(env);
1201 tor_assert(from);
1202 tor_assert(to);
1204 aes_crypt(env->cipher, from, fromlen, to);
1205 return 0;
1208 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1209 * Return 0 on success, -1 on failure.
1212 crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
1214 return crypto_cipher_advance(env, -delta);
1217 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1218 * Return 0 on success, -1 on failure.
1221 crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
1223 aes_adjust_counter(env->cipher, delta);
1224 return 0;
1227 /* SHA-1 */
1229 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1230 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1231 * Return 0 on success, -1 on failure.
1234 crypto_digest(char *digest, const char *m, size_t len)
1236 tor_assert(m);
1237 tor_assert(digest);
1238 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1241 /** Intermediate information about the digest of a stream of data. */
1242 struct crypto_digest_env_t {
1243 SHA_CTX d;
1246 /** Allocate and return a new digest object.
1248 crypto_digest_env_t *
1249 crypto_new_digest_env(void)
1251 crypto_digest_env_t *r;
1252 r = tor_malloc(sizeof(crypto_digest_env_t));
1253 SHA1_Init(&r->d);
1254 return r;
1257 /** Deallocate a digest object.
1259 void
1260 crypto_free_digest_env(crypto_digest_env_t *digest)
1262 tor_free(digest);
1265 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1267 void
1268 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1269 size_t len)
1271 tor_assert(digest);
1272 tor_assert(data);
1273 /* Using the SHA1_*() calls directly means we don't support doing
1274 * sha1 in hardware. But so far the delay of getting the question
1275 * to the hardware, and hearing the answer, is likely higher than
1276 * just doing it ourselves. Hashes are fast.
1278 SHA1_Update(&digest->d, (void*)data, len);
1281 /** Compute the hash of the data that has been passed to the digest
1282 * object; write the first out_len bytes of the result to <b>out</b>.
1283 * <b>out_len</b> must be \<= DIGEST_LEN.
1285 void
1286 crypto_digest_get_digest(crypto_digest_env_t *digest,
1287 char *out, size_t out_len)
1289 static unsigned char r[DIGEST_LEN];
1290 SHA_CTX tmpctx;
1291 tor_assert(digest);
1292 tor_assert(out);
1293 tor_assert(out_len <= DIGEST_LEN);
1294 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1295 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1296 SHA1_Final(r, &tmpctx);
1297 memcpy(out, r, out_len);
1300 /** Allocate and return a new digest object with the same state as
1301 * <b>digest</b>
1303 crypto_digest_env_t *
1304 crypto_digest_dup(const crypto_digest_env_t *digest)
1306 crypto_digest_env_t *r;
1307 tor_assert(digest);
1308 r = tor_malloc(sizeof(crypto_digest_env_t));
1309 memcpy(r,digest,sizeof(crypto_digest_env_t));
1310 return r;
1313 /** Replace the state of the digest object <b>into</b> with the state
1314 * of the digest object <b>from</b>.
1316 void
1317 crypto_digest_assign(crypto_digest_env_t *into,
1318 const crypto_digest_env_t *from)
1320 tor_assert(into);
1321 tor_assert(from);
1322 memcpy(into,from,sizeof(crypto_digest_env_t));
1325 /* DH */
1327 /** Shared P parameter for our DH key exchanged. */
1328 static BIGNUM *dh_param_p = NULL;
1329 /** Shared G parameter for our DH key exchanges. */
1330 static BIGNUM *dh_param_g = NULL;
1332 /** Initialize dh_param_p and dh_param_g if they are not already
1333 * set. */
1334 static void
1335 init_dh_param(void)
1337 BIGNUM *p, *g;
1338 int r;
1339 if (dh_param_p && dh_param_g)
1340 return;
1342 p = BN_new();
1343 g = BN_new();
1344 tor_assert(p);
1345 tor_assert(g);
1347 /* This is from rfc2409, section 6.2. It's a safe prime, and
1348 supposedly it equals:
1349 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1351 r = BN_hex2bn(&p,
1352 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1353 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1354 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1355 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1356 "49286651ECE65381FFFFFFFFFFFFFFFF");
1357 tor_assert(r);
1359 r = BN_set_word(g, 2);
1360 tor_assert(r);
1361 dh_param_p = p;
1362 dh_param_g = g;
1365 #define DH_PRIVATE_KEY_BITS 320
1367 /** Allocate and return a new DH object for a key exchange.
1369 crypto_dh_env_t *
1370 crypto_dh_new(void)
1372 crypto_dh_env_t *res = NULL;
1374 if (!dh_param_p)
1375 init_dh_param();
1377 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1379 if (!(res->dh = DH_new()))
1380 goto err;
1382 if (!(res->dh->p = BN_dup(dh_param_p)))
1383 goto err;
1385 if (!(res->dh->g = BN_dup(dh_param_g)))
1386 goto err;
1388 res->dh->length = DH_PRIVATE_KEY_BITS;
1390 return res;
1391 err:
1392 crypto_log_errors(LOG_WARN, "creating DH object");
1393 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1394 if (res) tor_free(res);
1395 return NULL;
1398 /** Return the length of the DH key in <b>dh</b>, in bytes.
1401 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1403 tor_assert(dh);
1404 return DH_size(dh->dh);
1407 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1408 * success, -1 on failure.
1411 crypto_dh_generate_public(crypto_dh_env_t *dh)
1413 again:
1414 if (!DH_generate_key(dh->dh)) {
1415 crypto_log_errors(LOG_WARN, "generating DH key");
1416 return -1;
1418 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1419 warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-the-universe chances really do happen. Trying again.");
1420 /* Free and clear the keys, so openssl will actually try again. */
1421 BN_free(dh->dh->pub_key);
1422 BN_free(dh->dh->priv_key);
1423 dh->dh->pub_key = dh->dh->priv_key = NULL;
1424 goto again;
1426 return 0;
1429 /** Generate g^x as necessary, and write the g^x for the key exchange
1430 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1431 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1434 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1436 int bytes;
1437 tor_assert(dh);
1438 if (!dh->dh->pub_key) {
1439 if (crypto_dh_generate_public(dh)<0)
1440 return -1;
1443 tor_assert(dh->dh->pub_key);
1444 bytes = BN_num_bytes(dh->dh->pub_key);
1445 tor_assert(bytes >= 0);
1446 if (pubkey_len < (size_t)bytes) {
1447 warn(LD_CRYPTO, "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)", (int) pubkey_len, bytes);
1448 return -1;
1451 memset(pubkey, 0, pubkey_len);
1452 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
1454 return 0;
1457 /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
1458 * okay, or -1 if it's bad.
1459 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
1461 static int
1462 tor_check_dh_key(BIGNUM *bn)
1464 /* There are about 2^116 ways to have a 1024-bit key with <= 16 bits set,
1465 * and similarly for <= 16 bits unset. This is negligible compared to the
1466 * 2^1024 entry keyspace. */
1467 #define MIN_DIFFERING_BITS 16
1468 /* This covers another 2^25 keys, which is still negligible. */
1469 #define MIN_DIST_FROM_EDGE (1<<24)
1470 /* XXXX Note that this is basically voodoo. Really, we only care about 0,
1471 * 1, and p-1. The "number of bits set" business is inherited from some
1472 * dire warnings in the OpenSSH comments. Real Cryptographers assure us
1473 * that these dire warnings are misplaced.
1475 * Still, it can't hurt. -NM We will likely remove all the crud from this
1476 * function in a future version, though. -RD
1478 int i, n_bits, n_set;
1479 BIGNUM *x = NULL;
1480 char *s;
1481 tor_assert(bn);
1482 x = BN_new();
1483 if (!dh_param_p)
1484 init_dh_param();
1485 if (bn->neg) {
1486 warn(LD_CRYPTO, "Rejecting DH key < 0");
1487 return -1;
1489 if (BN_cmp(bn, dh_param_p)>=0) {
1490 warn(LD_CRYPTO, "Rejecting DH key >= p");
1491 return -1;
1493 n_bits = BN_num_bits(bn);
1494 n_set = 0;
1495 for (i=0; i <= n_bits; ++i) {
1496 if (BN_is_bit_set(bn, i))
1497 ++n_set;
1499 if (n_set < MIN_DIFFERING_BITS || n_set >= n_bits-MIN_DIFFERING_BITS) {
1500 warn(LD_CRYPTO, "Too few/many bits in DH key (%d)", n_set);
1501 goto err;
1503 BN_set_word(x, MIN_DIST_FROM_EDGE);
1504 if (BN_cmp(bn,x)<=0) {
1505 warn(LD_CRYPTO, "DH key is too close to 0");
1506 goto err;
1508 BN_copy(x,dh_param_p);
1509 BN_sub_word(x, MIN_DIST_FROM_EDGE);
1510 if (BN_cmp(bn,x)>=0) {
1511 warn(LD_CRYPTO, "DH key is too close to p");
1512 goto err;
1514 BN_free(x);
1515 return 0;
1516 err:
1517 BN_free(x);
1518 s = BN_bn2hex(bn);
1519 warn(LD_CRYPTO, "Rejecting invalid DH key [%s]", s);
1520 OPENSSL_free(s);
1521 return -1;
1524 #undef MIN
1525 #define MIN(a,b) ((a)<(b)?(a):(b))
1526 /** Given a DH key exchange object, and our peer's value of g^y (as a
1527 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1528 * <b>secret_bytes_out</b> bytes of shared key material and write them
1529 * to <b>secret_out</b>. Return the number of bytes generated on success,
1530 * or -1 on failure.
1532 * (We generate key material by computing
1533 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1534 * where || is concatenation.)
1537 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1538 const char *pubkey, size_t pubkey_len,
1539 char *secret_out, size_t secret_bytes_out)
1541 char hash[DIGEST_LEN];
1542 char *secret_tmp = NULL;
1543 BIGNUM *pubkey_bn = NULL;
1544 size_t secret_len=0;
1545 unsigned int i;
1546 int result=0;
1547 tor_assert(dh);
1548 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1550 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
1551 goto error;
1552 if (tor_check_dh_key(pubkey_bn)<0) {
1553 /* Check for invalid public keys. */
1554 warn(LD_CRYPTO,"Rejected invalid g^x");
1555 goto error;
1557 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
1558 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1559 if (result < 0) {
1560 warn(LD_CRYPTO,"DH_compute_key() failed.");
1561 goto error;
1563 secret_len = result;
1564 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1565 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1566 * Leading zeros MUST be preserved, so that ZZ occupies as many
1567 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1568 * bytes long.
1569 * What are the security implications here?
1571 for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
1572 secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
1573 if (crypto_digest(hash, secret_tmp, secret_len+1))
1574 goto error;
1575 memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
1577 secret_len = secret_bytes_out;
1579 goto done;
1580 error:
1581 result = -1;
1582 done:
1583 crypto_log_errors(LOG_WARN, "completing DH handshake");
1584 if (pubkey_bn)
1585 BN_free(pubkey_bn);
1586 tor_free(secret_tmp);
1587 if (result < 0)
1588 return result;
1589 else
1590 return secret_len;
1593 /** Free a DH key exchange object.
1595 void
1596 crypto_dh_free(crypto_dh_env_t *dh)
1598 tor_assert(dh);
1599 tor_assert(dh->dh);
1600 DH_free(dh->dh);
1601 tor_free(dh);
1604 /* random numbers */
1606 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1607 * work for us too. */
1608 #define ADD_ENTROPY 32
1610 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1611 "release".) */
1612 #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1614 /** Seed OpenSSL's random number generator with bytes from the
1615 * operating system. Return 0 on success, -1 on failure.
1618 crypto_seed_rng(void)
1620 char buf[ADD_ENTROPY];
1621 int rand_poll_status;
1623 /* local variables */
1624 #ifdef MS_WINDOWS
1625 static int provider_set = 0;
1626 static HCRYPTPROV provider;
1627 #else
1628 static const char *filenames[] = {
1629 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1631 int fd;
1632 int i, n;
1633 #endif
1635 #if USE_RAND_POLL
1636 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1637 * entropy than we do. We'll try calling that, *and* calling our own entropy
1638 * functions. If one succeeds, we'll accept the RNG as seeded. */
1639 rand_poll_status = RAND_poll();
1640 if (rand_poll_status == 0)
1641 warn(LD_CRYPTO, "RAND_poll() failed.");
1642 #else
1643 rand_poll_status = 0;
1644 #endif
1646 #ifdef MS_WINDOWS
1647 if (!provider_set) {
1648 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
1649 if (GetLastError() != NTE_BAD_KEYSET) {
1650 warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1651 return rand_poll_status ? 0 : -1;
1654 provider_set = 1;
1656 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1657 warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1658 return rand_poll_status ? 0 : -1;
1660 RAND_seed(buf, sizeof(buf));
1661 return 0;
1662 #else
1663 for (i = 0; filenames[i]; ++i) {
1664 fd = open(filenames[i], O_RDONLY, 0);
1665 if (fd<0) continue;
1666 info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1667 n = read_all(fd, buf, sizeof(buf), 0);
1668 close(fd);
1669 if (n != sizeof(buf)) {
1670 warn(LD_CRYPTO, "Error reading from entropy source");
1671 return -1;
1673 RAND_seed(buf, sizeof(buf));
1674 return 0;
1677 warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1678 return rand_poll_status ? 0 : -1;
1679 #endif
1682 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1683 * success, -1 on failure.
1686 crypto_rand(char *to, size_t n)
1688 int r;
1689 tor_assert(to);
1690 r = RAND_bytes((unsigned char*)to, n);
1691 if (r == 0)
1692 crypto_log_errors(LOG_WARN, "generating random data");
1693 return (r == 1) ? 0 : -1;
1696 /** Return a pseudorandom integer, chosen uniformly from the values
1697 * between 0 and max-1. */
1699 crypto_rand_int(unsigned int max)
1701 unsigned int val;
1702 unsigned int cutoff;
1703 tor_assert(max < UINT_MAX);
1704 tor_assert(max > 0); /* don't div by 0 */
1706 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1707 * distribution with clipping at the upper end of unsigned int's
1708 * range.
1710 cutoff = UINT_MAX - (UINT_MAX%max);
1711 while (1) {
1712 crypto_rand((char*)&val, sizeof(val));
1713 if (val < cutoff)
1714 return val % max;
1718 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1720 void *
1721 smartlist_choose(const smartlist_t *sl)
1723 size_t len;
1724 len = smartlist_len(sl);
1725 if (len)
1726 return smartlist_get(sl,crypto_rand_int(len));
1727 return NULL; /* no elements to choose from */
1730 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1731 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1732 * bytes. Return the number of bytes written on success; -1 if
1733 * destlen is too short, or other failure.
1736 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1738 EVP_ENCODE_CTX ctx;
1739 int len, ret;
1741 /* 48 bytes of input -> 64 bytes of output plus newline.
1742 Plus one more byte, in case I'm wrong.
1744 if (destlen < ((srclen/48)+1)*66)
1745 return -1;
1746 if (destlen > SIZE_T_CEILING)
1747 return -1;
1749 EVP_EncodeInit(&ctx);
1750 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len, (unsigned char*)src, srclen);
1751 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1752 ret += len;
1753 return ret;
1756 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1757 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1758 * bytes. Return the number of bytes written on success; -1 if
1759 * destlen is too short, or other failure.
1761 * NOTE: destlen should be a little longer than the amount of data it
1762 * will contain, since we check for sufficient space conservatively.
1763 * Here, "a little" is around 64-ish bytes.
1766 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1768 EVP_ENCODE_CTX ctx;
1769 int len, ret;
1770 /* 64 bytes of input -> *up to* 48 bytes of output.
1771 Plus one more byte, in case I'm wrong.
1773 if (destlen < ((srclen/64)+1)*49)
1774 return -1;
1775 if (destlen > SIZE_T_CEILING)
1776 return -1;
1778 EVP_DecodeInit(&ctx);
1779 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len, (unsigned char*)src, srclen);
1780 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
1781 ret += len;
1782 return ret;
1786 digest_to_base64(char *d64, const char *digest)
1788 char buf[256];
1789 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
1790 buf[BASE64_DIGEST_LEN] = '\0';
1791 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
1792 return 0;
1796 digest_from_base64(char *digest, const char *d64)
1798 char buf_in[BASE64_DIGEST_LEN+3];
1799 char buf[256];
1800 if (strlen(d64) != BASE64_DIGEST_LEN)
1801 return -1;
1802 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
1803 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
1804 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
1805 return -1;
1806 memcpy(digest, buf, DIGEST_LEN);
1807 return 0;
1810 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1811 * that srclen*8 is a multiple of 5.
1813 void
1814 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1816 unsigned int nbits, i, bit, v, u;
1817 nbits = srclen * 8;
1819 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1820 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1821 tor_assert(destlen < SIZE_T_CEILING);
1823 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1824 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1825 v = ((uint8_t)src[bit/8]) << 8;
1826 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1827 /* set u to the 5-bit value at the bit'th bit of src. */
1828 u = (v >> (11-(bit%8))) & 0x1F;
1829 dest[i] = BASE32_CHARS[u];
1831 dest[i] = '\0';
1834 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1835 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1836 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1837 * are a salt; the 9th byte describes how much iteration to do.
1838 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1840 void
1841 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1842 size_t secret_len, const char *s2k_specifier)
1844 crypto_digest_env_t *d;
1845 uint8_t c;
1846 size_t count;
1847 char *tmp;
1848 tor_assert(key_out_len < SIZE_T_CEILING);
1850 #define EXPBIAS 6
1851 c = s2k_specifier[8];
1852 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1853 #undef EXPBIAS
1855 tor_assert(key_out_len <= DIGEST_LEN);
1857 d = crypto_new_digest_env();
1858 tmp = tor_malloc(8+secret_len);
1859 memcpy(tmp,s2k_specifier,8);
1860 memcpy(tmp+8,secret,secret_len);
1861 secret_len += 8;
1862 while (count) {
1863 if (count >= secret_len) {
1864 crypto_digest_add_bytes(d, tmp, secret_len);
1865 count -= secret_len;
1866 } else {
1867 crypto_digest_add_bytes(d, tmp, count);
1868 count = 0;
1871 crypto_digest_get_digest(d, key_out, key_out_len);
1872 tor_free(tmp);
1873 crypto_free_digest_env(d);
1876 #ifdef TOR_IS_MULTITHREADED
1877 static void
1878 _openssl_locking_cb(int mode, int n, const char *file, int line)
1880 if (!_openssl_mutexes)
1881 /* This is not a really good fix for the
1882 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1883 * it can't hurt. */
1884 return;
1885 if (mode & CRYPTO_LOCK)
1886 tor_mutex_acquire(_openssl_mutexes[n]);
1887 else
1888 tor_mutex_release(_openssl_mutexes[n]);
1891 static int
1892 setup_openssl_threading(void)
1894 int i;
1895 int n = CRYPTO_num_locks();
1896 _n_openssl_mutexes = n;
1897 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
1898 for (i=0; i < n; ++i)
1899 _openssl_mutexes[i] = tor_mutex_new();
1900 CRYPTO_set_locking_callback(_openssl_locking_cb);
1901 CRYPTO_set_id_callback(tor_get_thread_id);
1902 return 0;
1904 #else
1905 static int
1906 setup_openssl_threading(void)
1908 return 0;
1910 #endif