Forward port changelog
[tor.git] / src / common / crypto.c
blobfc69f7dd1e6dd12441fdcf1902a04f83bcd7d337
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
4 const char crypto_c_id[] = "$Id$";
6 /**
7 * \file crypto.c
9 * \brief Low-level cryptographic functions.
10 **/
12 #include "orconfig.h"
14 #ifdef MS_WINDOWS
15 #define WIN32_WINNT 0x400
16 #define _WIN32_WINNT 0x400
17 #define WIN32_LEAN_AND_MEAN
18 #include <windows.h>
19 #include <wincrypt.h>
20 #endif
22 #include <string.h>
24 #include <openssl/err.h>
25 #include <openssl/rsa.h>
26 #include <openssl/pem.h>
27 #include <openssl/evp.h>
28 #include <openssl/rand.h>
29 #include <openssl/opensslv.h>
30 #include <openssl/bn.h>
31 #include <openssl/dh.h>
32 #include <openssl/rsa.h>
33 #include <openssl/dh.h>
35 #include <stdlib.h>
36 #include <assert.h>
37 #include <stdio.h>
38 #include <limits.h>
40 #ifdef HAVE_CTYPE_H
41 #include <ctype.h>
42 #endif
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #endif
49 #ifdef HAVE_SYS_FCNTL_H
50 #include <sys/fcntl.h>
51 #endif
53 #include "crypto.h"
54 #include "log.h"
55 #include "aes.h"
56 #include "util.h"
57 #include "container.h"
59 #if OPENSSL_VERSION_NUMBER < 0x00905000l
60 #error "We require openssl >= 0.9.5"
61 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
62 #define OPENSSL_095
63 #endif
65 /* Certain functions that return a success code in OpenSSL 0.9.6 return void
66 * (and don't indicate errors) in OpenSSL version 0.9.5.
68 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
70 #ifdef OPENSSL_095
71 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
72 #else
73 #define RETURN_SSL_OUTCOME(exp) return !(exp)
74 #endif
76 /** Macro: is k a valid RSA public or private key? */
77 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
78 /** Macro: is k a valid RSA private key? */
79 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
81 struct crypto_pk_env_t
83 int refs; /* reference counting so we don't have to copy keys */
84 RSA *key;
87 struct crypto_cipher_env_t
89 unsigned char key[CIPHER_KEY_LEN];
90 aes_cnt_cipher_t *cipher;
93 struct crypto_dh_env_t {
94 DH *dh;
97 /* Prototypes for functions only used by tortls.c */
98 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
99 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
100 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
101 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
103 /** Return the number of bytes added by padding method <b>padding</b>.
105 static INLINE int
106 crypto_get_rsa_padding_overhead(int padding) {
107 switch (padding)
109 case RSA_NO_PADDING: return 0;
110 case RSA_PKCS1_OAEP_PADDING: return 42;
111 case RSA_PKCS1_PADDING: return 11;
112 default: tor_assert(0); return -1;
116 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
118 static INLINE int
119 crypto_get_rsa_padding(int padding) {
120 switch (padding)
122 case PK_NO_PADDING: return RSA_NO_PADDING;
123 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
124 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
125 default: tor_assert(0); return -1;
129 /** Boolean: has OpenSSL's crypto been initialized? */
130 static int _crypto_global_initialized = 0;
132 /** Log all pending crypto errors at level <b>severity</b>. Use
133 * <b>doing</b> to describe our current activities.
135 static void
136 crypto_log_errors(int severity, const char *doing)
138 unsigned int err;
139 const char *msg, *lib, *func;
140 while ((err = ERR_get_error()) != 0) {
141 msg = (const char*)ERR_reason_error_string(err);
142 lib = (const char*)ERR_lib_error_string(err);
143 func = (const char*)ERR_func_error_string(err);
144 if (!msg) msg = "(null)";
145 if (doing) {
146 log(severity, "crypto error while %s: %s (in %s:%s)", doing, msg, lib, func);
147 } else {
148 log(severity, "crypto error: %s (in %s:%s)", msg, lib, func);
153 /** Initialize the crypto library. Return 0 on success, -1 on failure.
155 int crypto_global_init()
157 if (!_crypto_global_initialized) {
158 ERR_load_crypto_strings();
159 _crypto_global_initialized = 1;
161 return 0;
164 /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
166 int crypto_global_cleanup()
168 ERR_free_strings();
169 return 0;
172 /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
173 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
175 crypto_pk_env_t *env;
176 tor_assert(rsa);
177 env = tor_malloc(sizeof(crypto_pk_env_t));
178 env->refs = 1;
179 env->key = rsa;
180 return env;
183 /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
184 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
186 return env->key;
189 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
190 * private is set, include the private-key portion of the key. */
191 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
193 RSA *key = NULL;
194 EVP_PKEY *pkey = NULL;
195 tor_assert(env->key);
196 if (private) {
197 if (!(key = RSAPrivateKey_dup(env->key)))
198 goto error;
199 } else {
200 if (!(key = RSAPublicKey_dup(env->key)))
201 goto error;
203 if (!(pkey = EVP_PKEY_new()))
204 goto error;
205 if (!(EVP_PKEY_assign_RSA(pkey, key)))
206 goto error;
207 return pkey;
208 error:
209 if (pkey)
210 EVP_PKEY_free(pkey);
211 if (key)
212 RSA_free(key);
213 return NULL;
216 /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
218 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh)
220 return dh->dh;
223 /** Allocate and return storage for a public key. The key itself will not yet
224 * be set.
226 crypto_pk_env_t *crypto_new_pk_env(void)
228 RSA *rsa;
230 rsa = RSA_new();
231 if (!rsa) return NULL;
232 return _crypto_new_pk_env_rsa(rsa);
235 /** Release a reference to an asymmetric key; when all the references
236 * are released, free the key.
238 void crypto_free_pk_env(crypto_pk_env_t *env)
240 tor_assert(env);
242 if (--env->refs > 0)
243 return;
245 if (env->key)
246 RSA_free(env->key);
248 free(env);
251 /** Create a new symmetric cipher for a given key and encryption flag
252 * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
253 * on failure.
255 crypto_cipher_env_t *
256 crypto_create_init_cipher(const char *key, int encrypt_mode)
258 int r;
259 crypto_cipher_env_t *crypto = NULL;
261 if (! (crypto = crypto_new_cipher_env())) {
262 log_fn(LOG_WARN, "Unable to allocate crypto object");
263 return NULL;
266 if (crypto_cipher_set_key(crypto, key)) {
267 crypto_log_errors(LOG_WARN, "setting symmetric key");
268 goto error;
271 if (encrypt_mode)
272 r = crypto_cipher_encrypt_init_cipher(crypto);
273 else
274 r = crypto_cipher_decrypt_init_cipher(crypto);
276 if (r)
277 goto error;
278 return crypto;
280 error:
281 if (crypto)
282 crypto_free_cipher_env(crypto);
283 return NULL;
286 /** Allocate and return a new symmetric cipher.
288 crypto_cipher_env_t *crypto_new_cipher_env()
290 crypto_cipher_env_t *env;
292 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
293 env->cipher = aes_new_cipher();
294 return env;
297 /** Free a symmetric cipher.
299 void crypto_free_cipher_env(crypto_cipher_env_t *env)
301 tor_assert(env);
303 tor_assert(env->cipher);
304 aes_free_cipher(env->cipher);
305 tor_free(env);
308 /* public key crypto */
310 /** Generate a new public/private keypair in <b>env</b>. Return 0 on
311 * success, -1 on failure.
313 int crypto_pk_generate_key(crypto_pk_env_t *env)
315 tor_assert(env);
317 if (env->key)
318 RSA_free(env->key);
319 env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
320 if (!env->key) {
321 crypto_log_errors(LOG_WARN, "generating RSA key");
322 return -1;
325 return 0;
328 /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
329 * Return 0 on success, -1 on failure.
331 static int crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
332 const char *s)
334 BIO *b;
336 tor_assert(env);
337 tor_assert(s);
339 /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
340 b = BIO_new_mem_buf((char*)s, -1);
342 if (env->key)
343 RSA_free(env->key);
345 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
347 BIO_free(b);
349 if (!env->key) {
350 crypto_log_errors(LOG_WARN, "Error parsing private key");
351 return -1;
353 return 0;
356 /** Read a PEM-encoded private key from the file named by
357 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
359 int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
361 char *contents;
362 int r;
364 /* Read the file into a string. */
365 contents = read_file_to_str(keyfile, 0);
366 if (!contents) {
367 log_fn(LOG_WARN, "Error reading private key from %s", keyfile);
368 return -1;
371 /* Try to parse it. */
372 r = crypto_pk_read_private_key_from_string(env, contents);
373 tor_free(contents);
374 if (r)
375 return -1; /* read_private_key_from_string already warned, so we don't.*/
377 /* Make sure it's valid. */
378 if (crypto_pk_check_key(env) <= 0)
379 return -1;
381 return 0;
384 /** PEM-encode the public key portion of <b>env</b> and write it to a
385 * newly allocated string. On success, set *<b>dest</b> to the new
386 * string, *<b>len</b> to the string's length, and return 0. On
387 * failure, return -1.
389 int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, size_t *len) {
390 BUF_MEM *buf;
391 BIO *b;
393 tor_assert(env);
394 tor_assert(env->key);
395 tor_assert(dest);
397 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
399 /* Now you can treat b as if it were a file. Just use the
400 * PEM_*_bio_* functions instead of the non-bio variants.
402 if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
403 crypto_log_errors(LOG_WARN, "writing public key to string");
404 return -1;
407 BIO_get_mem_ptr(b, &buf);
408 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
409 BIO_free(b);
411 tor_assert(buf->length >= 0);
412 *dest = tor_malloc(buf->length+1);
413 memcpy(*dest, buf->data, buf->length);
414 (*dest)[buf->length] = 0; /* null terminate it */
415 *len = buf->length;
416 BUF_MEM_free(buf);
418 return 0;
421 /** Read a PEM-encoded public key from the first <b>len</b> characters of
422 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
423 * failure.
425 int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, size_t len) {
426 BIO *b;
428 tor_assert(env);
429 tor_assert(src);
431 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
433 BIO_write(b, src, len);
435 if (env->key)
436 RSA_free(env->key);
437 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
438 BIO_free(b);
439 if (!env->key) {
440 crypto_log_errors(LOG_WARN, "reading public key from string");
441 return -1;
444 return 0;
447 /* Write the private key from 'env' into the file named by 'fname',
448 * PEM-encoded. Return 0 on success, -1 on failure.
451 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
452 const char *fname)
454 BIO *bio;
455 char *cp;
456 long len;
457 char *s;
458 int r;
460 tor_assert(PRIVATE_KEY_OK(env));
462 if (!(bio = BIO_new(BIO_s_mem())))
463 return -1;
464 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
465 == 0) {
466 crypto_log_errors(LOG_WARN, "writing private key");
467 BIO_free(bio);
468 return -1;
470 len = BIO_get_mem_data(bio, &cp);
471 tor_assert(len >= 0);
472 s = tor_malloc(len+1);
473 memcpy(s, cp, len);
474 s[len]='\0';
475 r = write_str_to_file(fname, s, 0);
476 BIO_free(bio);
477 free(s);
478 return r;
481 /** Allocate a new string in *<b>out</b>, containing the public portion of the
482 * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
483 * length of the encoded representation on success, and -1 on failure.
485 * <i>This function is for temporary use only. We need a simple
486 * one-line representation for keys to work around a bug in parsing
487 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
488 * in versions of Tor up to 0.0.9pre2.</i>
490 int crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
492 int len;
493 char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
494 tor_assert(env);
495 tor_assert(out);
496 len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
497 if (len < 0) {
498 return -1;
500 *out = tor_malloc(len * 2); /* too long, but safe. */
501 if (base64_encode(*out, len*2, buf, len) < 0) {
502 log_fn(LOG_WARN, "Error base64-encoding DER-encoded key");
503 tor_free(*out);
504 return -1;
506 /* Remove spaces */
507 tor_strstrip(*out, " \r\n\t");
508 return strlen(*out);
511 /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
512 * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
514 * <i>This function is for temporary use only. We need a simple
515 * one-line representation for keys to work around a bug in parsing
516 * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
517 * in versions of Tor up to 0.0.9pre2.</i>
519 crypto_pk_env_t *crypto_pk_DER64_decode_public_key(const char *in)
521 char partitioned[PK_BYTES*2 + 16];
522 char buf[PK_BYTES*2];
523 int len;
524 tor_assert(in);
525 len = strlen(in);
527 if (strlen(in) > PK_BYTES*2) {
528 return NULL;
530 /* base64_decode doesn't work unless we insert linebreaks every 64
531 * characters. how dumb. */
532 if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
533 ALWAYS_TERMINATE))
534 return NULL;
535 len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
536 if (len<0) {
537 log_fn(LOG_WARN,"Error base-64 decoding key");
538 return NULL;
540 return crypto_pk_asn1_decode(buf, len);
543 /** Return true iff <b>env</b> has a valid key.
545 int crypto_pk_check_key(crypto_pk_env_t *env)
547 int r;
548 tor_assert(env);
550 r = RSA_check_key(env->key);
551 if (r <= 0)
552 crypto_log_errors(LOG_WARN,"checking RSA key");
553 return r;
556 /** Compare the public-key components of a and b. Return -1 if a\<b, 0
557 * if a==b, and 1 if a\>b.
559 int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
560 int result;
562 if (!a || !b)
563 return -1;
565 if (!a->key || !b->key)
566 return -1;
568 tor_assert(PUBLIC_KEY_OK(a));
569 tor_assert(PUBLIC_KEY_OK(b));
570 result = BN_cmp((a->key)->n, (b->key)->n);
571 if (result)
572 return result;
573 return BN_cmp((a->key)->e, (b->key)->e);
576 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
577 int crypto_pk_keysize(crypto_pk_env_t *env)
579 tor_assert(env);
580 tor_assert(env->key);
582 return RSA_size(env->key);
585 /** Increase the reference count of <b>env</b>, and return it.
587 crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
588 tor_assert(env);
589 tor_assert(env->key);
591 env->refs++;
592 return env;
595 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
596 * in <b>env</b>, using the padding method <b>padding</b>. On success,
597 * write the result to <b>to</b>, and return the number of bytes
598 * written. On failure, return -1.
601 crypto_pk_public_encrypt(crypto_pk_env_t *env, unsigned char *to,
602 const unsigned char *from, int fromlen, int padding)
604 int r;
605 tor_assert(env);
606 tor_assert(from);
607 tor_assert(to);
609 r = RSA_public_encrypt(fromlen, (unsigned char*)from, to, env->key,
610 crypto_get_rsa_padding(padding));
611 if (r<0) {
612 crypto_log_errors(LOG_WARN, "performing RSA encryption");
613 return -1;
615 return r;
618 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private 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_private_decrypt(crypto_pk_env_t *env, unsigned char *to,
625 const unsigned char *from, int fromlen,
626 int padding, int warnOnFailure)
628 int r;
629 tor_assert(env);
630 tor_assert(from);
631 tor_assert(to);
632 tor_assert(env->key);
633 if (!env->key->p)
634 /* Not a private key */
635 return -1;
637 r = RSA_private_decrypt(fromlen, (unsigned char*)from, to, env->key,
638 crypto_get_rsa_padding(padding));
639 if (r<0) {
640 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_INFO,
641 "performing RSA decryption");
642 return -1;
644 return r;
647 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
648 * public key in <b>env</b>, using PKCS1 padding. On success, write the
649 * signed data to <b>to</b>, and return the number of bytes written.
650 * On failure, return -1.
653 crypto_pk_public_checksig(crypto_pk_env_t *env, unsigned char *to,
654 const unsigned char *from, int fromlen)
656 int r;
657 tor_assert(env);
658 tor_assert(from);
659 tor_assert(to);
660 r = RSA_public_decrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
662 if (r<0) {
663 crypto_log_errors(LOG_WARN, "checking RSA signature");
664 return -1;
666 return r;
669 /** Check a siglen-byte long signature at <b>sig</b> against
670 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
671 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
672 * SHA1(data). Else return -1.
675 crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const unsigned char *data,
676 int datalen, const unsigned char *sig, int siglen)
678 char digest[DIGEST_LEN];
679 char buf[PK_BYTES+1];
680 int r;
682 tor_assert(env);
683 tor_assert(data);
684 tor_assert(sig);
686 if (crypto_digest(digest,data,datalen)<0) {
687 log_fn(LOG_WARN, "couldn't compute digest");
688 return -1;
690 r = crypto_pk_public_checksig(env,buf,sig,siglen);
691 if (r != DIGEST_LEN) {
692 log_fn(LOG_WARN, "Invalid signature");
693 return -1;
695 if (memcmp(buf, digest, DIGEST_LEN)) {
696 log_fn(LOG_WARN, "Signature mismatched with digest.");
697 return -1;
700 return 0;
703 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
704 * <b>env</b>, using PKCS1 padding. On success, write the signature to
705 * <b>to</b>, and return the number of bytes written. On failure, return
706 * -1.
709 crypto_pk_private_sign(crypto_pk_env_t *env, unsigned char *to,
710 const unsigned char *from, int fromlen)
712 int r;
713 tor_assert(env);
714 tor_assert(from);
715 tor_assert(to);
716 if (!env->key->p)
717 /* Not a private key */
718 return -1;
720 r = RSA_private_encrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
721 if (r<0) {
722 crypto_log_errors(LOG_WARN, "generating RSA signature");
723 return -1;
725 return r;
728 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
729 * <b>from</b>; sign the data with the private key in <b>env</b>, and
730 * store it in <b>to</b>. Return the number of bytes written on
731 * success, and -1 on failure.
734 crypto_pk_private_sign_digest(crypto_pk_env_t *env, unsigned char *to,
735 const unsigned char *from, int fromlen)
737 char digest[DIGEST_LEN];
738 if (crypto_digest(digest,from,fromlen)<0)
739 return -1;
740 return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
743 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
744 * bytes of data from <b>from</b>, with padding type 'padding',
745 * storing the results on <b>to</b>.
747 * If no padding is used, the public key must be at least as large as
748 * <b>from</b>.
750 * Returns the number of bytes written on success, -1 on failure.
752 * The encrypted data consists of:
753 * - The source data, padded and encrypted with the public key, if the
754 * padded source data is no longer than the public key, and <b>force</b>
755 * is false, OR
756 * - The beginning of the source data prefixed with a 16-byte symmetric key,
757 * padded and encrypted with the public key; followed by the rest of
758 * the source data encrypted in AES-CTR mode with the symmetric key.
760 int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
761 unsigned char *to,
762 const unsigned char *from,
763 int fromlen,
764 int padding, int force)
766 int overhead, pkeylen, outlen, r, symlen;
767 crypto_cipher_env_t *cipher = NULL;
768 char buf[PK_BYTES+1];
770 tor_assert(env);
771 tor_assert(from);
772 tor_assert(to);
774 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
775 pkeylen = crypto_pk_keysize(env);
777 if (padding == PK_NO_PADDING && fromlen < pkeylen)
778 return -1;
780 if (!force && fromlen+overhead <= pkeylen) {
781 /* It all fits in a single encrypt. */
782 return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
784 cipher = crypto_new_cipher_env();
785 if (!cipher) return -1;
786 if (crypto_cipher_generate_key(cipher)<0)
787 goto err;
788 /* You can't just run around RSA-encrypting any bitstream: if it's
789 * greater than the RSA key, then OpenSSL will happily encrypt, and
790 * later decrypt to the wrong value. So we set the first bit of
791 * 'cipher->key' to 0 if we aren't padding. This means that our
792 * symmetric key is really only 127 bits.
794 if (padding == PK_NO_PADDING)
795 cipher->key[0] &= 0x7f;
796 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
797 goto err;
798 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
799 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
801 /* Length of symmetrically encrypted data. */
802 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
804 outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
805 if (outlen!=pkeylen) {
806 goto err;
808 r = crypto_cipher_encrypt(cipher, to+outlen,
809 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
811 if (r<0) goto err;
812 memset(buf, 0, sizeof(buf));
813 crypto_free_cipher_env(cipher);
814 return outlen + symlen;
815 err:
816 memset(buf, 0, sizeof(buf));
817 if (cipher) crypto_free_cipher_env(cipher);
818 return -1;
821 /** Invert crypto_pk_public_hybrid_encrypt. */
822 int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
823 unsigned char *to,
824 const unsigned char *from,
825 int fromlen,
826 int padding, int warnOnFailure)
828 int overhead, pkeylen, outlen, r;
829 crypto_cipher_env_t *cipher = NULL;
830 char buf[PK_BYTES+1];
832 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
833 pkeylen = crypto_pk_keysize(env);
835 if (fromlen <= pkeylen) {
836 return crypto_pk_private_decrypt(env,to,from,fromlen,padding,warnOnFailure);
838 outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,warnOnFailure);
839 if (outlen<0) {
840 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, "Error decrypting public-key data");
841 return -1;
843 if (outlen < CIPHER_KEY_LEN) {
844 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, "No room for a symmetric key");
845 return -1;
847 cipher = crypto_create_init_cipher(buf, 0);
848 if (!cipher) {
849 return -1;
851 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
852 outlen -= CIPHER_KEY_LEN;
853 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
854 if (r<0)
855 goto err;
856 memset(buf,0,sizeof(buf));
857 crypto_free_cipher_env(cipher);
858 return outlen + (fromlen-pkeylen);
859 err:
860 memset(buf,0,sizeof(buf));
861 if (cipher) crypto_free_cipher_env(cipher);
862 return -1;
865 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
866 * Return -1 on error, or the number of characters used on success.
868 int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
870 int len;
871 unsigned char *buf, *cp;
872 len = i2d_RSAPublicKey(pk->key, NULL);
873 if (len < 0 || len > dest_len)
874 return -1;
875 cp = buf = tor_malloc(len+1);
876 len = i2d_RSAPublicKey(pk->key, &cp);
877 if (len < 0) {
878 crypto_log_errors(LOG_WARN,"encoding public key");
879 tor_free(buf);
880 return -1;
882 /* We don't encode directly into 'dest', because that would be illegal
883 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
885 memcpy(dest,buf,len);
886 tor_free(buf);
887 return len;
890 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
891 * success and NULL on failure.
893 crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len)
895 RSA *rsa;
896 unsigned char *buf;
897 /* This ifdef suppresses a type warning. Take out the first case once
898 * everybody is using openssl 0.9.7 or later.
900 #if OPENSSL_VERSION_NUMBER < 0x00907000l
901 unsigned char *cp;
902 #else
903 const unsigned char *cp;
904 #endif
905 cp = buf = tor_malloc(len);
906 memcpy(buf,str,len);
907 rsa = d2i_RSAPublicKey(NULL, &cp, len);
908 tor_free(buf);
909 if (!rsa) {
910 crypto_log_errors(LOG_WARN,"decoding public key");
911 return NULL;
913 return _crypto_new_pk_env_rsa(rsa);
916 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
917 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
918 * Return 0 on success, -1 on failure.
920 int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
922 unsigned char *buf, *bufp;
923 int len;
925 len = i2d_RSAPublicKey(pk->key, NULL);
926 if (len < 0)
927 return -1;
928 buf = bufp = tor_malloc(len+1);
929 len = i2d_RSAPublicKey(pk->key, &bufp);
930 if (len < 0) {
931 crypto_log_errors(LOG_WARN,"encoding public key");
932 free(buf);
933 return -1;
935 if (crypto_digest(digest_out, buf, len) < 0) {
936 free(buf);
937 return -1;
939 free(buf);
940 return 0;
943 /** Given a private or public key <b>pk</b>, put a fingerprint of the
944 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
945 * space). Return 0 on success, -1 on failure.
947 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
948 * of the public key, converted to hexadecimal, in upper case, with a
949 * space after every four digits.
951 * If <b>add_space</b> is false, omit the spaces.
954 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
956 unsigned char digest[DIGEST_LEN];
957 unsigned char hexdigest[HEX_DIGEST_LEN+1];
958 if (crypto_pk_get_digest(pk, digest)) {
959 return -1;
961 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
962 if (add_space) {
963 if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
964 NEVER_TERMINATE)<0)
965 return -1;
966 } else {
967 strcpy(fp_out, hexdigest);
969 return 0;
972 /** Return true iff <b>s</b> is in the correct format for a fingerprint.
975 crypto_pk_check_fingerprint_syntax(const char *s)
977 int i;
978 for (i = 0; i < FINGERPRINT_LEN; ++i) {
979 if ((i%5) == 4) {
980 if (!TOR_ISSPACE(s[i])) return 0;
981 } else {
982 if (!TOR_ISXDIGIT(s[i])) return 0;
985 if (s[FINGERPRINT_LEN]) return 0;
986 return 1;
989 /* symmetric crypto */
991 /** Generate a new random key for the symmetric cipher in <b>env</b>.
992 * Return 0 on success, -1 on failure. Does not initialize the cipher.
994 int crypto_cipher_generate_key(crypto_cipher_env_t *env)
996 tor_assert(env);
998 return crypto_rand(env->key, CIPHER_KEY_LEN);
1001 /** Set the symmetric key for the cipher in <b>env</b> to the first
1002 * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
1003 * Return 0 on success, -1 on failure.
1005 int crypto_cipher_set_key(crypto_cipher_env_t *env, const unsigned char *key)
1007 tor_assert(env);
1008 tor_assert(key);
1010 if (!env->key)
1011 return -1;
1013 memcpy(env->key, key, CIPHER_KEY_LEN);
1015 return 0;
1018 /** Return a pointer to the key set for the cipher in <b>env</b>.
1020 const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
1022 return env->key;
1025 /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
1026 * success, -1 on failure.
1028 int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
1030 tor_assert(env);
1032 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1033 return 0;
1036 /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
1037 * success, -1 on failure.
1039 int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
1041 tor_assert(env);
1043 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
1044 return 0;
1047 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1048 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1049 * On failure, return -1.
1052 crypto_cipher_encrypt(crypto_cipher_env_t *env, unsigned char *to,
1053 const unsigned char *from, unsigned int fromlen)
1055 tor_assert(env);
1056 tor_assert(env->cipher);
1057 tor_assert(from);
1058 tor_assert(fromlen);
1059 tor_assert(to);
1061 aes_crypt(env->cipher, from, fromlen, to);
1062 return 0;
1065 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1066 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1067 * On failure, return -1.
1070 crypto_cipher_decrypt(crypto_cipher_env_t *env, unsigned char *to,
1071 const unsigned char *from, unsigned int fromlen)
1073 tor_assert(env);
1074 tor_assert(from);
1075 tor_assert(to);
1077 aes_crypt(env->cipher, from, fromlen, to);
1078 return 0;
1081 /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
1082 * Return 0 on success, -1 on failure.
1085 crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
1087 return crypto_cipher_advance(env, -delta);
1090 /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
1091 * Return 0 on success, -1 on failure.
1094 crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
1096 aes_adjust_counter(env->cipher, delta);
1097 return 0;
1100 /* SHA-1 */
1102 /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
1103 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1104 * Return 0 on success, -1 on failure.
1106 int crypto_digest(unsigned char *digest, const unsigned char *m, int len)
1108 tor_assert(m);
1109 tor_assert(digest);
1110 return (SHA1(m,len,digest) == NULL);
1113 struct crypto_digest_env_t {
1114 SHA_CTX d;
1117 /** Allocate and return a new digest object.
1119 crypto_digest_env_t *
1120 crypto_new_digest_env(void)
1122 crypto_digest_env_t *r;
1123 r = tor_malloc(sizeof(crypto_digest_env_t));
1124 SHA1_Init(&r->d);
1125 return r;
1128 /** Deallocate a digest object.
1130 void
1131 crypto_free_digest_env(crypto_digest_env_t *digest) {
1132 tor_free(digest);
1135 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1137 void
1138 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
1139 size_t len)
1141 tor_assert(digest);
1142 tor_assert(data);
1143 /* Using the SHA1_*() calls directly means we don't support doing
1144 * sha1 in hardware. But so far the delay of getting the question
1145 * to the hardware, and hearing the answer, is likely higher than
1146 * just doing it ourselves. Hashes are fast.
1148 SHA1_Update(&digest->d, (void*)data, len);
1151 /** Compute the hash of the data that has been passed to the digest
1152 * object; write the first out_len bytes of the result to <b>out</b>.
1153 * <b>out_len</b> must be \<= DIGEST_LEN.
1155 void crypto_digest_get_digest(crypto_digest_env_t *digest,
1156 char *out, size_t out_len)
1158 static char r[DIGEST_LEN];
1159 SHA_CTX tmpctx;
1160 tor_assert(digest);
1161 tor_assert(out);
1162 tor_assert(out_len <= DIGEST_LEN);
1163 /* memcpy into a temporary ctx, since SHA1_Final clears the context */
1164 memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
1165 SHA1_Final(r, &tmpctx);
1166 memcpy(out, r, out_len);
1169 /** Allocate and return a new digest object with the same state as
1170 * <b>digest</b>
1172 crypto_digest_env_t *
1173 crypto_digest_dup(const crypto_digest_env_t *digest)
1175 crypto_digest_env_t *r;
1176 tor_assert(digest);
1177 r = tor_malloc(sizeof(crypto_digest_env_t));
1178 memcpy(r,digest,sizeof(crypto_digest_env_t));
1179 return r;
1182 /** Replace the state of the digest object <b>into</b> with the state
1183 * of the digest object <b>from</b>.
1185 void
1186 crypto_digest_assign(crypto_digest_env_t *into,
1187 const crypto_digest_env_t *from)
1189 tor_assert(into);
1190 tor_assert(from);
1191 memcpy(into,from,sizeof(crypto_digest_env_t));
1194 /* DH */
1196 /** Shared P parameter for our DH key exchanged. */
1197 static BIGNUM *dh_param_p = NULL;
1198 /** Shared G parameter for our DH key exchanges. */
1199 static BIGNUM *dh_param_g = NULL;
1201 /** Initialize dh_param_p and dh_param_g if they are not already
1202 * set. */
1203 static void init_dh_param(void) {
1204 BIGNUM *p, *g;
1205 int r;
1206 if (dh_param_p && dh_param_g)
1207 return;
1209 p = BN_new();
1210 g = BN_new();
1211 tor_assert(p);
1212 tor_assert(g);
1214 #if 0
1215 /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
1216 prime, and supposedly it equals:
1217 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
1219 r = BN_hex2bn(&p,
1220 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
1221 "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
1222 "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
1223 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
1224 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
1225 "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
1226 "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
1227 "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
1228 #endif
1230 /* This is from rfc2409, section 6.2. It's a safe prime, and
1231 supposedly it equals:
1232 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
1234 /* See also rfc 3536 */
1235 r = BN_hex2bn(&p,
1236 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
1237 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
1238 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
1239 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
1240 "49286651ECE65381FFFFFFFFFFFFFFFF");
1241 tor_assert(r);
1243 r = BN_set_word(g, 2);
1244 tor_assert(r);
1245 dh_param_p = p;
1246 dh_param_g = g;
1249 /** Allocate and return a new DH object for a key exchange.
1251 crypto_dh_env_t *crypto_dh_new()
1253 crypto_dh_env_t *res = NULL;
1255 if (!dh_param_p)
1256 init_dh_param();
1258 res = tor_malloc_zero(sizeof(crypto_dh_env_t));
1260 if (!(res->dh = DH_new()))
1261 goto err;
1263 if (!(res->dh->p = BN_dup(dh_param_p)))
1264 goto err;
1266 if (!(res->dh->g = BN_dup(dh_param_g)))
1267 goto err;
1269 return res;
1270 err:
1271 crypto_log_errors(LOG_WARN, "creating DH object");
1272 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1273 if (res) free(res);
1274 return NULL;
1277 /** Return the length of the DH key in <b>dh</b>, in bytes.
1279 int crypto_dh_get_bytes(crypto_dh_env_t *dh)
1281 tor_assert(dh);
1282 return DH_size(dh->dh);
1285 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
1286 * success, -1 on failure.
1288 int crypto_dh_generate_public(crypto_dh_env_t *dh)
1290 if (!DH_generate_key(dh->dh)) {
1291 crypto_log_errors(LOG_WARN, "generating DH key");
1292 return -1;
1294 return 0;
1297 /** Generate g^x as necessary, and write the g^x for the key exchange
1298 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
1299 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
1301 int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
1303 int bytes;
1304 tor_assert(dh);
1305 if (!dh->dh->pub_key) {
1306 if (crypto_dh_generate_public(dh)<0)
1307 return -1;
1310 tor_assert(dh->dh->pub_key);
1311 bytes = BN_num_bytes(dh->dh->pub_key);
1312 tor_assert(bytes >= 0);
1313 if (pubkey_len < (size_t)bytes)
1314 return -1;
1316 memset(pubkey, 0, pubkey_len);
1317 BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
1319 return 0;
1322 #undef MIN
1323 #define MIN(a,b) ((a)<(b)?(a):(b))
1324 /** Given a DH key exchange object, and our peer's value of g^y (as a
1325 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
1326 * <b>secret_bytes_out</b> bytes of shared key material and write them
1327 * to <b>secret_out</b>. Return the number of bytes generated on success,
1328 * or -1 on failure.
1330 * (We generate key material by computing
1331 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
1332 * where || is concatenation.)
1334 int crypto_dh_compute_secret(crypto_dh_env_t *dh,
1335 const char *pubkey, size_t pubkey_len,
1336 char *secret_out, size_t secret_bytes_out)
1338 unsigned char hash[DIGEST_LEN];
1339 unsigned char *secret_tmp = NULL;
1340 BIGNUM *pubkey_bn = NULL;
1341 size_t secret_len=0;
1342 unsigned int i;
1343 int result=0;
1344 tor_assert(dh);
1345 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1347 if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
1348 goto error;
1349 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
1350 result = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
1351 if (result < 0) {
1352 log_fn(LOG_WARN,"DH_compute_key() failed.");
1353 goto error;
1355 secret_len = result;
1356 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1357 for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
1358 secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
1359 if (crypto_digest(hash, secret_tmp, secret_len+1))
1360 goto error;
1361 memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
1363 secret_len = secret_bytes_out;
1365 goto done;
1366 error:
1367 result = -1;
1368 done:
1369 crypto_log_errors(LOG_WARN, "completing DH handshake");
1370 if (pubkey_bn)
1371 BN_free(pubkey_bn);
1372 tor_free(secret_tmp);
1373 if (result < 0)
1374 return result;
1375 else
1376 return secret_len;
1379 /** Free a DH key exchange object.
1381 void crypto_dh_free(crypto_dh_env_t *dh)
1383 tor_assert(dh);
1384 tor_assert(dh->dh);
1385 DH_free(dh->dh);
1386 free(dh);
1389 /* random numbers */
1391 /** Seed OpenSSL's random number generator with DIGEST_LEN bytes from the
1392 * operating system. Return 0 on success, -1 on failure.
1394 int crypto_seed_rng(void)
1396 #ifdef MS_WINDOWS
1397 static int provider_set = 0;
1398 static HCRYPTPROV provider;
1399 char buf[DIGEST_LEN+1];
1401 if (!provider_set) {
1402 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, 0)) {
1403 if (GetLastError() != NTE_BAD_KEYSET) {
1404 log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
1405 return -1;
1407 /* Yes, we need to try it twice. */
1408 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1409 CRYPT_NEWKEYSET)) {
1410 log_fn(LOG_ERR,"Can't get CryptoAPI provider [2]");
1411 return -1;
1414 provider_set = 1;
1416 if (!CryptGenRandom(provider, DIGEST_LEN, buf)) {
1417 log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
1418 return -1;
1420 RAND_seed(buf, DIGEST_LEN);
1421 /* And add the current screen state to the entropy pool for
1422 * good measure. */
1423 RAND_screen();
1424 return 0;
1425 #else
1426 static const char *filenames[] = {
1427 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1429 int fd;
1430 int i, n;
1431 char buf[DIGEST_LEN+1];
1433 for (i = 0; filenames[i]; ++i) {
1434 fd = open(filenames[i], O_RDONLY, 0);
1435 if (fd<0) continue;
1436 log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
1437 n = read(fd, buf, DIGEST_LEN);
1438 close(fd);
1439 if (n != DIGEST_LEN) {
1440 log_fn(LOG_WARN, "Error reading from entropy source");
1441 return -1;
1443 RAND_seed(buf, DIGEST_LEN);
1444 return 0;
1447 log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
1448 return -1;
1449 #endif
1452 /** Write n bytes of strong random data to <b>to</b>. Return 0 on
1453 * success, -1 on failure.
1455 int crypto_rand(unsigned char *to, unsigned int n)
1457 int r;
1458 tor_assert(to);
1459 r = RAND_bytes(to, n);
1460 if (r == 0)
1461 crypto_log_errors(LOG_WARN, "generating random data");
1462 return (r == 1) ? 0 : -1;
1465 /** Write n bytes of pseudorandom data to <b>to</b>. Return 0 on
1466 * success, -1 on failure.
1468 void crypto_pseudo_rand(unsigned char *to, unsigned int n)
1470 tor_assert(to);
1471 if (RAND_pseudo_bytes(to, n) == -1) {
1472 log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
1473 crypto_log_errors(LOG_WARN, "generating random data");
1474 exit(1);
1478 /** Return a pseudorandom integer, chosen uniformly from the values
1479 * between 0 and max-1. */
1480 int crypto_pseudo_rand_int(unsigned int max) {
1481 unsigned int val;
1482 unsigned int cutoff;
1483 tor_assert(max < UINT_MAX);
1484 tor_assert(max > 0); /* don't div by 0 */
1486 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1487 * distribution with clipping at the upper end of unsigned int's
1488 * range.
1490 cutoff = UINT_MAX - (UINT_MAX%max);
1491 while (1) {
1492 crypto_pseudo_rand((unsigned char*) &val, sizeof(val));
1493 if (val < cutoff)
1494 return val % max;
1498 /** Return a randomly chosen element of sl; or NULL if sl is empty.
1500 void *smartlist_choose(const smartlist_t *sl) {
1501 size_t len;
1502 len = smartlist_len(sl);
1503 if (len)
1504 return smartlist_get(sl,crypto_pseudo_rand_int(len));
1505 return NULL; /* no elements to choose from */
1508 /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
1509 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1510 * bytes. Return the number of bytes written on success; -1 if
1511 * destlen is too short, or other failure.
1514 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1516 EVP_ENCODE_CTX ctx;
1517 int len, ret;
1519 /* 48 bytes of input -> 64 bytes of output plus newline.
1520 Plus one more byte, in case I'm wrong.
1522 if (destlen < ((srclen/48)+1)*66)
1523 return -1;
1524 if (destlen > SIZE_T_CEILING)
1525 return -1;
1527 EVP_EncodeInit(&ctx);
1528 EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1529 EVP_EncodeFinal(&ctx, dest+len, &ret);
1530 ret += len;
1531 return ret;
1534 /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
1535 * the result into <b>dest</b>, if it will fit within <b>destlen</b>
1536 * bytes. Return the number of bytes written on success; -1 if
1537 * destlen is too short, or other failure.
1539 * NOTE: destlen should be a little longer than the amount of data it
1540 * will contain, since we check for sufficient space conservatively.
1541 * Here, "a little" is around 64-ish bytes.
1544 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
1546 EVP_ENCODE_CTX ctx;
1547 int len, ret;
1548 /* 64 bytes of input -> *up to* 48 bytes of output.
1549 Plus one more byte, in case I'm wrong.
1551 if (destlen < ((srclen/64)+1)*49)
1552 return -1;
1553 if (destlen > SIZE_T_CEILING)
1554 return -1;
1556 EVP_DecodeInit(&ctx);
1557 EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1558 EVP_DecodeFinal(&ctx, dest, &ret);
1559 ret += len;
1560 return ret;
1563 /** Implements base32 encoding as in rfc3548. Limitation: Requires
1564 * that srclen*8 is a multiple of 5.
1566 void
1567 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
1569 unsigned int nbits, i, bit, v, u;
1570 nbits = srclen * 8;
1572 tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
1573 tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
1574 tor_assert(destlen < SIZE_T_CEILING);
1576 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1577 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1578 v = ((uint8_t)src[bit/8]) << 8;
1579 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1580 /* set u to the 5-bit value at the bit'th bit of src. */
1581 u = (v >> (11-(bit%8))) & 0x1F;
1582 dest[i] = BASE32_CHARS[u];
1584 dest[i] = '\0';
1587 /** Implement RFC2440-style iterated-salted S2K conversion: convert the
1588 * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
1589 * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
1590 * are a salt; the 9th byte describes how much iteration to do.
1591 * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
1593 void
1594 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
1595 size_t secret_len, const char *s2k_specifier)
1597 crypto_digest_env_t *d;
1598 uint8_t c;
1599 size_t count;
1600 char *tmp;
1601 tor_assert(key_out_len < SIZE_T_CEILING);
1603 #define EXPBIAS 6
1604 c = s2k_specifier[8];
1605 count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
1606 #undef EXPBIAS
1608 tor_assert(key_out_len <= DIGEST_LEN);
1610 d = crypto_new_digest_env();
1611 tmp = tor_malloc(8+secret_len);
1612 memcpy(tmp,s2k_specifier,8);
1613 memcpy(tmp+8,secret,secret_len);
1614 secret_len += 8;
1615 while (count) {
1616 if (count >= secret_len) {
1617 crypto_digest_add_bytes(d, tmp, secret_len);
1618 count -= secret_len;
1619 } else {
1620 crypto_digest_add_bytes(d, tmp, count);
1621 count = 0;
1624 crypto_digest_get_digest(d, key_out, key_out_len);
1625 tor_free(tmp);
1626 crypto_free_digest_env(d);