Stupid cut-and-paste bug.
[tor.git] / src / common / crypto.c
blobb3f53589c084f00cc5c1c477035d4bd0b2d13282
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[] =
6 "$Id$";
8 /**
9 * \file crypto.c
10 * \brief Wrapper functions to present a consistent interface to
11 * public-key and symmetric cryptography operations from OpenSSL.
12 **/
14 #include "orconfig.h"
16 #ifdef MS_WINDOWS
17 #define WIN32_WINNT 0x400
18 #define _WIN32_WINNT 0x400
19 #define WIN32_LEAN_AND_MEAN
20 #include <windows.h>
21 #include <wincrypt.h>
22 #endif
24 #include <string.h>
26 #include <openssl/err.h>
27 #include <openssl/rsa.h>
28 #include <openssl/pem.h>
29 #include <openssl/evp.h>
30 #include <openssl/rand.h>
31 #include <openssl/opensslv.h>
32 #include <openssl/bn.h>
33 #include <openssl/dh.h>
34 #include <openssl/rsa.h>
35 #include <openssl/dh.h>
36 #include <openssl/conf.h>
38 #include <stdlib.h>
39 #include <assert.h>
40 #include <stdio.h>
41 #include <limits.h>
43 #ifdef HAVE_CTYPE_H
44 #include <ctype.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49 #ifdef HAVE_FCNTL_H
50 #include <fcntl.h>
51 #endif
52 #ifdef HAVE_SYS_FCNTL_H
53 #include <sys/fcntl.h>
54 #endif
56 #include "crypto.h"
57 #include "log.h"
58 #include "aes.h"
59 #include "util.h"
60 #include "container.h"
61 #include "compat.h"
63 #if OPENSSL_VERSION_NUMBER < 0x00905000l
64 #error "We require openssl >= 0.9.5"
65 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
66 #define OPENSSL_095
67 #endif
69 #if OPENSSL_VERSION_NUMBER < 0x00907000l
70 #define OPENSSL_PRE_097
71 #define NO_ENGINES
72 #else
73 #include <openssl/engine.h>
74 #endif
76 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
77 * (and don't indicate errors) in OpenSSL version 0.9.5.
79 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
81 #ifdef OPENSSL_095
82 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
83 #else
84 #define RETURN_SSL_OUTCOME(exp) return !(exp)
85 #endif
87 /** Macro: is k a valid RSA public or private key? */
88 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
89 /** Macro: is k a valid RSA private key? */
90 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
92 #ifdef TOR_IS_MULTITHREADED
93 static tor_mutex_t **_openssl_mutexes = NULL;
94 static int _n_openssl_mutexes = -1;
95 #endif
97 /** A public key, or a public/private keypair. */
98 struct crypto_pk_env_t
100 int refs; /* reference counting so we don't have to copy keys */
101 RSA *key;
104 /** Key and stream information for a stream cipher. */
105 struct crypto_cipher_env_t
107 char key[CIPHER_KEY_LEN];
108 aes_cnt_cipher_t *cipher;
111 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
112 * while we're waiting for the second.*/
113 struct crypto_dh_env_t {
114 DH *dh;
117 /* Prototypes for functions only used by tortls.c */
118 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
119 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
120 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
121 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
123 static int setup_openssl_threading(void);
124 static int tor_check_dh_key(BIGNUM *bn);
126 /** Return the number of bytes added by padding method <b>padding</b>.
128 static INLINE int
129 crypto_get_rsa_padding_overhead(int padding)
131 switch (padding)
133 case RSA_NO_PADDING: return 0;
134 case RSA_PKCS1_OAEP_PADDING: return 42;
135 case RSA_PKCS1_PADDING: return 11;
136 default: tor_assert(0); return -1;
140 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
142 static INLINE int
143 crypto_get_rsa_padding(int padding)
145 switch (padding)
147 case PK_NO_PADDING: return RSA_NO_PADDING;
148 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
149 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
150 default: tor_assert(0); return -1;
154 /** Boolean: has OpenSSL's crypto been initialized? */
155 static int _crypto_global_initialized = 0;
157 /** Log all pending crypto errors at level <b>severity</b>. Use
158 * <b>doing</b> to describe our current activities.
160 static void
161 crypto_log_errors(int severity, const char *doing)
163 unsigned int err;
164 const char *msg, *lib, *func;
165 while ((err = ERR_get_error()) != 0) {
166 msg = (const char*)ERR_reason_error_string(err);
167 lib = (const char*)ERR_lib_error_string(err);
168 func = (const char*)ERR_func_error_string(err);
169 if (!msg) msg = "(null)";
170 if (doing) {
171 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
172 doing, msg, lib, func);
173 } else {
174 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
179 #ifndef NO_ENGINES
180 static void
181 log_engine(const char *fn, ENGINE *e)
183 if (e) {
184 const char *name, *id;
185 name = ENGINE_get_name(e);
186 id = ENGINE_get_id(e);
187 log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
188 name?name:"?", id?id:"?", fn);
189 } else {
190 log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
193 #endif
195 /** Initialize the crypto library. Return 0 on success, -1 on failure.
198 crypto_global_init(int useAccel)
200 if (!_crypto_global_initialized) {
201 ERR_load_crypto_strings();
202 OpenSSL_add_all_algorithms();
203 _crypto_global_initialized = 1;
204 setup_openssl_threading();
205 #ifndef NO_ENGINES
206 if (useAccel) {
207 if (useAccel < 0)
208 warn(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
209 info(LD_CRYPTO, "Initializing OpenSSL engine support.");
210 ENGINE_load_builtin_engines();
211 if (!ENGINE_register_all_complete())
212 return -1;
214 /* XXXX make sure this isn't leaking. */
215 log_engine("RSA", ENGINE_get_default_RSA());
216 log_engine("DH", ENGINE_get_default_DH());
217 log_engine("RAND", ENGINE_get_default_RAND());
218 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
219 log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
220 log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
222 #endif
224 return 0;
227 /** Free crypto resources held by this thread. */
228 void
229 crypto_thread_cleanup(void)
231 #ifndef ENABLE_0119_PARANOIA_B1
232 ERR_remove_state(0);
233 #endif
236 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
239 crypto_global_cleanup(void)
241 EVP_cleanup();
242 #ifndef ENABLE_0119_PARANOIA_C
243 ERR_remove_state(0);
244 #endif
245 ERR_free_strings();
246 #ifndef NO_ENGINES
247 ENGINE_cleanup();
248 #ifndef ENABLE_0119_PARANOIA_C
249 CONF_modules_unload(1);
250 CRYPTO_cleanup_all_ex_data();
251 #endif
252 #endif
253 #ifdef TOR_IS_MULTITHREADED
254 if (_n_openssl_mutexes) {
255 int n = _n_openssl_mutexes;
256 tor_mutex_t **ms = _openssl_mutexes;
257 int i;
258 _openssl_mutexes = NULL;
259 _n_openssl_mutexes = 0;
260 for (i=0;i<n;++i) {
261 tor_mutex_free(ms[i]);
263 tor_free(ms);
265 #endif
266 return 0;
269 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
270 crypto_pk_env_t *
271 _crypto_new_pk_env_rsa(RSA *rsa)
273 crypto_pk_env_t *env;
274 tor_assert(rsa);
275 env = tor_malloc(sizeof(crypto_pk_env_t));
276 env->refs = 1;
277 env->key = rsa;
278 return env;
281 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
282 RSA *
283 _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
285 return env->key;
288 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
289 * private is set, include the private-key portion of the key. */
290 EVP_PKEY *
291 _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
293 RSA *key = NULL;
294 EVP_PKEY *pkey = NULL;
295 tor_assert(env->key);
296 if (private) {
297 if (!(key = RSAPrivateKey_dup(env->key)))
298 goto error;
299 } else {
300 if (!(key = RSAPublicKey_dup(env->key)))
301 goto error;
303 if (!(pkey = EVP_PKEY_new()))
304 goto error;
305 if (!(EVP_PKEY_assign_RSA(pkey, key)))
306 goto error;
307 return pkey;
308 error:
309 if (pkey)
310 EVP_PKEY_free(pkey);
311 if (key)
312 RSA_free(key);
313 return NULL;
316 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
318 DH *
319 _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
321 return dh->dh;
324 /** Allocate and return storage for a public key. The key itself will not yet
325 * be set.
327 crypto_pk_env_t *
328 crypto_new_pk_env(void)
330 RSA *rsa;
332 rsa = RSA_new();
333 if (!rsa) return NULL;
334 return _crypto_new_pk_env_rsa(rsa);
337 /** Release a reference to an asymmetric key; when all the references
338 * are released, free the key.
340 void
341 crypto_free_pk_env(crypto_pk_env_t *env)
343 tor_assert(env);
345 if (--env->refs > 0)
346 return;
348 if (env->key)
349 RSA_free(env->key);
351 tor_free(env);
354 /** Create a new symmetric cipher for a given key and encryption flag
355 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
356 * on failure.
358 crypto_cipher_env_t *
359 crypto_create_init_cipher(const char *key, int encrypt_mode)
361 int r;
362 crypto_cipher_env_t *crypto = NULL;
364 if (! (crypto = crypto_new_cipher_env())) {
365 warn(LD_CRYPTO, "Unable to allocate crypto object");
366 return NULL;
369 if (crypto_cipher_set_key(crypto, key)) {
370 crypto_log_errors(LOG_WARN, "setting symmetric key");
371 goto error;
374 if (encrypt_mode)
375 r = crypto_cipher_encrypt_init_cipher(crypto);
376 else
377 r = crypto_cipher_decrypt_init_cipher(crypto);
379 if (r)
380 goto error;
381 return crypto;
383 error:
384 if (crypto)
385 crypto_free_cipher_env(crypto);
386 return NULL;
389 /** Allocate and return a new symmetric cipher.
391 crypto_cipher_env_t *
392 crypto_new_cipher_env(void)
394 crypto_cipher_env_t *env;
396 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
397 env->cipher = aes_new_cipher();
398 return env;
401 /** Free a symmetric cipher.
403 void
404 crypto_free_cipher_env(crypto_cipher_env_t *env)
406 tor_assert(env);
408 tor_assert(env->cipher);
409 aes_free_cipher(env->cipher);
410 tor_free(env);
413 /* public key crypto */
415 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
416 * success, -1 on failure.
419 crypto_pk_generate_key(crypto_pk_env_t *env)
421 tor_assert(env);
423 if (env->key)
424 RSA_free(env->key);
425 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
426 if (!env->key) {
427 crypto_log_errors(LOG_WARN, "generating RSA key");
428 return -1;
431 return 0;
434 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
435 * Return 0 on success, -1 on failure.
437 static int
438 crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
439 const char *s)
441 BIO *b;
443 tor_assert(env);
444 tor_assert(s);
446 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
447 b = BIO_new_mem_buf((char*)s, -1);
449 if (env->key)
450 RSA_free(env->key);
452 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
454 BIO_free(b);
456 if (!env->key) {
457 crypto_log_errors(LOG_WARN, "Error parsing private key");
458 return -1;
460 return 0;
463 /** Read a PEM-encoded private key from the file named by
464 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
467 crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
468 const char *keyfile)
470 char *contents;
471 int r;
473 /* Read the file into a string. */
474 contents = read_file_to_str(keyfile, 0);
475 if (!contents) {
476 warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
477 return -1;
480 /* Try to parse it. */
481 r = crypto_pk_read_private_key_from_string(env, contents);
482 tor_free(contents);
483 if (r)
484 return -1; /* read_private_key_from_string already warned, so we don't.*/
486 /* Make sure it's valid. */
487 if (crypto_pk_check_key(env) <= 0)
488 return -1;
490 return 0;
493 /** PEM-encode the public key portion of <b>env</b> and write it to a
494 * newly allocated string. On success, set *<b>dest</b> to the new
495 * string, *<b>len</b> to the string's length, and return 0. On
496 * failure, return -1.
499 crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
500 size_t *len)
502 BUF_MEM *buf;
503 BIO *b;
505 tor_assert(env);
506 tor_assert(env->key);
507 tor_assert(dest);
509 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
511 /* Now you can treat b as if it were a file. Just use the
512 * PEM_*_bio_* functions instead of the non-bio variants.
514 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
515 crypto_log_errors(LOG_WARN, "writing public key to string");
516 return -1;
519 BIO_get_mem_ptr(b, &buf);
520 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
521 BIO_free(b);
523 tor_assert(buf->length >= 0);
524 *dest = tor_malloc(buf->length+1);
525 memcpy(*dest, buf->data, buf->length);
526 (*dest)[buf->length] = 0; /* null terminate it */
527 *len = buf->length;
528 BUF_MEM_free(buf);
530 return 0;
533 /** Read a PEM-encoded public key from the first <b>len</b> characters of
534 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
535 * failure.
538 crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
539 size_t len)
541 BIO *b;
543 tor_assert(env);
544 tor_assert(src);
546 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
548 BIO_write(b, src, len);
550 if (env->key)
551 RSA_free(env->key);
552 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
553 BIO_free(b);
554 if (!env->key) {
555 crypto_log_errors(LOG_WARN, "reading public key from string");
556 return -1;
559 return 0;
562 /* Write the private key from 'env' into the file named by 'fname',
563 * PEM-encoded. Return 0 on success, -1 on failure.
566 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
567 const char *fname)
569 BIO *bio;
570 char *cp;
571 long len;
572 char *s;
573 int r;
575 tor_assert(PRIVATE_KEY_OK(env));
577 if (!(bio = BIO_new(BIO_s_mem())))
578 return -1;
579 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
580 == 0) {
581 crypto_log_errors(LOG_WARN, "writing private key");
582 BIO_free(bio);
583 return -1;
585 len = BIO_get_mem_data(bio, &cp);
586 tor_assert(len >= 0);
587 s = tor_malloc(len+1);
588 memcpy(s, cp, len);
589 s[len]='\0';
590 r = write_str_to_file(fname, s, 0);
591 BIO_free(bio);
592 tor_free(s);
593 return r;
596 /** Allocate a new string in *<b>out</b>, containing the public portion of the
597 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
598 * length of the encoded representation on success, and -1 on failure.
600 * <i>This function is for temporary use only. We need a simple
601 * one-line representation for keys to work around a bug in parsing
602 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
603 * in versions of Tor up to 0.0.9pre2.</i>
606 crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
608 int len;
609 char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
610 tor_assert(env);
611 tor_assert(out);
612 len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
613 if (len < 0) {
614 return -1;
616 *out = tor_malloc(len * 2); /* too long, but safe. */
617 if (base64_encode(*out, len*2, buf, len) < 0) {
618 warn(LD_CRYPTO, "Error base64-encoding DER-encoded key");
619 tor_free(*out);
620 return -1;
622 /* Remove spaces */
623 tor_strstrip(*out, " \r\n\t");
624 return strlen(*out);
627 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
628 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
630 * <i>This function is for temporary use only. We need a simple
631 * one-line representation for keys to work around a bug in parsing
632 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
633 * in versions of Tor up to 0.0.9pre2.</i>
635 crypto_pk_env_t *
636 crypto_pk_DER64_decode_public_key(const char *in)
638 char partitioned[PK_BYTES*2 + 16];
639 char buf[PK_BYTES*2];
640 int len;
641 tor_assert(in);
642 len = strlen(in);
644 if (strlen(in) > PK_BYTES*2) {
645 return NULL;
647 /* base64_decode doesn't work unless we insert linebreaks every 64
648 * characters. how dumb. */
649 if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
650 ALWAYS_TERMINATE))
651 return NULL;
652 len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
653 if (len<0) {
654 warn(LD_CRYPTO,"Error base-64 decoding key");
655 return NULL;
657 return crypto_pk_asn1_decode(buf, len);
660 /** Return true iff <b>env</b> has a valid key.
663 crypto_pk_check_key(crypto_pk_env_t *env)
665 int r;
666 tor_assert(env);
668 r = RSA_check_key(env->key);
669 if (r <= 0)
670 crypto_log_errors(LOG_WARN,"checking RSA key");
671 return r;
674 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
675 * if a==b, and 1 if a\>b.
678 crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
680 int result;
682 if (!a || !b)
683 return -1;
685 if (!a->key || !b->key)
686 return -1;
688 tor_assert(PUBLIC_KEY_OK(a));
689 tor_assert(PUBLIC_KEY_OK(b));
690 result = BN_cmp((a->key)->n, (b->key)->n);
691 if (result)
692 return result;
693 return BN_cmp((a->key)->e, (b->key)->e);
696 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
697 size_t
698 crypto_pk_keysize(crypto_pk_env_t *env)
700 tor_assert(env);
701 tor_assert(env->key);
703 return (size_t) RSA_size(env->key);
706 /** Increase the reference count of <b>env</b>, and return it.
708 crypto_pk_env_t *
709 crypto_pk_dup_key(crypto_pk_env_t *env)
711 tor_assert(env);
712 tor_assert(env->key);
714 env->refs++;
715 return env;
718 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
719 * in <b>env</b>, using the padding method <b>padding</b>. On success,
720 * write the result to <b>to</b>, and return the number of bytes
721 * written. On failure, return -1.
724 crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
725 const char *from, size_t fromlen, int padding)
727 int r;
728 tor_assert(env);
729 tor_assert(from);
730 tor_assert(to);
732 r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
733 env->key, crypto_get_rsa_padding(padding));
734 if (r<0) {
735 crypto_log_errors(LOG_WARN, "performing RSA encryption");
736 return -1;
738 return r;
741 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
742 * in <b>env</b>, using the padding method <b>padding</b>. On success,
743 * write the result to <b>to</b>, and return the number of bytes
744 * written. On failure, return -1.
747 crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
748 const char *from, size_t fromlen,
749 int padding, int warnOnFailure)
751 int r;
752 tor_assert(env);
753 tor_assert(from);
754 tor_assert(to);
755 tor_assert(env->key);
756 if (!env->key->p)
757 /* Not a private key */
758 return -1;
760 r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
761 env->key, crypto_get_rsa_padding(padding));
763 if (r<0) {
764 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
765 "performing RSA decryption");
766 return -1;
768 return r;
771 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
772 * public key in <b>env</b>, using PKCS1 padding. On success, write the
773 * signed data to <b>to</b>, and return the number of bytes written.
774 * On failure, return -1.
777 crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
778 const char *from, size_t fromlen)
780 int r;
781 tor_assert(env);
782 tor_assert(from);
783 tor_assert(to);
784 r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
785 env->key, RSA_PKCS1_PADDING);
787 if (r<0) {
788 crypto_log_errors(LOG_WARN, "checking RSA signature");
789 return -1;
791 return r;
794 /** Check a siglen-byte long signature at <b>sig</b> against
795 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
796 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
797 * SHA1(data). Else return -1.
800 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
801 int datalen, const char *sig, int siglen)
803 char digest[DIGEST_LEN];
804 char buf[PK_BYTES+1];
805 int r;
807 tor_assert(env);
808 tor_assert(data);
809 tor_assert(sig);
811 if (crypto_digest(digest,data,datalen)<0) {
812 warn(LD_CRYPTO, "couldn't compute digest");
813 return -1;
815 r = crypto_pk_public_checksig(env,buf,sig,siglen);
816 if (r != DIGEST_LEN) {
817 warn(LD_CRYPTO, "Invalid signature");
818 return -1;
820 if (memcmp(buf, digest, DIGEST_LEN)) {
821 warn(LD_CRYPTO, "Signature mismatched with digest.");
822 return -1;
825 return 0;
828 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
829 * <b>env</b>, using PKCS1 padding. On success, write the signature to
830 * <b>to</b>, and return the number of bytes written. On failure, return
831 * -1.
834 crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
835 const char *from, size_t fromlen)
837 int r;
838 tor_assert(env);
839 tor_assert(from);
840 tor_assert(to);
841 if (!env->key->p)
842 /* Not a private key */
843 return -1;
845 r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
846 env->key, RSA_PKCS1_PADDING);
847 if (r<0) {
848 crypto_log_errors(LOG_WARN, "generating RSA signature");
849 return -1;
851 return r;
854 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
855 * <b>from</b>; sign the data with the private key in <b>env</b>, and
856 * store it in <b>to</b>. Return the number of bytes written on
857 * success, and -1 on failure.
860 crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
861 const char *from, size_t fromlen)
863 char digest[DIGEST_LEN];
864 if (crypto_digest(digest,from,fromlen)<0)
865 return -1;
866 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
869 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
870 * bytes of data from <b>from</b>, with padding type 'padding',
871 * storing the results on <b>to</b>.
873 * If no padding is used, the public key must be at least as large as
874 * <b>from</b>.
876 * Returns the number of bytes written on success, -1 on failure.
878 * The encrypted data consists of:
879 * - The source data, padded and encrypted with the public key, if the
880 * padded source data is no longer than the public key, and <b>force</b>
881 * is false, OR
882 * - The beginning of the source data prefixed with a 16-byte symmetric key,
883 * padded and encrypted with the public key; followed by the rest of
884 * the source data encrypted in AES-CTR mode with the symmetric key.
887 crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
888 char *to,
889 const char *from,
890 size_t fromlen,
891 int padding, int force)
893 int overhead, outlen, r, symlen;
894 size_t pkeylen;
895 crypto_cipher_env_t *cipher = NULL;
896 char buf[PK_BYTES+1];
898 tor_assert(env);
899 tor_assert(from);
900 tor_assert(to);
902 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
903 pkeylen = crypto_pk_keysize(env);
905 if (padding == PK_NO_PADDING && fromlen < pkeylen)
906 return -1;
908 if (!force && fromlen+overhead <= pkeylen) {
909 /* It all fits in a single encrypt. */
910 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
912 cipher = crypto_new_cipher_env();
913 if (!cipher) return -1;
914 if (crypto_cipher_generate_key(cipher)<0)
915 goto err;
916 /* You can't just run around RSA-encrypting any bitstream: if it's
917 * greater than the RSA key, then OpenSSL will happily encrypt, and
918 * later decrypt to the wrong value. So we set the first bit of
919 * 'cipher->key' to 0 if we aren't padding. This means that our
920 * symmetric key is really only 127 bits.
922 if (padding == PK_NO_PADDING)
923 cipher->key[0] &= 0x7f;
924 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
925 goto err;
926 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
927 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
929 /* Length of symmetrically encrypted data. */
930 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
932 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
933 if (outlen!=(int)pkeylen) {
934 goto err;
936 r = crypto_cipher_encrypt(cipher, to+outlen,
937 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
939 if (r<0) goto err;
940 memset(buf, 0, sizeof(buf));
941 crypto_free_cipher_env(cipher);
942 return outlen + symlen;
943 err:
944 memset(buf, 0, sizeof(buf));
945 if (cipher) crypto_free_cipher_env(cipher);
946 return -1;
949 /** Invert crypto_pk_public_hybrid_encrypt. */
951 crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
952 char *to,
953 const char *from,
954 size_t fromlen,
955 int padding, int warnOnFailure)
957 int overhead, outlen, r;
958 size_t pkeylen;
959 crypto_cipher_env_t *cipher = NULL;
960 char buf[PK_BYTES+1];
962 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
963 pkeylen = crypto_pk_keysize(env);
965 if (fromlen <= pkeylen) {
966 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
967 warnOnFailure);
969 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
970 warnOnFailure);
971 if (outlen<0) {
972 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
973 "Error decrypting public-key data");
974 return -1;
976 if (outlen < CIPHER_KEY_LEN) {
977 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
978 "No room for a symmetric key");
979 return -1;
981 cipher = crypto_create_init_cipher(buf, 0);
982 if (!cipher) {
983 return -1;
985 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
986 outlen -= CIPHER_KEY_LEN;
987 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
988 if (r<0)
989 goto err;
990 memset(buf,0,sizeof(buf));
991 crypto_free_cipher_env(cipher);
992 return outlen + (fromlen-pkeylen);
993 err:
994 memset(buf,0,sizeof(buf));
995 if (cipher) crypto_free_cipher_env(cipher);
996 return -1;
999 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1000 * Return -1 on error, or the number of characters used on success.
1003 crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
1005 int len;
1006 unsigned char *buf, *cp;
1007 len = i2d_RSAPublicKey(pk->key, NULL);
1008 if (len < 0 || len > dest_len)
1009 return -1;
1010 cp = buf = tor_malloc(len+1);
1011 len = i2d_RSAPublicKey(pk->key, &cp);
1012 if (len < 0) {
1013 crypto_log_errors(LOG_WARN,"encoding public key");
1014 tor_free(buf);
1015 return -1;
1017 /* We don't encode directly into 'dest', because that would be illegal
1018 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1020 memcpy(dest,buf,len);
1021 tor_free(buf);
1022 return len;
1025 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1026 * success and NULL on failure.
1028 crypto_pk_env_t *
1029 crypto_pk_asn1_decode(const char *str, size_t len)
1031 RSA *rsa;
1032 unsigned char *buf;
1033 /* This ifdef suppresses a type warning. Take out the first case once
1034 * everybody is using openssl 0.9.7 or later.
1036 #if OPENSSL_VERSION_NUMBER < 0x00907000l
1037 unsigned char *cp;
1038 #else
1039 const unsigned char *cp;
1040 #endif
1041 cp = buf = tor_malloc(len);
1042 memcpy(buf,str,len);
1043 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1044 tor_free(buf);
1045 if (!rsa) {
1046 crypto_log_errors(LOG_WARN,"decoding public key");
1047 return NULL;
1049 return _crypto_new_pk_env_rsa(rsa);
1052 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1053 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1054 * Return 0 on success, -1 on failure.
1057 crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
1059 unsigned char *buf, *bufp;
1060 int len;
1062 len = i2d_RSAPublicKey(pk->key, NULL);
1063 if (len < 0)
1064 return -1;
1065 buf = bufp = tor_malloc(len+1);
1066 len = i2d_RSAPublicKey(pk->key, &bufp);
1067 if (len < 0) {
1068 crypto_log_errors(LOG_WARN,"encoding public key");
1069 tor_free(buf);
1070 return -1;
1072 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1073 tor_free(buf);
1074 return -1;
1076 tor_free(buf);
1077 return 0;
1080 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1081 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1082 * space). Return 0 on success, -1 on failure.
1084 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1085 * of the public key, converted to hexadecimal, in upper case, with a
1086 * space after every four digits.
1088 * If <b>add_space</b> is false, omit the spaces.
1091 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
1093 char digest[DIGEST_LEN];
1094 char hexdigest[HEX_DIGEST_LEN+1];
1095 if (crypto_pk_get_digest(pk, digest)) {
1096 return -1;
1098 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1099 if (add_space) {
1100 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
1101 NEVER_TERMINATE)<0)
1102 return -1;
1103 } else {
1104 strcpy(fp_out, hexdigest);
1106 return 0;
1109 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
1112 crypto_pk_check_fingerprint_syntax(const char *s)
1114 int i;
1115 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1116 if ((i%5) == 4) {
1117 if (!TOR_ISSPACE(s[i])) return 0;
1118 } else {
1119 if (!TOR_ISXDIGIT(s[i])) return 0;
1122 if (s[FINGERPRINT_LEN]) return 0;
1123 return 1;
1126 /* symmetric crypto */
1128 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1129 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1132 crypto_cipher_generate_key(crypto_cipher_env_t *env)
1134 tor_assert(env);
1136 return crypto_rand(env->key, CIPHER_KEY_LEN);
1139 /** Set the symmetric key for the cipher in <b>env</b> to the first
1140 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1141 * Return 0 on success, -1 on failure.
1144 crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
1146 tor_assert(env);
1147 tor_assert(key);
1149 if (!env->key)
1150 return -1;
1152 memcpy(env->key, key, CIPHER_KEY_LEN);
1154 return 0;
1157 /** Return a pointer to the key set for the cipher in <b>env</b>.
1159 const char *
1160 crypto_cipher_get_key(crypto_cipher_env_t *env)
1162 return env->key;
1165 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1166 * success, -1 on failure.
1169 crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1171 tor_assert(env);
1173 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1174 return 0;
1177 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1178 * success, -1 on failure.
1181 crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1183 tor_assert(env);
1185 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1186 return 0;
1189 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1190 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1191 * On failure, return -1.
1194 crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
1195 const char *from, size_t fromlen)
1197 tor_assert(env);
1198 tor_assert(env->cipher);
1199 tor_assert(from);
1200 tor_assert(fromlen);
1201 tor_assert(to);
1203 aes_crypt(env->cipher, from, fromlen, to);
1204 return 0;
1207 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1208 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1209 * On failure, return -1.
1212 crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
1213 const char *from, size_t fromlen)
1215 tor_assert(env);
1216 tor_assert(from);
1217 tor_assert(to);
1219 aes_crypt(env->cipher, from, fromlen, to);
1220 return 0;
1223 /* SHA-1 */
1225 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1226 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1227 * Return 0 on success, -1 on failure.
1230 crypto_digest(char *digest, const char *m, size_t len)
1232 tor_assert(m);
1233 tor_assert(digest);
1234 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1237 /** Intermediate information about the digest of a stream of data. */
1238 struct crypto_digest_env_t {
1239 SHA_CTX d;
1242 /** Allocate and return a new digest object.
1244 crypto_digest_env_t *
1245 crypto_new_digest_env(void)
1247 crypto_digest_env_t *r;
1248 r = tor_malloc(sizeof(crypto_digest_env_t));
1249 SHA1_Init(&r->d);
1250 return r;
1253 /** Deallocate a digest object.
1255 void
1256 crypto_free_digest_env(crypto_digest_env_t *digest)
1258 tor_free(digest);
1261 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1263 void
1264 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1265 size_t len)
1267 tor_assert(digest);
1268 tor_assert(data);
1269 /* Using the SHA1_*() calls directly means we don't support doing
1270 * sha1 in hardware. But so far the delay of getting the question
1271 * to the hardware, and hearing the answer, is likely higher than
1272 * just doing it ourselves. Hashes are fast.
1274 SHA1_Update(&digest->d, (void*)data, len);
1277 /** Compute the hash of the data that has been passed to the digest
1278 * object; write the first out_len bytes of the result to <b>out</b>.
1279 * <b>out_len</b> must be \<= DIGEST_LEN.
1281 void
1282 crypto_digest_get_digest(crypto_digest_env_t *digest,
1283 char *out, size_t out_len)
1285 static unsigned char r[DIGEST_LEN];
1286 SHA_CTX tmpctx;
1287 tor_assert(digest);
1288 tor_assert(out);
1289 tor_assert(out_len <= DIGEST_LEN);
1290 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1291 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1292 SHA1_Final(r, &tmpctx);
1293 memcpy(out, r, out_len);
1296 /** Allocate and return a new digest object with the same state as
1297 * <b>digest</b>
1299 crypto_digest_env_t *
1300 crypto_digest_dup(const crypto_digest_env_t *digest)
1302 crypto_digest_env_t *r;
1303 tor_assert(digest);
1304 r = tor_malloc(sizeof(crypto_digest_env_t));
1305 memcpy(r,digest,sizeof(crypto_digest_env_t));
1306 return r;
1309 /** Replace the state of the digest object <b>into</b> with the state
1310 * of the digest object <b>from</b>.
1312 void
1313 crypto_digest_assign(crypto_digest_env_t *into,
1314 const crypto_digest_env_t *from)
1316 tor_assert(into);
1317 tor_assert(from);
1318 memcpy(into,from,sizeof(crypto_digest_env_t));
1321 /* DH */
1323 /** Shared P parameter for our DH key exchanged. */
1324 static BIGNUM *dh_param_p = NULL;
1325 /** Shared G parameter for our DH key exchanges. */
1326 static BIGNUM *dh_param_g = NULL;
1328 /** Initialize dh_param_p and dh_param_g if they are not already
1329 * set. */
1330 static void
1331 init_dh_param(void)
1333 BIGNUM *p, *g;
1334 int r;
1335 if (dh_param_p && dh_param_g)
1336 return;
1338 p = BN_new();
1339 g = BN_new();
1340 tor_assert(p);
1341 tor_assert(g);
1343 /* This is from rfc2409, section 6.2. It's a safe prime, and
1344 supposedly it equals:
1345 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1347 r = BN_hex2bn(&p,
1348 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1349 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1350 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1351 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1352 "49286651ECE65381FFFFFFFFFFFFFFFF");
1353 tor_assert(r);
1355 r = BN_set_word(g, 2);
1356 tor_assert(r);
1357 dh_param_p = p;
1358 dh_param_g = g;
1361 #define DH_PRIVATE_KEY_BITS 320
1363 /** Allocate and return a new DH object for a key exchange.
1365 crypto_dh_env_t *
1366 crypto_dh_new(void)
1368 crypto_dh_env_t *res = NULL;
1370 if (!dh_param_p)
1371 init_dh_param();
1373 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1375 if (!(res->dh = DH_new()))
1376 goto err;
1378 if (!(res->dh->p = BN_dup(dh_param_p)))
1379 goto err;
1381 if (!(res->dh->g = BN_dup(dh_param_g)))
1382 goto err;
1384 #ifndef ENABLE_0119_PARANOIA_A
1385 res->dh->length = DH_PRIVATE_KEY_BITS;
1386 #endif
1388 return res;
1389 err:
1390 crypto_log_errors(LOG_WARN, "creating DH object");
1391 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1392 if (res) tor_free(res);
1393 return NULL;
1396 /** Return the length of the DH key in <b>dh</b>, in bytes.
1399 crypto_dh_get_bytes(crypto_dh_env_t *dh)
1401 tor_assert(dh);
1402 return DH_size(dh->dh);
1405 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1406 * success, -1 on failure.
1409 crypto_dh_generate_public(crypto_dh_env_t *dh)
1411 again:
1412 if (!DH_generate_key(dh->dh)) {
1413 crypto_log_errors(LOG_WARN, "generating DH key");
1414 return -1;
1416 if (tor_check_dh_key(dh->dh->pub_key)<0) {
1417 warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
1418 "the-universe chances really do happen. Trying again.");
1419 /* Free and clear the keys, so openssl will actually try again. */
1420 BN_free(dh->dh->pub_key);
1421 BN_free(dh->dh->priv_key);
1422 dh->dh->pub_key = dh->dh->priv_key = NULL;
1423 goto again;
1425 return 0;
1428 /** Generate g^x as necessary, and write the g^x for the key exchange
1429 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1430 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1433 crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1435 int bytes;
1436 tor_assert(dh);
1437 if (!dh->dh->pub_key) {
1438 if (crypto_dh_generate_public(dh)<0)
1439 return -1;
1442 tor_assert(dh->dh->pub_key);
1443 bytes = BN_num_bytes(dh->dh->pub_key);
1444 tor_assert(bytes >= 0);
1445 if (pubkey_len < (size_t)bytes) {
1446 warn(LD_CRYPTO, "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
1447 (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 (in the subgroup [2,p-2]), 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 BIGNUM *x;
1465 char *s;
1466 tor_assert(bn);
1467 x = BN_new();
1468 tor_assert(x);
1469 if (!dh_param_p)
1470 init_dh_param();
1471 BN_set_word(x, 1);
1472 if (BN_cmp(bn,x)<=0) {
1473 warn(LD_CRYPTO, "DH key must be at least 2.");
1474 goto err;
1476 BN_copy(x,dh_param_p);
1477 BN_sub_word(x, 1);
1478 if (BN_cmp(bn,x)>=0) {
1479 warn(LD_CRYPTO, "DH key must be at most p-2.");
1480 goto err;
1482 BN_free(x);
1483 return 0;
1484 err:
1485 BN_free(x);
1486 s = BN_bn2hex(bn);
1487 warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
1488 OPENSSL_free(s);
1489 return -1;
1492 #undef MIN
1493 #define MIN(a,b) ((a)<(b)?(a):(b))
1494 /** Given a DH key exchange object, and our peer's value of g^y (as a
1495 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1496 * <b>secret_bytes_out</b> bytes of shared key material and write them
1497 * to <b>secret_out</b>. Return the number of bytes generated on success,
1498 * or -1 on failure.
1500 * (We generate key material by computing
1501 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1502 * where || is concatenation.)
1505 crypto_dh_compute_secret(crypto_dh_env_t *dh,
1506 const char *pubkey, size_t pubkey_len,
1507 char *secret_out, size_t secret_bytes_out)
1509 char *secret_tmp = NULL;
1510 BIGNUM *pubkey_bn = NULL;
1511 size_t secret_len=0;
1512 int result=0;
1513 tor_assert(dh);
1514 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1516 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
1517 goto error;
1518 if (tor_check_dh_key(pubkey_bn)<0) {
1519 /* Check for invalid public keys. */
1520 warn(LD_CRYPTO,"Rejected invalid g^x");
1521 goto error;
1523 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
1524 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
1525 if (result < 0) {
1526 warn(LD_CRYPTO,"DH_compute_key() failed.");
1527 goto error;
1529 secret_len = result;
1530 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1531 /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
1532 * Leading zeros MUST be preserved, so that ZZ occupies as many
1533 * octets as p. For instance, if p is 1024 bits, ZZ should be 128
1534 * bytes long.
1535 * What are the security implications here?
1537 if (crypto_expand_key_material(secret_tmp, secret_len,
1538 secret_out, secret_bytes_out)<0)
1539 goto error;
1540 secret_len = secret_bytes_out;
1542 goto done;
1543 error:
1544 result = -1;
1545 done:
1546 crypto_log_errors(LOG_WARN, "completing DH handshake");
1547 if (pubkey_bn)
1548 BN_free(pubkey_bn);
1549 tor_free(secret_tmp);
1550 if (result < 0)
1551 return result;
1552 else
1553 return secret_len;
1556 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
1557 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
1558 * <b>key_out</b> by taking the first key_out_len bytes of
1559 * H(K | [00]) | H(K | [01]) | ....
1561 * Return 0 on success, -1 on failure.
1564 crypto_expand_key_material(const char *key_in, size_t key_in_len,
1565 char *key_out, size_t key_out_len)
1567 int i;
1568 char *cp, *tmp = tor_malloc(key_in_len+1);
1569 char digest[DIGEST_LEN];
1571 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
1572 tor_assert(key_out_len <= DIGEST_LEN*256);
1574 memcpy(tmp, key_in, key_in_len);
1575 for (cp = key_out, i=0; key_out_len; ++i, cp += DIGEST_LEN) {
1576 tmp[key_in_len] = i;
1577 if (crypto_digest(digest, tmp, key_in_len+1))
1578 goto err;
1579 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len));
1580 if (key_out_len < DIGEST_LEN)
1581 break;
1582 key_out_len -= DIGEST_LEN;
1584 memset(tmp, 0, key_in_len+1);
1585 tor_free(tmp);
1586 return 0;
1588 err:
1589 memset(tmp, 0, key_in_len+1);
1590 tor_free(tmp);
1591 return -1;
1594 /** Free a DH key exchange object.
1596 void
1597 crypto_dh_free(crypto_dh_env_t *dh)
1599 tor_assert(dh);
1600 tor_assert(dh->dh);
1601 DH_free(dh->dh);
1602 tor_free(dh);
1605 /* random numbers */
1607 /* This is how much entropy OpenSSL likes to add right now, so maybe it will
1608 * work for us too. */
1609 #define ADD_ENTROPY 32
1611 /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
1612 "release".) */
1613 #ifndef ENABLE_0119_PARANOIA_B2
1614 #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
1615 #else
1616 #define USE_RAND_POLL 0
1617 #endif
1619 /** Seed OpenSSL's random number generator with bytes from the
1620 * operating system. Return 0 on success, -1 on failure.
1623 crypto_seed_rng(void)
1625 char buf[ADD_ENTROPY];
1626 int rand_poll_status;
1628 /* local variables */
1629 #ifdef MS_WINDOWS
1630 static int provider_set = 0;
1631 static HCRYPTPROV provider;
1632 #else
1633 static const char *filenames[] = {
1634 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1636 int fd;
1637 int i, n;
1638 #endif
1640 #if USE_RAND_POLL
1641 /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
1642 * entropy than we do. We'll try calling that, *and* calling our own entropy
1643 * functions. If one succeeds, we'll accept the RNG as seeded. */
1644 rand_poll_status = RAND_poll();
1645 if (rand_poll_status == 0)
1646 warn(LD_CRYPTO, "RAND_poll() failed.");
1647 #else
1648 rand_poll_status = 0;
1649 #endif
1651 #ifdef MS_WINDOWS
1652 if (!provider_set) {
1653 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1654 CRYPT_VERIFYCONTEXT)) {
1655 if (GetLastError() != NTE_BAD_KEYSET) {
1656 warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
1657 return rand_poll_status ? 0 : -1;
1660 provider_set = 1;
1662 if (!CryptGenRandom(provider, sizeof(buf), buf)) {
1663 warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
1664 return rand_poll_status ? 0 : -1;
1666 RAND_seed(buf, sizeof(buf));
1667 return 0;
1668 #else
1669 for (i = 0; filenames[i]; ++i) {
1670 fd = open(filenames[i], O_RDONLY, 0);
1671 if (fd<0) continue;
1672 info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
1673 n = read_all(fd, buf, sizeof(buf), 0);
1674 close(fd);
1675 if (n != sizeof(buf)) {
1676 warn(LD_CRYPTO,
1677 "Error reading from entropy source (read only %d bytes).", n);
1678 return -1;
1680 RAND_seed(buf, sizeof(buf));
1681 return 0;
1684 warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
1685 return rand_poll_status ? 0 : -1;
1686 #endif
1689 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1690 * success, -1 on failure.
1693 crypto_rand(char *to, size_t n)
1695 int r;
1696 tor_assert(to);
1697 r = RAND_bytes((unsigned char*)to, n);
1698 if (r == 0)
1699 crypto_log_errors(LOG_WARN, "generating random data");
1700 return (r == 1) ? 0 : -1;
1703 /** Return a pseudorandom integer, chosen uniformly from the values
1704 * between 0 and max-1. */
1706 crypto_rand_int(unsigned int max)
1708 unsigned int val;
1709 unsigned int cutoff;
1710 tor_assert(max < UINT_MAX);
1711 tor_assert(max > 0); /* don't div by 0 */
1713 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1714 * distribution with clipping at the upper end of unsigned int's
1715 * range.
1717 cutoff = UINT_MAX - (UINT_MAX%max);
1718 while (1) {
1719 crypto_rand((char*)&val, sizeof(val));
1720 if (val < cutoff)
1721 return val % max;
1725 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1727 void *
1728 smartlist_choose(const smartlist_t *sl)
1730 size_t len;
1731 len = smartlist_len(sl);
1732 if (len)
1733 return smartlist_get(sl,crypto_rand_int(len));
1734 return NULL; /* no elements to choose from */
1737 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1738 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1739 * bytes. Return the number of bytes written on success; -1 if
1740 * destlen is too short, or other failure.
1743 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1745 EVP_ENCODE_CTX ctx;
1746 int len, ret;
1748 /* 48 bytes of input -> 64 bytes of output plus newline.
1749 Plus one more byte, in case I'm wrong.
1751 if (destlen < ((srclen/48)+1)*66)
1752 return -1;
1753 if (destlen > SIZE_T_CEILING)
1754 return -1;
1756 EVP_EncodeInit(&ctx);
1757 EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
1758 (unsigned char*)src, srclen);
1759 EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
1760 ret += len;
1761 return ret;
1764 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1765 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1766 * bytes. Return the number of bytes written on success; -1 if
1767 * destlen is too short, or other failure.
1769 * NOTE: destlen should be a little longer than the amount of data it
1770 * will contain, since we check for sufficient space conservatively.
1771 * Here, "a little" is around 64-ish bytes.
1774 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1776 EVP_ENCODE_CTX ctx;
1777 int len, ret;
1778 /* 64 bytes of input -> *up to* 48 bytes of output.
1779 Plus one more byte, in case I'm wrong.
1781 if (destlen < ((srclen/64)+1)*49)
1782 return -1;
1783 if (destlen > SIZE_T_CEILING)
1784 return -1;
1786 EVP_DecodeInit(&ctx);
1787 EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
1788 (unsigned char*)src, srclen);
1789 EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
1790 ret += len;
1791 return ret;
1795 digest_to_base64(char *d64, const char *digest)
1797 char buf[256];
1798 base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
1799 buf[BASE64_DIGEST_LEN] = '\0';
1800 memcpy(d64, buf, BASE64_DIGEST_LEN+1);
1801 return 0;
1805 digest_from_base64(char *digest, const char *d64)
1807 char buf_in[BASE64_DIGEST_LEN+3];
1808 char buf[256];
1809 if (strlen(d64) != BASE64_DIGEST_LEN)
1810 return -1;
1811 memcpy(buf_in, d64, BASE64_DIGEST_LEN);
1812 memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
1813 if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
1814 return -1;
1815 memcpy(digest, buf, DIGEST_LEN);
1816 return 0;
1819 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1820 * that srclen*8 is a multiple of 5.
1822 void
1823 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1825 unsigned int nbits, i, bit, v, u;
1826 nbits = srclen * 8;
1828 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1829 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1830 tor_assert(destlen < SIZE_T_CEILING);
1832 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1833 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1834 v = ((uint8_t)src[bit/8]) << 8;
1835 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1836 /* set u to the 5-bit value at the bit'th bit of src. */
1837 u = (v >> (11-(bit%8))) & 0x1F;
1838 dest[i] = BASE32_CHARS[u];
1840 dest[i] = '\0';
1843 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1844 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1845 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1846 * are a salt; the 9th byte describes how much iteration to do.
1847 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1849 void
1850 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1851 size_t secret_len, const char *s2k_specifier)
1853 crypto_digest_env_t *d;
1854 uint8_t c;
1855 size_t count;
1856 char *tmp;
1857 tor_assert(key_out_len < SIZE_T_CEILING);
1859 #define EXPBIAS 6
1860 c = s2k_specifier[8];
1861 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1862 #undef EXPBIAS
1864 tor_assert(key_out_len <= DIGEST_LEN);
1866 d = crypto_new_digest_env();
1867 tmp = tor_malloc(8+secret_len);
1868 memcpy(tmp,s2k_specifier,8);
1869 memcpy(tmp+8,secret,secret_len);
1870 secret_len += 8;
1871 while (count) {
1872 if (count >= secret_len) {
1873 crypto_digest_add_bytes(d, tmp, secret_len);
1874 count -= secret_len;
1875 } else {
1876 crypto_digest_add_bytes(d, tmp, count);
1877 count = 0;
1880 crypto_digest_get_digest(d, key_out, key_out_len);
1881 tor_free(tmp);
1882 crypto_free_digest_env(d);
1885 #ifdef TOR_IS_MULTITHREADED
1886 static void
1887 _openssl_locking_cb(int mode, int n, const char *file, int line)
1889 if (!_openssl_mutexes)
1890 /* This is not a really good fix for the
1891 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1892 * it can't hurt. */
1893 return;
1894 if (mode & CRYPTO_LOCK)
1895 tor_mutex_acquire(_openssl_mutexes[n]);
1896 else
1897 tor_mutex_release(_openssl_mutexes[n]);
1900 static int
1901 setup_openssl_threading(void)
1903 int i;
1904 int n = CRYPTO_num_locks();
1905 _n_openssl_mutexes = n;
1906 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
1907 for (i=0; i < n; ++i)
1908 _openssl_mutexes[i] = tor_mutex_new();
1909 CRYPTO_set_locking_callback(_openssl_locking_cb);
1910 CRYPTO_set_id_callback(tor_get_thread_id);
1911 return 0;
1913 #else
1914 static int
1915 setup_openssl_threading(void)
1917 return 0;
1919 #endif