update copyright notices.
[tor.git] / src / common / crypto.c
blob91af2d58d672146a00f246b1162929adfcbff607
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
10 * \brief Low-level cryptographic functions.
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>
36 #include <stdlib.h>
37 #include <assert.h>
38 #include <stdio.h>
39 #include <limits.h>
41 #ifdef HAVE_CTYPE_H
42 #include <ctype.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif
50 #ifdef HAVE_SYS_FCNTL_H
51 #include <sys/fcntl.h>
52 #endif
54 #include "crypto.h"
55 #include "log.h"
56 #include "aes.h"
57 #include "util.h"
58 #include "container.h"
59 #include "compat.h"
61 #if OPENSSL_VERSION_NUMBER < 0x00905000l
62 #error "We require openssl >= 0.9.5"
63 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
64 #define OPENSSL_095
65 #endif
67 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
68 * (and don't indicate errors) in OpenSSL version 0.9.5.
70 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
72 #ifdef OPENSSL_095
73 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
74 #else
75 #define RETURN_SSL_OUTCOME(exp) return !(exp)
76 #endif
78 /** Macro: is k a valid RSA public or private key? */
79 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
80 /** Macro: is k a valid RSA private key? */
81 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
83 #ifdef TOR_IS_MULTITHREADED
84 static tor_mutex_t **_openssl_mutexes = NULL;
85 static int _n_openssl_mutexes = -1;
86 #endif
88 struct crypto_pk_env_t
90 int refs; /* reference counting so we don't have to copy keys */
91 RSA *key;
94 struct crypto_cipher_env_t
96 unsigned char key[CIPHER_KEY_LEN];
97 aes_cnt_cipher_t *cipher;
100 struct crypto_dh_env_t {
101 DH *dh;
104 /* Prototypes for functions only used by tortls.c */
105 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
106 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
107 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
108 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
110 static int setup_openssl_threading(void);
112 /** Return the number of bytes added by padding method <b>padding</b>.
114 static INLINE int
115 crypto_get_rsa_padding_overhead(int padding) {
116 switch (padding)
118 case RSA_NO_PADDING: return 0;
119 case RSA_PKCS1_OAEP_PADDING: return 42;
120 case RSA_PKCS1_PADDING: return 11;
121 default: tor_assert(0); return -1;
125 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
127 static INLINE int
128 crypto_get_rsa_padding(int padding) {
129 switch (padding)
131 case PK_NO_PADDING: return RSA_NO_PADDING;
132 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
133 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
134 default: tor_assert(0); return -1;
138 /** Boolean: has OpenSSL's crypto been initialized? */
139 static int _crypto_global_initialized = 0;
141 /** Log all pending crypto errors at level <b>severity</b>. Use
142 * <b>doing</b> to describe our current activities.
144 static void
145 crypto_log_errors(int severity, const char *doing)
147 unsigned int err;
148 const char *msg, *lib, *func;
149 while ((err = ERR_get_error()) != 0) {
150 msg = (const char*)ERR_reason_error_string(err);
151 lib = (const char*)ERR_lib_error_string(err);
152 func = (const char*)ERR_func_error_string(err);
153 if (!msg) msg = "(null)";
154 if (doing) {
155 log(severity, "crypto error while %s: %s (in %s:%s)", doing, msg, lib, func);
156 } else {
157 log(severity, "crypto error: %s (in %s:%s)", msg, lib, func);
162 /** Initialize the crypto library. Return 0 on success, -1 on failure.
164 int crypto_global_init()
166 if (!_crypto_global_initialized) {
167 ERR_load_crypto_strings();
168 _crypto_global_initialized = 1;
169 setup_openssl_threading();
171 return 0;
174 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
176 int crypto_global_cleanup()
178 ERR_free_strings();
179 #ifdef TOR_IS_MULTITHREADED
180 if (_n_openssl_mutexes) {
181 int n = _n_openssl_mutexes;
182 tor_mutex_t **ms = _openssl_mutexes;
183 int i;
184 _openssl_mutexes = NULL;
185 _n_openssl_mutexes = 0;
186 for (i=0;i<n;++i) {
187 tor_mutex_free(ms[i]);
189 tor_free(ms);
191 #endif
192 return 0;
195 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
196 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
198 crypto_pk_env_t *env;
199 tor_assert(rsa);
200 env = tor_malloc(sizeof(crypto_pk_env_t));
201 env->refs = 1;
202 env->key = rsa;
203 return env;
206 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
207 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
209 return env->key;
212 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
213 * private is set, include the private-key portion of the key. */
214 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
216 RSA *key = NULL;
217 EVP_PKEY *pkey = NULL;
218 tor_assert(env->key);
219 if (private) {
220 if (!(key = RSAPrivateKey_dup(env->key)))
221 goto error;
222 } else {
223 if (!(key = RSAPublicKey_dup(env->key)))
224 goto error;
226 if (!(pkey = EVP_PKEY_new()))
227 goto error;
228 if (!(EVP_PKEY_assign_RSA(pkey, key)))
229 goto error;
230 return pkey;
231 error:
232 if (pkey)
233 EVP_PKEY_free(pkey);
234 if (key)
235 RSA_free(key);
236 return NULL;
239 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
241 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh)
243 return dh->dh;
246 /** Allocate and return storage for a public key. The key itself will not yet
247 * be set.
249 crypto_pk_env_t *crypto_new_pk_env(void)
251 RSA *rsa;
253 rsa = RSA_new();
254 if (!rsa) return NULL;
255 return _crypto_new_pk_env_rsa(rsa);
258 /** Release a reference to an asymmetric key; when all the references
259 * are released, free the key.
261 void crypto_free_pk_env(crypto_pk_env_t *env)
263 tor_assert(env);
265 if (--env->refs > 0)
266 return;
268 if (env->key)
269 RSA_free(env->key);
271 free(env);
274 /** Create a new symmetric cipher for a given key and encryption flag
275 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
276 * on failure.
278 crypto_cipher_env_t *
279 crypto_create_init_cipher(const char *key, int encrypt_mode)
281 int r;
282 crypto_cipher_env_t *crypto = NULL;
284 if (! (crypto = crypto_new_cipher_env())) {
285 log_fn(LOG_WARN, "Unable to allocate crypto object");
286 return NULL;
289 if (crypto_cipher_set_key(crypto, key)) {
290 crypto_log_errors(LOG_WARN, "setting symmetric key");
291 goto error;
294 if (encrypt_mode)
295 r = crypto_cipher_encrypt_init_cipher(crypto);
296 else
297 r = crypto_cipher_decrypt_init_cipher(crypto);
299 if (r)
300 goto error;
301 return crypto;
303 error:
304 if (crypto)
305 crypto_free_cipher_env(crypto);
306 return NULL;
309 /** Allocate and return a new symmetric cipher.
311 crypto_cipher_env_t *crypto_new_cipher_env()
313 crypto_cipher_env_t *env;
315 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
316 env->cipher = aes_new_cipher();
317 return env;
320 /** Free a symmetric cipher.
322 void crypto_free_cipher_env(crypto_cipher_env_t *env)
324 tor_assert(env);
326 tor_assert(env->cipher);
327 aes_free_cipher(env->cipher);
328 tor_free(env);
331 /* public key crypto */
333 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
334 * success, -1 on failure.
336 int crypto_pk_generate_key(crypto_pk_env_t *env)
338 tor_assert(env);
340 if (env->key)
341 RSA_free(env->key);
342 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
343 if (!env->key) {
344 crypto_log_errors(LOG_WARN, "generating RSA key");
345 return -1;
348 return 0;
351 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
352 * Return 0 on success, -1 on failure.
354 static int crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
355 const char *s)
357 BIO *b;
359 tor_assert(env);
360 tor_assert(s);
362 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
363 b = BIO_new_mem_buf((char*)s, -1);
365 if (env->key)
366 RSA_free(env->key);
368 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
370 BIO_free(b);
372 if (!env->key) {
373 crypto_log_errors(LOG_WARN, "Error parsing private key");
374 return -1;
376 return 0;
379 /** Read a PEM-encoded private key from the file named by
380 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
382 int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
384 char *contents;
385 int r;
387 /* Read the file into a string. */
388 contents = read_file_to_str(keyfile, 0);
389 if (!contents) {
390 log_fn(LOG_WARN, "Error reading private key from %s", keyfile);
391 return -1;
394 /* Try to parse it. */
395 r = crypto_pk_read_private_key_from_string(env, contents);
396 tor_free(contents);
397 if (r)
398 return -1; /* read_private_key_from_string already warned, so we don't.*/
400 /* Make sure it's valid. */
401 if (crypto_pk_check_key(env) <= 0)
402 return -1;
404 return 0;
407 /** PEM-encode the public key portion of <b>env</b> and write it to a
408 * newly allocated string. On success, set *<b>dest</b> to the new
409 * string, *<b>len</b> to the string's length, and return 0. On
410 * failure, return -1.
412 int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, size_t *len) {
413 BUF_MEM *buf;
414 BIO *b;
416 tor_assert(env);
417 tor_assert(env->key);
418 tor_assert(dest);
420 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
422 /* Now you can treat b as if it were a file. Just use the
423 * PEM_*_bio_* functions instead of the non-bio variants.
425 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
426 crypto_log_errors(LOG_WARN, "writing public key to string");
427 return -1;
430 BIO_get_mem_ptr(b, &buf);
431 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
432 BIO_free(b);
434 tor_assert(buf->length >= 0);
435 *dest = tor_malloc(buf->length+1);
436 memcpy(*dest, buf->data, buf->length);
437 (*dest)[buf->length] = 0; /* null terminate it */
438 *len = buf->length;
439 BUF_MEM_free(buf);
441 return 0;
444 /** Read a PEM-encoded public key from the first <b>len</b> characters of
445 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
446 * failure.
448 int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, size_t len) {
449 BIO *b;
451 tor_assert(env);
452 tor_assert(src);
454 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
456 BIO_write(b, src, len);
458 if (env->key)
459 RSA_free(env->key);
460 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
461 BIO_free(b);
462 if (!env->key) {
463 crypto_log_errors(LOG_WARN, "reading public key from string");
464 return -1;
467 return 0;
470 /* Write the private key from 'env' into the file named by 'fname',
471 * PEM-encoded. Return 0 on success, -1 on failure.
474 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
475 const char *fname)
477 BIO *bio;
478 char *cp;
479 long len;
480 char *s;
481 int r;
483 tor_assert(PRIVATE_KEY_OK(env));
485 if (!(bio = BIO_new(BIO_s_mem())))
486 return -1;
487 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
488 == 0) {
489 crypto_log_errors(LOG_WARN, "writing private key");
490 BIO_free(bio);
491 return -1;
493 len = BIO_get_mem_data(bio, &cp);
494 tor_assert(len >= 0);
495 s = tor_malloc(len+1);
496 memcpy(s, cp, len);
497 s[len]='\0';
498 r = write_str_to_file(fname, s, 0);
499 BIO_free(bio);
500 free(s);
501 return r;
504 /** Allocate a new string in *<b>out</b>, containing the public portion of the
505 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
506 * length of the encoded representation on success, and -1 on failure.
508 * <i>This function is for temporary use only. We need a simple
509 * one-line representation for keys to work around a bug in parsing
510 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
511 * in versions of Tor up to 0.0.9pre2.</i>
513 int crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
515 int len;
516 char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
517 tor_assert(env);
518 tor_assert(out);
519 len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
520 if (len < 0) {
521 return -1;
523 *out = tor_malloc(len * 2); /* too long, but safe. */
524 if (base64_encode(*out, len*2, buf, len) < 0) {
525 log_fn(LOG_WARN, "Error base64-encoding DER-encoded key");
526 tor_free(*out);
527 return -1;
529 /* Remove spaces */
530 tor_strstrip(*out, " \r\n\t");
531 return strlen(*out);
534 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
535 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
537 * <i>This function is for temporary use only. We need a simple
538 * one-line representation for keys to work around a bug in parsing
539 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
540 * in versions of Tor up to 0.0.9pre2.</i>
542 crypto_pk_env_t *crypto_pk_DER64_decode_public_key(const char *in)
544 char partitioned[PK_BYTES*2 + 16];
545 char buf[PK_BYTES*2];
546 int len;
547 tor_assert(in);
548 len = strlen(in);
550 if (strlen(in) > PK_BYTES*2) {
551 return NULL;
553 /* base64_decode doesn't work unless we insert linebreaks every 64
554 * characters. how dumb. */
555 if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
556 ALWAYS_TERMINATE))
557 return NULL;
558 len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
559 if (len<0) {
560 log_fn(LOG_WARN,"Error base-64 decoding key");
561 return NULL;
563 return crypto_pk_asn1_decode(buf, len);
566 /** Return true iff <b>env</b> has a valid key.
568 int crypto_pk_check_key(crypto_pk_env_t *env)
570 int r;
571 tor_assert(env);
573 r = RSA_check_key(env->key);
574 if (r <= 0)
575 crypto_log_errors(LOG_WARN,"checking RSA key");
576 return r;
579 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
580 * if a==b, and 1 if a\>b.
582 int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
583 int result;
585 if (!a || !b)
586 return -1;
588 if (!a->key || !b->key)
589 return -1;
591 tor_assert(PUBLIC_KEY_OK(a));
592 tor_assert(PUBLIC_KEY_OK(b));
593 result = BN_cmp((a->key)->n, (b->key)->n);
594 if (result)
595 return result;
596 return BN_cmp((a->key)->e, (b->key)->e);
599 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
600 int crypto_pk_keysize(crypto_pk_env_t *env)
602 tor_assert(env);
603 tor_assert(env->key);
605 return RSA_size(env->key);
608 /** Increase the reference count of <b>env</b>, and return it.
610 crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
611 tor_assert(env);
612 tor_assert(env->key);
614 env->refs++;
615 return env;
618 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
619 * in <b>env</b>, using the padding method <b>padding</b>. On success,
620 * write the result to <b>to</b>, and return the number of bytes
621 * written. On failure, return -1.
624 crypto_pk_public_encrypt(crypto_pk_env_t *env, unsigned char *to,
625 const unsigned char *from, int fromlen, int padding)
627 int r;
628 tor_assert(env);
629 tor_assert(from);
630 tor_assert(to);
632 r = RSA_public_encrypt(fromlen, (unsigned char*)from, to, env->key,
633 crypto_get_rsa_padding(padding));
634 if (r<0) {
635 crypto_log_errors(LOG_WARN, "performing RSA encryption");
636 return -1;
638 return r;
641 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
642 * in <b>env</b>, using the padding method <b>padding</b>. On success,
643 * write the result to <b>to</b>, and return the number of bytes
644 * written. On failure, return -1.
647 crypto_pk_private_decrypt(crypto_pk_env_t *env, unsigned char *to,
648 const unsigned char *from, int fromlen,
649 int padding, int warnOnFailure)
651 int r;
652 tor_assert(env);
653 tor_assert(from);
654 tor_assert(to);
655 tor_assert(env->key);
656 if (!env->key->p)
657 /* Not a private key */
658 return -1;
660 r = RSA_private_decrypt(fromlen, (unsigned char*)from, to, env->key,
661 crypto_get_rsa_padding(padding));
662 if (r<0) {
663 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_INFO,
664 "performing RSA decryption");
665 return -1;
667 return r;
670 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
671 * public key in <b>env</b>, using PKCS1 padding. On success, write the
672 * signed data to <b>to</b>, and return the number of bytes written.
673 * On failure, return -1.
676 crypto_pk_public_checksig(crypto_pk_env_t *env, unsigned char *to,
677 const unsigned char *from, int fromlen)
679 int r;
680 tor_assert(env);
681 tor_assert(from);
682 tor_assert(to);
683 r = RSA_public_decrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
685 if (r<0) {
686 crypto_log_errors(LOG_WARN, "checking RSA signature");
687 return -1;
689 return r;
692 /** Check a siglen-byte long signature at <b>sig</b> against
693 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
694 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
695 * SHA1(data). Else return -1.
698 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const unsigned char *data,
699 int datalen, const unsigned char *sig, int siglen)
701 char digest[DIGEST_LEN];
702 char buf[PK_BYTES+1];
703 int r;
705 tor_assert(env);
706 tor_assert(data);
707 tor_assert(sig);
709 if (crypto_digest(digest,data,datalen)<0) {
710 log_fn(LOG_WARN, "couldn't compute digest");
711 return -1;
713 r = crypto_pk_public_checksig(env,buf,sig,siglen);
714 if (r != DIGEST_LEN) {
715 log_fn(LOG_WARN, "Invalid signature");
716 return -1;
718 if (memcmp(buf, digest, DIGEST_LEN)) {
719 log_fn(LOG_WARN, "Signature mismatched with digest.");
720 return -1;
723 return 0;
726 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
727 * <b>env</b>, using PKCS1 padding. On success, write the signature to
728 * <b>to</b>, and return the number of bytes written. On failure, return
729 * -1.
732 crypto_pk_private_sign(crypto_pk_env_t *env, unsigned char *to,
733 const unsigned char *from, int fromlen)
735 int r;
736 tor_assert(env);
737 tor_assert(from);
738 tor_assert(to);
739 if (!env->key->p)
740 /* Not a private key */
741 return -1;
743 r = RSA_private_encrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
744 if (r<0) {
745 crypto_log_errors(LOG_WARN, "generating RSA signature");
746 return -1;
748 return r;
751 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
752 * <b>from</b>; sign the data with the private key in <b>env</b>, and
753 * store it in <b>to</b>. Return the number of bytes written on
754 * success, and -1 on failure.
757 crypto_pk_private_sign_digest(crypto_pk_env_t *env, unsigned char *to,
758 const unsigned char *from, int fromlen)
760 char digest[DIGEST_LEN];
761 if (crypto_digest(digest,from,fromlen)<0)
762 return -1;
763 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
766 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
767 * bytes of data from <b>from</b>, with padding type 'padding',
768 * storing the results on <b>to</b>.
770 * If no padding is used, the public key must be at least as large as
771 * <b>from</b>.
773 * Returns the number of bytes written on success, -1 on failure.
775 * The encrypted data consists of:
776 * - The source data, padded and encrypted with the public key, if the
777 * padded source data is no longer than the public key, and <b>force</b>
778 * is false, OR
779 * - The beginning of the source data prefixed with a 16-byte symmetric key,
780 * padded and encrypted with the public key; followed by the rest of
781 * the source data encrypted in AES-CTR mode with the symmetric key.
783 int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
784 unsigned char *to,
785 const unsigned char *from,
786 int fromlen,
787 int padding, int force)
789 int overhead, pkeylen, outlen, r, symlen;
790 crypto_cipher_env_t *cipher = NULL;
791 char buf[PK_BYTES+1];
793 tor_assert(env);
794 tor_assert(from);
795 tor_assert(to);
797 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
798 pkeylen = crypto_pk_keysize(env);
800 if (padding == PK_NO_PADDING && fromlen < pkeylen)
801 return -1;
803 if (!force && fromlen+overhead <= pkeylen) {
804 /* It all fits in a single encrypt. */
805 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
807 cipher = crypto_new_cipher_env();
808 if (!cipher) return -1;
809 if (crypto_cipher_generate_key(cipher)<0)
810 goto err;
811 /* You can't just run around RSA-encrypting any bitstream: if it's
812 * greater than the RSA key, then OpenSSL will happily encrypt, and
813 * later decrypt to the wrong value. So we set the first bit of
814 * 'cipher->key' to 0 if we aren't padding. This means that our
815 * symmetric key is really only 127 bits.
817 if (padding == PK_NO_PADDING)
818 cipher->key[0] &= 0x7f;
819 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
820 goto err;
821 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
822 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
824 /* Length of symmetrically encrypted data. */
825 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
827 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
828 if (outlen!=pkeylen) {
829 goto err;
831 r = crypto_cipher_encrypt(cipher, to+outlen,
832 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
834 if (r<0) goto err;
835 memset(buf, 0, sizeof(buf));
836 crypto_free_cipher_env(cipher);
837 return outlen + symlen;
838 err:
839 memset(buf, 0, sizeof(buf));
840 if (cipher) crypto_free_cipher_env(cipher);
841 return -1;
844 /** Invert crypto_pk_public_hybrid_encrypt. */
845 int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
846 unsigned char *to,
847 const unsigned char *from,
848 int fromlen,
849 int padding, int warnOnFailure)
851 int overhead, pkeylen, outlen, r;
852 crypto_cipher_env_t *cipher = NULL;
853 char buf[PK_BYTES+1];
855 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
856 pkeylen = crypto_pk_keysize(env);
858 if (fromlen <= pkeylen) {
859 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,warnOnFailure);
861 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,warnOnFailure);
862 if (outlen<0) {
863 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, "Error decrypting public-key data");
864 return -1;
866 if (outlen < CIPHER_KEY_LEN) {
867 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, "No room for a symmetric key");
868 return -1;
870 cipher = crypto_create_init_cipher(buf, 0);
871 if (!cipher) {
872 return -1;
874 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
875 outlen -= CIPHER_KEY_LEN;
876 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
877 if (r<0)
878 goto err;
879 memset(buf,0,sizeof(buf));
880 crypto_free_cipher_env(cipher);
881 return outlen + (fromlen-pkeylen);
882 err:
883 memset(buf,0,sizeof(buf));
884 if (cipher) crypto_free_cipher_env(cipher);
885 return -1;
888 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
889 * Return -1 on error, or the number of characters used on success.
891 int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
893 int len;
894 unsigned char *buf, *cp;
895 len = i2d_RSAPublicKey(pk->key, NULL);
896 if (len < 0 || len > dest_len)
897 return -1;
898 cp = buf = tor_malloc(len+1);
899 len = i2d_RSAPublicKey(pk->key, &cp);
900 if (len < 0) {
901 crypto_log_errors(LOG_WARN,"encoding public key");
902 tor_free(buf);
903 return -1;
905 /* We don't encode directly into 'dest', because that would be illegal
906 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
908 memcpy(dest,buf,len);
909 tor_free(buf);
910 return len;
913 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
914 * success and NULL on failure.
916 crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len)
918 RSA *rsa;
919 unsigned char *buf;
920 /* This ifdef suppresses a type warning. Take out the first case once
921 * everybody is using openssl 0.9.7 or later.
923 #if OPENSSL_VERSION_NUMBER < 0x00907000l
924 unsigned char *cp;
925 #else
926 const unsigned char *cp;
927 #endif
928 cp = buf = tor_malloc(len);
929 memcpy(buf,str,len);
930 rsa = d2i_RSAPublicKey(NULL, &cp, len);
931 tor_free(buf);
932 if (!rsa) {
933 crypto_log_errors(LOG_WARN,"decoding public key");
934 return NULL;
936 return _crypto_new_pk_env_rsa(rsa);
939 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
940 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
941 * Return 0 on success, -1 on failure.
943 int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
945 unsigned char *buf, *bufp;
946 int len;
948 len = i2d_RSAPublicKey(pk->key, NULL);
949 if (len < 0)
950 return -1;
951 buf = bufp = tor_malloc(len+1);
952 len = i2d_RSAPublicKey(pk->key, &bufp);
953 if (len < 0) {
954 crypto_log_errors(LOG_WARN,"encoding public key");
955 free(buf);
956 return -1;
958 if (crypto_digest(digest_out, buf, len) < 0) {
959 free(buf);
960 return -1;
962 free(buf);
963 return 0;
966 /** Given a private or public key <b>pk</b>, put a fingerprint of the
967 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
968 * space). Return 0 on success, -1 on failure.
970 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
971 * of the public key, converted to hexadecimal, in upper case, with a
972 * space after every four digits.
974 * If <b>add_space</b> is false, omit the spaces.
977 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
979 unsigned char digest[DIGEST_LEN];
980 unsigned char hexdigest[HEX_DIGEST_LEN+1];
981 if (crypto_pk_get_digest(pk, digest)) {
982 return -1;
984 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
985 if (add_space) {
986 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
987 NEVER_TERMINATE)<0)
988 return -1;
989 } else {
990 strcpy(fp_out, hexdigest);
992 return 0;
995 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
998 crypto_pk_check_fingerprint_syntax(const char *s)
1000 int i;
1001 for (i = 0; i < FINGERPRINT_LEN; ++i) {
1002 if ((i%5) == 4) {
1003 if (!TOR_ISSPACE(s[i])) return 0;
1004 } else {
1005 if (!TOR_ISXDIGIT(s[i])) return 0;
1008 if (s[FINGERPRINT_LEN]) return 0;
1009 return 1;
1012 /* symmetric crypto */
1014 /** Generate a new random key for the symmetric cipher in <b>env</b>.
1015 * Return 0 on success, -1 on failure. Does not initialize the cipher.
1017 int crypto_cipher_generate_key(crypto_cipher_env_t *env)
1019 tor_assert(env);
1021 return crypto_rand(env->key, CIPHER_KEY_LEN);
1024 /** Set the symmetric key for the cipher in <b>env</b> to the first
1025 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1026 * Return 0 on success, -1 on failure.
1028 int crypto_cipher_set_key(crypto_cipher_env_t *env, const unsigned char *key)
1030 tor_assert(env);
1031 tor_assert(key);
1033 if (!env->key)
1034 return -1;
1036 memcpy(env->key, key, CIPHER_KEY_LEN);
1038 return 0;
1041 /** Return a pointer to the key set for the cipher in <b>env</b>.
1043 const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
1045 return env->key;
1048 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1049 * success, -1 on failure.
1051 int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1053 tor_assert(env);
1055 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1056 return 0;
1059 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1060 * success, -1 on failure.
1062 int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1064 tor_assert(env);
1066 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1067 return 0;
1070 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1071 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1072 * On failure, return -1.
1075 crypto_cipher_encrypt(crypto_cipher_env_t *env, unsigned char *to,
1076 const unsigned char *from, unsigned int fromlen)
1078 tor_assert(env);
1079 tor_assert(env->cipher);
1080 tor_assert(from);
1081 tor_assert(fromlen);
1082 tor_assert(to);
1084 aes_crypt(env->cipher, from, fromlen, to);
1085 return 0;
1088 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1089 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1090 * On failure, return -1.
1093 crypto_cipher_decrypt(crypto_cipher_env_t *env, unsigned char *to,
1094 const unsigned char *from, unsigned int fromlen)
1096 tor_assert(env);
1097 tor_assert(from);
1098 tor_assert(to);
1100 aes_crypt(env->cipher, from, fromlen, to);
1101 return 0;
1104 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1105 * Return 0 on success, -1 on failure.
1108 crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
1110 return crypto_cipher_advance(env, -delta);
1113 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1114 * Return 0 on success, -1 on failure.
1117 crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
1119 aes_adjust_counter(env->cipher, delta);
1120 return 0;
1123 /* SHA-1 */
1125 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1126 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1127 * Return 0 on success, -1 on failure.
1129 int crypto_digest(unsigned char *digest, const unsigned char *m, int len)
1131 tor_assert(m);
1132 tor_assert(digest);
1133 return (SHA1(m,len,digest) == NULL);
1136 struct crypto_digest_env_t {
1137 SHA_CTX d;
1140 /** Allocate and return a new digest object.
1142 crypto_digest_env_t *
1143 crypto_new_digest_env(void)
1145 crypto_digest_env_t *r;
1146 r = tor_malloc(sizeof(crypto_digest_env_t));
1147 SHA1_Init(&r->d);
1148 return r;
1151 /** Deallocate a digest object.
1153 void
1154 crypto_free_digest_env(crypto_digest_env_t *digest) {
1155 tor_free(digest);
1158 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1160 void
1161 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1162 size_t len)
1164 tor_assert(digest);
1165 tor_assert(data);
1166 /* Using the SHA1_*() calls directly means we don't support doing
1167 * sha1 in hardware. But so far the delay of getting the question
1168 * to the hardware, and hearing the answer, is likely higher than
1169 * just doing it ourselves. Hashes are fast.
1171 SHA1_Update(&digest->d, (void*)data, len);
1174 /** Compute the hash of the data that has been passed to the digest
1175 * object; write the first out_len bytes of the result to <b>out</b>.
1176 * <b>out_len</b> must be \<= DIGEST_LEN.
1178 void crypto_digest_get_digest(crypto_digest_env_t *digest,
1179 char *out, size_t out_len)
1181 static char r[DIGEST_LEN];
1182 SHA_CTX tmpctx;
1183 tor_assert(digest);
1184 tor_assert(out);
1185 tor_assert(out_len <= DIGEST_LEN);
1186 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1187 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1188 SHA1_Final(r, &tmpctx);
1189 memcpy(out, r, out_len);
1192 /** Allocate and return a new digest object with the same state as
1193 * <b>digest</b>
1195 crypto_digest_env_t *
1196 crypto_digest_dup(const crypto_digest_env_t *digest)
1198 crypto_digest_env_t *r;
1199 tor_assert(digest);
1200 r = tor_malloc(sizeof(crypto_digest_env_t));
1201 memcpy(r,digest,sizeof(crypto_digest_env_t));
1202 return r;
1205 /** Replace the state of the digest object <b>into</b> with the state
1206 * of the digest object <b>from</b>.
1208 void
1209 crypto_digest_assign(crypto_digest_env_t *into,
1210 const crypto_digest_env_t *from)
1212 tor_assert(into);
1213 tor_assert(from);
1214 memcpy(into,from,sizeof(crypto_digest_env_t));
1217 /* DH */
1219 /** Shared P parameter for our DH key exchanged. */
1220 static BIGNUM *dh_param_p = NULL;
1221 /** Shared G parameter for our DH key exchanges. */
1222 static BIGNUM *dh_param_g = NULL;
1224 /** Initialize dh_param_p and dh_param_g if they are not already
1225 * set. */
1226 static void init_dh_param(void) {
1227 BIGNUM *p, *g;
1228 int r;
1229 if (dh_param_p && dh_param_g)
1230 return;
1232 p = BN_new();
1233 g = BN_new();
1234 tor_assert(p);
1235 tor_assert(g);
1237 #if 0
1238 /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
1239 prime, and supposedly it equals:
1240 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
1242 r = BN_hex2bn(&p,
1243 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
1244 "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
1245 "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
1246 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
1247 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
1248 "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
1249 "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
1250 "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
1251 #endif
1253 /* This is from rfc2409, section 6.2. It's a safe prime, and
1254 supposedly it equals:
1255 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1257 /* See also rfc 3536 */
1258 r = BN_hex2bn(&p,
1259 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1260 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1261 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1262 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1263 "49286651ECE65381FFFFFFFFFFFFFFFF");
1264 tor_assert(r);
1266 r = BN_set_word(g, 2);
1267 tor_assert(r);
1268 dh_param_p = p;
1269 dh_param_g = g;
1272 /** Allocate and return a new DH object for a key exchange.
1274 crypto_dh_env_t *crypto_dh_new()
1276 crypto_dh_env_t *res = NULL;
1278 if (!dh_param_p)
1279 init_dh_param();
1281 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1283 if (!(res->dh = DH_new()))
1284 goto err;
1286 if (!(res->dh->p = BN_dup(dh_param_p)))
1287 goto err;
1289 if (!(res->dh->g = BN_dup(dh_param_g)))
1290 goto err;
1292 return res;
1293 err:
1294 crypto_log_errors(LOG_WARN, "creating DH object");
1295 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1296 if (res) free(res);
1297 return NULL;
1300 /** Return the length of the DH key in <b>dh</b>, in bytes.
1302 int crypto_dh_get_bytes(crypto_dh_env_t *dh)
1304 tor_assert(dh);
1305 return DH_size(dh->dh);
1308 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1309 * success, -1 on failure.
1311 int crypto_dh_generate_public(crypto_dh_env_t *dh)
1313 if (!DH_generate_key(dh->dh)) {
1314 crypto_log_errors(LOG_WARN, "generating DH key");
1315 return -1;
1317 return 0;
1320 /** Generate g^x as necessary, and write the g^x for the key exchange
1321 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1322 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1324 int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1326 int bytes;
1327 tor_assert(dh);
1328 if (!dh->dh->pub_key) {
1329 if (crypto_dh_generate_public(dh)<0)
1330 return -1;
1333 tor_assert(dh->dh->pub_key);
1334 bytes = BN_num_bytes(dh->dh->pub_key);
1335 tor_assert(bytes >= 0);
1336 if (pubkey_len < (size_t)bytes)
1337 return -1;
1339 memset(pubkey, 0, pubkey_len);
1340 BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
1342 return 0;
1345 #undef MIN
1346 #define MIN(a,b) ((a)<(b)?(a):(b))
1347 /** Given a DH key exchange object, and our peer's value of g^y (as a
1348 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1349 * <b>secret_bytes_out</b> bytes of shared key material and write them
1350 * to <b>secret_out</b>. Return the number of bytes generated on success,
1351 * or -1 on failure.
1353 * (We generate key material by computing
1354 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1355 * where || is concatenation.)
1357 int crypto_dh_compute_secret(crypto_dh_env_t *dh,
1358 const char *pubkey, size_t pubkey_len,
1359 char *secret_out, size_t secret_bytes_out)
1361 unsigned char hash[DIGEST_LEN];
1362 unsigned char *secret_tmp = NULL;
1363 BIGNUM *pubkey_bn = NULL;
1364 size_t secret_len=0;
1365 unsigned int i;
1366 int result=0;
1367 tor_assert(dh);
1368 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1370 if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
1371 goto error;
1372 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
1373 result = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
1374 if (result < 0) {
1375 log_fn(LOG_WARN,"DH_compute_key() failed.");
1376 goto error;
1378 secret_len = result;
1379 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1380 for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
1381 secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
1382 if (crypto_digest(hash, secret_tmp, secret_len+1))
1383 goto error;
1384 memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
1386 secret_len = secret_bytes_out;
1388 goto done;
1389 error:
1390 result = -1;
1391 done:
1392 crypto_log_errors(LOG_WARN, "completing DH handshake");
1393 if (pubkey_bn)
1394 BN_free(pubkey_bn);
1395 tor_free(secret_tmp);
1396 if (result < 0)
1397 return result;
1398 else
1399 return secret_len;
1402 /** Free a DH key exchange object.
1404 void crypto_dh_free(crypto_dh_env_t *dh)
1406 tor_assert(dh);
1407 tor_assert(dh->dh);
1408 DH_free(dh->dh);
1409 free(dh);
1412 /* random numbers */
1414 /** Seed OpenSSL's random number generator with DIGEST_LEN bytes from the
1415 * operating system. Return 0 on success, -1 on failure.
1417 int crypto_seed_rng(void)
1419 #ifdef MS_WINDOWS
1420 static int provider_set = 0;
1421 static HCRYPTPROV provider;
1422 char buf[DIGEST_LEN+1];
1424 if (!provider_set) {
1425 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET)) {
1426 if (GetLastError() != NTE_BAD_KEYSET) {
1427 log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
1428 return -1;
1430 /* Yes, we need to try it twice. */
1431 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1432 CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET)) {
1433 log_fn(LOG_ERR,"Can't get CryptoAPI provider [2], error code: %x", GetLastError());
1434 return -1;
1437 provider_set = 1;
1439 if (!CryptGenRandom(provider, DIGEST_LEN, buf)) {
1440 log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
1441 return -1;
1443 RAND_seed(buf, DIGEST_LEN);
1444 /* And add the current screen state to the entropy pool for
1445 * good measure. */
1446 RAND_screen();
1447 return 0;
1448 #else
1449 static const char *filenames[] = {
1450 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1452 int fd;
1453 int i, n;
1454 char buf[DIGEST_LEN+1];
1456 for (i = 0; filenames[i]; ++i) {
1457 fd = open(filenames[i], O_RDONLY, 0);
1458 if (fd<0) continue;
1459 log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
1460 n = read(fd, buf, DIGEST_LEN);
1461 close(fd);
1462 if (n != DIGEST_LEN) {
1463 log_fn(LOG_WARN, "Error reading from entropy source");
1464 return -1;
1466 RAND_seed(buf, DIGEST_LEN);
1467 return 0;
1470 log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
1471 return -1;
1472 #endif
1475 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1476 * success, -1 on failure.
1478 int crypto_rand(unsigned char *to, unsigned int n)
1480 int r;
1481 tor_assert(to);
1482 r = RAND_bytes(to, n);
1483 if (r == 0)
1484 crypto_log_errors(LOG_WARN, "generating random data");
1485 return (r == 1) ? 0 : -1;
1488 /** Write n bytes of pseudorandom data to <b>to</b>. Return 0 on
1489 * success, -1 on failure.
1491 void crypto_pseudo_rand(unsigned char *to, unsigned int n)
1493 tor_assert(to);
1494 if (RAND_pseudo_bytes(to, n) == -1) {
1495 log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
1496 crypto_log_errors(LOG_WARN, "generating random data");
1497 exit(1);
1501 /** Return a pseudorandom integer, chosen uniformly from the values
1502 * between 0 and max-1. */
1503 int crypto_pseudo_rand_int(unsigned int max) {
1504 unsigned int val;
1505 unsigned int cutoff;
1506 tor_assert(max < UINT_MAX);
1507 tor_assert(max > 0); /* don't div by 0 */
1509 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1510 * distribution with clipping at the upper end of unsigned int's
1511 * range.
1513 cutoff = UINT_MAX - (UINT_MAX%max);
1514 while (1) {
1515 crypto_pseudo_rand((unsigned char*) &val, sizeof(val));
1516 if (val < cutoff)
1517 return val % max;
1521 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1523 void *smartlist_choose(const smartlist_t *sl) {
1524 size_t len;
1525 len = smartlist_len(sl);
1526 if (len)
1527 return smartlist_get(sl,crypto_pseudo_rand_int(len));
1528 return NULL; /* no elements to choose from */
1531 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1532 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1533 * bytes. Return the number of bytes written on success; -1 if
1534 * destlen is too short, or other failure.
1537 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1539 EVP_ENCODE_CTX ctx;
1540 int len, ret;
1542 /* 48 bytes of input -> 64 bytes of output plus newline.
1543 Plus one more byte, in case I'm wrong.
1545 if (destlen < ((srclen/48)+1)*66)
1546 return -1;
1547 if (destlen > SIZE_T_CEILING)
1548 return -1;
1550 EVP_EncodeInit(&ctx);
1551 EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1552 EVP_EncodeFinal(&ctx, dest+len, &ret);
1553 ret += len;
1554 return ret;
1557 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1558 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1559 * bytes. Return the number of bytes written on success; -1 if
1560 * destlen is too short, or other failure.
1562 * NOTE: destlen should be a little longer than the amount of data it
1563 * will contain, since we check for sufficient space conservatively.
1564 * Here, "a little" is around 64-ish bytes.
1567 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1569 EVP_ENCODE_CTX ctx;
1570 int len, ret;
1571 /* 64 bytes of input -> *up to* 48 bytes of output.
1572 Plus one more byte, in case I'm wrong.
1574 if (destlen < ((srclen/64)+1)*49)
1575 return -1;
1576 if (destlen > SIZE_T_CEILING)
1577 return -1;
1579 EVP_DecodeInit(&ctx);
1580 EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1581 EVP_DecodeFinal(&ctx, dest, &ret);
1582 ret += len;
1583 return ret;
1586 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1587 * that srclen*8 is a multiple of 5.
1589 void
1590 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1592 unsigned int nbits, i, bit, v, u;
1593 nbits = srclen * 8;
1595 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1596 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1597 tor_assert(destlen < SIZE_T_CEILING);
1599 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1600 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1601 v = ((uint8_t)src[bit/8]) << 8;
1602 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1603 /* set u to the 5-bit value at the bit'th bit of src. */
1604 u = (v >> (11-(bit%8))) & 0x1F;
1605 dest[i] = BASE32_CHARS[u];
1607 dest[i] = '\0';
1610 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1611 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1612 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1613 * are a salt; the 9th byte describes how much iteration to do.
1614 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1616 void
1617 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1618 size_t secret_len, const char *s2k_specifier)
1620 crypto_digest_env_t *d;
1621 uint8_t c;
1622 size_t count;
1623 char *tmp;
1624 tor_assert(key_out_len < SIZE_T_CEILING);
1626 #define EXPBIAS 6
1627 c = s2k_specifier[8];
1628 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1629 #undef EXPBIAS
1631 tor_assert(key_out_len <= DIGEST_LEN);
1633 d = crypto_new_digest_env();
1634 tmp = tor_malloc(8+secret_len);
1635 memcpy(tmp,s2k_specifier,8);
1636 memcpy(tmp+8,secret,secret_len);
1637 secret_len += 8;
1638 while (count) {
1639 if (count >= secret_len) {
1640 crypto_digest_add_bytes(d, tmp, secret_len);
1641 count -= secret_len;
1642 } else {
1643 crypto_digest_add_bytes(d, tmp, count);
1644 count = 0;
1647 crypto_digest_get_digest(d, key_out, key_out_len);
1648 tor_free(tmp);
1649 crypto_free_digest_env(d);
1652 #ifdef TOR_IS_MULTITHREADED
1653 static void
1654 _openssl_locking_cb(int mode, int n, const char *file, int line)
1656 if (!_openssl_mutexes)
1657 /* This is not a really good fix for the
1658 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
1659 * it can't hurt. */
1660 return;
1661 if (mode & CRYPTO_LOCK)
1662 tor_mutex_acquire(_openssl_mutexes[n]);
1663 else
1664 tor_mutex_release(_openssl_mutexes[n]);
1666 static int
1667 setup_openssl_threading(void) {
1668 int i;
1669 int n = CRYPTO_num_locks();
1670 _n_openssl_mutexes = n;
1671 _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
1672 for (i=0; i < n; ++i)
1673 _openssl_mutexes[i] = tor_mutex_new();
1674 CRYPTO_set_locking_callback(_openssl_locking_cb);
1675 CRYPTO_set_id_callback(tor_get_thread_id);
1676 return 0;
1678 #else
1679 static int setup_openssl_threading(void) { return 0; }
1680 #endif