Make Tor build on win32 with VC6 without warnings.
[tor.git] / src / common / crypto.c
blob4599e0cbb63f67a548fb73fef2385c50ea567dc7
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "orconfig.h"
7 #ifdef MS_WINDOWS
8 #define WIN32_WINNT 0x400
9 #define _WIN32_WINNT 0x400
10 #define WIN32_LEAN_AND_MEAN
11 #include <windows.h>
12 #include <wincrypt.h>
13 #endif
15 #include <string.h>
17 #include <openssl/err.h>
18 #include <openssl/rsa.h>
19 #include <openssl/pem.h>
20 #include <openssl/evp.h>
21 #include <openssl/rand.h>
22 #include <openssl/opensslv.h>
23 #include <openssl/bn.h>
24 #include <openssl/dh.h>
25 #include <openssl/rsa.h>
26 #include <openssl/dh.h>
28 #include <stdlib.h>
29 #include <assert.h>
30 #include <stdio.h>
31 #include <limits.h>
33 #ifdef HAVE_CTYPE_H
34 #include <ctype.h>
35 #endif
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #endif
42 #ifdef HAVE_SYS_FCNTL_H
43 #include <sys/fcntl.h>
44 #endif
46 #include "crypto.h"
47 #include "log.h"
48 #include "aes.h"
49 #include "util.h"
51 #if OPENSSL_VERSION_NUMBER < 0x00905000l
52 #error "We require openssl >= 0.9.5"
53 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
54 #define OPENSSL_095
55 #endif
58 * Certain functions that return a success code in OpenSSL 0.9.6 return void
59 * (and don't indicate errors) in OpenSSL version 0.9.5.
61 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
63 #ifdef OPENSSL_095
64 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
65 #else
66 #define RETURN_SSL_OUTCOME(exp) return !(exp)
67 #endif
69 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
70 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
72 struct crypto_pk_env_t
74 int refs; /* reference counting; so we don't have to copy keys */
75 RSA *key;
78 struct crypto_cipher_env_t
80 unsigned char key[CIPHER_KEY_LEN];
81 unsigned char iv[CIPHER_IV_LEN+1];
82 /* +1 because some compilers don't like a length of 0 */
83 aes_cnt_cipher_t *cipher;
86 struct crypto_dh_env_t {
87 DH *dh;
90 static INLINE int
91 crypto_get_rsa_padding_overhead(int padding) {
92 switch(padding)
94 case RSA_NO_PADDING: return 0;
95 case RSA_PKCS1_OAEP_PADDING: return 42;
96 case RSA_PKCS1_PADDING: return 11;
97 default: tor_assert(0); return -1;
101 static INLINE int
102 crypto_get_rsa_padding(int padding) {
103 switch(padding)
105 case PK_NO_PADDING: return RSA_NO_PADDING;
106 case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
107 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
108 default: tor_assert(0); return -1;
112 static int _crypto_global_initialized = 0;
115 /* errors */
116 static void
117 crypto_log_errors(int severity, const char *doing)
119 int err;
120 const char *msg, *lib, *func;
121 while ((err = ERR_get_error()) != 0) {
122 msg = (const char*)ERR_reason_error_string(err);
123 lib = (const char*)ERR_lib_error_string(err);
124 func = (const char*)ERR_func_error_string(err);
125 if (!msg) msg = "(null)";
126 if (doing) {
127 log(severity, "crypto error while %s: %s (in %s:%s)", doing, msg, lib,func);
128 } else {
129 log(severity, "crypto error: %s (in %s:%s)", msg, lib, func);
133 int crypto_global_init()
135 if (!_crypto_global_initialized) {
136 ERR_load_crypto_strings();
137 _crypto_global_initialized = 1;
139 return 0;
142 int crypto_global_cleanup()
144 ERR_free_strings();
145 return 0;
148 /* used by tortls.c */
149 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
151 crypto_pk_env_t *env;
152 tor_assert(rsa);
153 env = tor_malloc(sizeof(crypto_pk_env_t));
154 env->refs = 1;
155 env->key = rsa;
156 return env;
159 /* used by tortls.c */
160 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
162 return env->key;
165 /* used by tortls.c */
166 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
168 RSA *key = NULL;
169 EVP_PKEY *pkey = NULL;
170 tor_assert(env->key);
171 if (private) {
172 if (!(key = RSAPrivateKey_dup(env->key)))
173 goto error;
174 } else {
175 if (!(key = RSAPublicKey_dup(env->key)))
176 goto error;
178 if (!(pkey = EVP_PKEY_new()))
179 goto error;
180 if (!(EVP_PKEY_assign_RSA(pkey, key)))
181 goto error;
182 return pkey;
183 error:
184 if (pkey)
185 EVP_PKEY_free(pkey);
186 if (key)
187 RSA_free(key);
188 return NULL;
191 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh)
193 return dh->dh;
196 crypto_pk_env_t *crypto_new_pk_env(void)
198 RSA *rsa;
200 rsa = RSA_new();
201 if (!rsa) return NULL;
202 return _crypto_new_pk_env_rsa(rsa);
205 void crypto_free_pk_env(crypto_pk_env_t *env)
207 tor_assert(env);
209 if(--env->refs > 0)
210 return;
212 if (env->key)
213 RSA_free(env->key);
215 free(env);
219 /* Create a new crypto_cipher_env_t for a given onion cipher type, key,
220 * iv, and encryption flag (1=encrypt, 0=decrypt). Return the crypto object
221 * on success; NULL on failure.
223 crypto_cipher_env_t *
224 crypto_create_init_cipher(const char *key, const char *iv, int encrypt_mode)
226 int r;
227 crypto_cipher_env_t *crypto = NULL;
229 if (! (crypto = crypto_new_cipher_env())) {
230 log_fn(LOG_WARN, "Unable to allocate crypto object");
231 return NULL;
234 if (crypto_cipher_set_key(crypto, key)) {
235 crypto_log_errors(LOG_WARN, "setting symmetric key");
236 goto error;
239 if (crypto_cipher_set_iv(crypto, iv)) {
240 crypto_log_errors(LOG_WARN, "setting IV");
241 goto error;
244 if (encrypt_mode)
245 r = crypto_cipher_encrypt_init_cipher(crypto);
246 else
247 r = crypto_cipher_decrypt_init_cipher(crypto);
249 if (r)
250 goto error;
251 return crypto;
253 error:
254 if (crypto)
255 crypto_free_cipher_env(crypto);
256 return NULL;
259 crypto_cipher_env_t *crypto_new_cipher_env()
261 crypto_cipher_env_t *env;
263 env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
264 env->cipher = aes_new_cipher();
265 return env;
268 void crypto_free_cipher_env(crypto_cipher_env_t *env)
270 tor_assert(env);
272 tor_assert(env->cipher);
273 aes_free_cipher(env->cipher);
274 tor_free(env);
277 /* public key crypto */
278 int crypto_pk_generate_key(crypto_pk_env_t *env)
280 tor_assert(env);
282 if (env->key)
283 RSA_free(env->key);
284 env->key = RSA_generate_key(PK_BITS,65537, NULL, NULL);
285 if (!env->key) {
286 crypto_log_errors(LOG_WARN, "generating RSA key");
287 return -1;
290 return 0;
293 static int crypto_pk_read_private_key_from_file(crypto_pk_env_t *env,
294 FILE *src)
296 tor_assert(env && src);
298 if (env->key)
299 RSA_free(env->key);
300 env->key = PEM_read_RSAPrivateKey(src, NULL, NULL, NULL);
301 if (!env->key) {
302 crypto_log_errors(LOG_WARN, "reading private key from file");
303 return -1;
306 return 0;
309 int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
311 FILE *f_pr;
313 tor_assert(env && keyfile);
315 if(strspn(keyfile,CONFIG_LEGAL_FILENAME_CHARACTERS) != strlen(keyfile)) {
316 /* filename contains nonlegal characters */
317 return -1;
320 /* open the keyfile */
321 f_pr=fopen(keyfile,"rb");
322 if (!f_pr)
323 return -1;
325 /* read the private key */
326 if(crypto_pk_read_private_key_from_file(env, f_pr) < 0) {
327 fclose(f_pr);
328 return -1;
330 fclose(f_pr);
332 /* check the private key */
333 if (crypto_pk_check_key(env) <= 0)
334 return -1;
336 return 0;
339 int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, int *len) {
340 BUF_MEM *buf;
341 BIO *b;
343 tor_assert(env && env->key && dest);
345 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
347 /* Now you can treat b as if it were a file. Just use the
348 * PEM_*_bio_* functions instead of the non-bio variants.
350 if(!PEM_write_bio_RSAPublicKey(b, env->key)) {
351 crypto_log_errors(LOG_WARN, "writing public key to string");
352 return -1;
355 BIO_get_mem_ptr(b, &buf);
356 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
357 BIO_free(b);
359 *dest = tor_malloc(buf->length+1);
360 memcpy(*dest, buf->data, buf->length);
361 (*dest)[buf->length] = 0; /* null terminate it */
362 *len = buf->length;
363 BUF_MEM_free(buf);
365 return 0;
368 int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, int len) {
369 BIO *b;
371 tor_assert(env && src);
373 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
375 BIO_write(b, src, len);
377 if (env->key)
378 RSA_free(env->key);
379 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
380 BIO_free(b);
381 if(!env->key) {
382 crypto_log_errors(LOG_WARN, "reading public key from string");
383 return -1;
386 return 0;
390 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
391 const char *fname)
393 BIO *bio;
394 char *cp;
395 long len;
396 char *s;
397 int r;
399 tor_assert(PRIVATE_KEY_OK(env));
401 if (!(bio = BIO_new(BIO_s_mem())))
402 return -1;
403 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
404 == 0) {
405 crypto_log_errors(LOG_WARN, "writing private key");
406 BIO_free(bio);
407 return -1;
409 len = BIO_get_mem_data(bio, &cp);
410 s = tor_malloc(len+1);
411 strncpy(s, cp, len);
412 s[len] = '\0';
413 r = write_str_to_file(fname, s);
414 BIO_free(bio);
415 free(s);
416 return r;
419 int crypto_pk_check_key(crypto_pk_env_t *env)
421 int r;
422 tor_assert(env);
424 r = RSA_check_key(env->key);
425 if (r <= 0)
426 crypto_log_errors(LOG_WARN,"checking RSA key");
427 return r;
430 int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
431 int result;
433 if (!a || !b)
434 return -1;
436 if (!a->key || !b->key)
437 return -1;
439 tor_assert(PUBLIC_KEY_OK(a));
440 tor_assert(PUBLIC_KEY_OK(b));
441 result = BN_cmp((a->key)->n, (b->key)->n);
442 if (result)
443 return result;
444 return BN_cmp((a->key)->e, (b->key)->e);
447 /* return the size of the public key modulus in 'env', in bytes. */
448 int crypto_pk_keysize(crypto_pk_env_t *env)
450 tor_assert(env && env->key);
452 return RSA_size(env->key);
455 crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
456 tor_assert(env && env->key);
458 env->refs++;
459 return env;
462 int crypto_pk_public_encrypt(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to, int padding)
464 int r;
465 tor_assert(env && from && to);
467 r = RSA_public_encrypt(fromlen, (unsigned char*)from, to, env->key,
468 crypto_get_rsa_padding(padding));
469 if (r<0)
470 crypto_log_errors(LOG_WARN, "performing RSA encryption");
471 return r;
474 int crypto_pk_private_decrypt(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to, int padding)
476 int r;
477 tor_assert(env && from && to && env->key);
478 if (!env->key->p)
479 /* Not a private key */
480 return -1;
482 r = RSA_private_decrypt(fromlen, (unsigned char*)from, to, env->key,
483 crypto_get_rsa_padding(padding));
484 if (r<0)
485 crypto_log_errors(LOG_WARN, "performing RSA decryption");
486 return r;
489 int crypto_pk_public_checksig(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to)
491 int r;
492 tor_assert(env && from && to);
493 r = RSA_public_decrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
495 if (r<0)
496 crypto_log_errors(LOG_WARN, "checking RSA signature");
497 return r;
500 int crypto_pk_private_sign(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to)
502 int r;
503 tor_assert(env && from && to);
504 if (!env->key->p)
505 /* Not a private key */
506 return -1;
508 r = RSA_private_encrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
509 if (r<0)
510 crypto_log_errors(LOG_WARN, "generating RSA signature");
511 return r;
514 /* Return 0 if sig is a correct signature for SHA1(data). Else return -1.
516 int crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const unsigned char *data, int datalen, const unsigned char *sig, int siglen)
518 char digest[DIGEST_LEN];
519 char buf[PK_BYTES+1];
520 int r;
522 tor_assert(env && data && sig);
524 if (crypto_digest(data,datalen,digest)<0) {
525 log_fn(LOG_WARN, "couldn't compute digest");
526 return -1;
528 r = crypto_pk_public_checksig(env,sig,siglen,buf);
529 if (r != DIGEST_LEN) {
530 log_fn(LOG_WARN, "Invalid signature");
531 return -1;
533 if (memcmp(buf, digest, DIGEST_LEN)) {
534 log_fn(LOG_WARN, "Signature mismatched with digest.");
535 return -1;
538 return 0;
541 /* Fill 'to' with a signature of SHA1(from).
543 int crypto_pk_private_sign_digest(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to)
545 char digest[DIGEST_LEN];
546 if (crypto_digest(from,fromlen,digest)<0)
547 return 0;
548 return crypto_pk_private_sign(env,digest,DIGEST_LEN,to);
552 /* Perform a hybrid (public/secret) encryption on 'fromlen' bytes of data
553 * from 'from', with padding type 'padding', storing the results on 'to'.
555 * If no padding is used, the public key must be at least as large as
556 * 'from'.
558 * Returns the number of bytes written on success, -1 on failure.
560 * The encrypted data consists of:
562 * The source data, padded and encrypted with the public key, if the
563 * padded source data is no longer than the public key, and "force"
564 * is false.
565 * OR
566 * The beginning of the source data prefixed with a 16-byte symmetric key,
567 * padded and encrypted with the public key; followed by the rest of
568 * the source data encrypted in AES-CTR mode with the symmetric key.
571 int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
572 const unsigned char *from,
573 int fromlen, unsigned char *to,
574 int padding, int force)
576 int overhead, pkeylen, outlen, r, symlen;
577 crypto_cipher_env_t *cipher = NULL;
578 char buf[PK_BYTES+1];
580 tor_assert(env && from && to);
582 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
583 pkeylen = crypto_pk_keysize(env);
585 if (padding == PK_NO_PADDING && fromlen < pkeylen)
586 return -1;
588 if (!force && fromlen+overhead <= pkeylen) {
589 /* It all fits in a single encrypt. */
590 return crypto_pk_public_encrypt(env,from,fromlen,to,padding);
592 cipher = crypto_new_cipher_env();
593 if (!cipher) return -1;
594 if (crypto_cipher_generate_key(cipher)<0)
595 goto err;
596 /* You can't just run around RSA-encrypting any bitstream: if it's
597 * greater than the RSA key, then OpenSSL will happily encrypt, and
598 * later decrypt to the wrong value. So we set the first bit of
599 * 'cipher->key' to 0 if we aren't padding. This means that our
600 * symmetric key is really only 127 bits.
602 if (padding == PK_NO_PADDING)
603 cipher->key[0] &= 0x7f;
604 if (crypto_cipher_encrypt_init_cipher(cipher)<0)
605 goto err;
606 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
607 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
609 /* Length of symmetrically encrypted data. */
610 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
612 outlen = crypto_pk_public_encrypt(env,buf,pkeylen-overhead,to,padding);
613 if (outlen!=pkeylen) {
614 goto err;
616 r = crypto_cipher_encrypt(cipher,
617 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen,
618 to+outlen);
620 if (r<0) goto err;
621 memset(buf, 0, sizeof(buf));
622 crypto_free_cipher_env(cipher);
623 return outlen + symlen;
624 err:
625 memset(buf, 0, sizeof(buf));
626 if (cipher) crypto_free_cipher_env(cipher);
627 return -1;
630 /* Invert crypto_pk_public_hybrid_encrypt. */
631 int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
632 const unsigned char *from,
633 int fromlen, unsigned char *to,
634 int padding)
636 int overhead, pkeylen, outlen, r;
637 crypto_cipher_env_t *cipher = NULL;
638 char buf[PK_BYTES+1];
640 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
641 pkeylen = crypto_pk_keysize(env);
643 if (fromlen <= pkeylen) {
644 return crypto_pk_private_decrypt(env,from,fromlen,to,padding);
646 outlen = crypto_pk_private_decrypt(env,from,pkeylen,buf,padding);
647 if (outlen<0) {
648 /* this is only log-levelinfo, because when we're decrypting
649 * onions, we try several keys to see which will work */
650 log_fn(LOG_INFO, "Error decrypting public-key data");
651 return -1;
653 if (outlen < CIPHER_KEY_LEN) {
654 log_fn(LOG_WARN, "No room for a symmetric key");
655 return -1;
657 cipher = crypto_create_init_cipher(buf, NULL, 0);
658 if (!cipher) {
659 return -1;
661 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
662 outlen -= CIPHER_KEY_LEN;
663 r = crypto_cipher_decrypt(cipher, from+pkeylen, fromlen-pkeylen,
664 to+outlen);
665 if (r<0)
666 goto err;
667 memset(buf,0,sizeof(buf));
668 crypto_free_cipher_env(cipher);
669 return outlen + (fromlen-pkeylen);
670 err:
671 memset(buf,0,sizeof(buf));
672 if (cipher) crypto_free_cipher_env(cipher);
673 return -1;
676 /* Encode the public portion of 'pk' into 'dest'. Return -1 on error,
677 * or the number of characters used on success.
679 int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
681 int len;
682 unsigned char *buf, *cp;
683 len = i2d_RSAPublicKey(pk->key, NULL);
684 if (len < 0 || len > dest_len)
685 return -1;
686 cp = buf = tor_malloc(len+1);
687 len = i2d_RSAPublicKey(pk->key, &cp);
688 if (len < 0) {
689 crypto_log_errors(LOG_WARN,"encoding public key");
690 tor_free(buf);
691 return -1;
693 /* We don't encode directly into 'dest', because that would be illegal
694 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
696 memcpy(dest,buf,len);
697 tor_free(buf);
698 return len;
701 /* Decode an ASN1-encoded public key from str.
703 crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len)
705 RSA *rsa;
706 unsigned char *buf;
707 /* This ifdef suppresses a type warning. Take out the first case once
708 * everybody is using openssl 0.9.7 or later.
710 #if OPENSSL_VERSION_NUMBER < 0x00907000l
711 unsigned char *cp;
712 #else
713 const unsigned char *cp;
714 #endif
715 cp = buf = tor_malloc(len);
716 memcpy(buf,str,len);
717 rsa = d2i_RSAPublicKey(NULL, &cp, len);
718 tor_free(buf);
719 if (!rsa) {
720 crypto_log_errors(LOG_WARN,"decoding public key");
721 return NULL;
723 return _crypto_new_pk_env_rsa(rsa);
726 /* Given a private or public key pk, put a SHA1 hash of the public key into
727 * digest_out (must have DIGEST_LEN bytes of space).
729 int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
731 unsigned char *buf, *bufp;
732 int len;
734 len = i2d_RSAPublicKey(pk->key, NULL);
735 if (len < 0)
736 return -1;
737 buf = bufp = tor_malloc(len+1);
738 len = i2d_RSAPublicKey(pk->key, &bufp);
739 if (len < 0) {
740 crypto_log_errors(LOG_WARN,"encoding public key");
741 free(buf);
742 return -1;
744 if (crypto_digest(buf, len, digest_out) < 0) {
745 free(buf);
746 return -1;
748 free(buf);
749 return 0;
752 /* Given a private or public key pk, put a fingerprint of the
753 * public key into fp_out (must have at least FINGERPRINT_LEN+1 bytes of
754 * space).
757 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out)
759 unsigned char *bufp;
760 unsigned char digest[DIGEST_LEN];
761 unsigned char buf[FINGERPRINT_LEN+1];
762 int i;
763 if (crypto_pk_get_digest(pk, digest)) {
764 return -1;
766 bufp = buf;
767 for (i = 0; i < DIGEST_LEN; ++i) {
768 sprintf(bufp,"%02X",digest[i]);
769 bufp += 2;
770 if (i%2 && i != 19) {
771 *bufp++ = ' ';
774 *bufp = '\0';
775 tor_assert(strlen(buf) == FINGERPRINT_LEN);
776 tor_assert(crypto_pk_check_fingerprint_syntax(buf));
777 strcpy(fp_out, buf);
778 return 0;
782 crypto_pk_check_fingerprint_syntax(const char *s)
784 int i;
785 for (i = 0; i < FINGERPRINT_LEN; ++i) {
786 if ((i%5) == 4) {
787 if (!isspace((int)s[i])) return 0;
788 } else {
789 if (!isxdigit((int)s[i])) return 0;
792 if (s[FINGERPRINT_LEN]) return 0;
793 return 1;
796 /* symmetric crypto */
797 int crypto_cipher_generate_key(crypto_cipher_env_t *env)
799 tor_assert(env);
801 return crypto_rand(CIPHER_KEY_LEN, env->key);
804 int crypto_cipher_set_iv(crypto_cipher_env_t *env, const unsigned char *iv)
806 tor_assert(env && (CIPHER_IV_LEN==0 || iv));
808 if (!CIPHER_IV_LEN)
809 return 0;
811 if (!env->iv)
812 return -1;
814 memcpy(env->iv, iv, CIPHER_IV_LEN);
816 return 0;
819 int crypto_cipher_set_key(crypto_cipher_env_t *env, const unsigned char *key)
821 tor_assert(env && key);
823 if (!env->key)
824 return -1;
826 memcpy(env->key, key, CIPHER_KEY_LEN);
828 return 0;
831 const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
833 return env->key;
836 int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
838 tor_assert(env);
840 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
841 return 0;
844 int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
846 tor_assert(env);
848 aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
849 return 0;
852 int crypto_cipher_encrypt(crypto_cipher_env_t *env, const unsigned char *from, unsigned int fromlen, unsigned char *to)
854 tor_assert(env && env->cipher && from && fromlen && to);
856 aes_crypt(env->cipher, from, fromlen, to);
857 return 0;
860 int crypto_cipher_decrypt(crypto_cipher_env_t *env, const unsigned char *from, unsigned int fromlen, unsigned char *to)
862 tor_assert(env && from && to);
864 aes_crypt(env->cipher, from, fromlen, to);
865 return 0;
869 crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
871 return crypto_cipher_advance(env, -delta);
875 crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
877 aes_adjust_counter(env->cipher, delta);
878 return 0;
881 /* SHA-1 */
882 int crypto_digest(const unsigned char *m, int len, unsigned char *digest)
884 tor_assert(m && digest);
885 return (SHA1(m,len,digest) == NULL);
888 struct crypto_digest_env_t {
889 SHA_CTX d;
892 crypto_digest_env_t *
893 crypto_new_digest_env(void)
895 crypto_digest_env_t *r;
896 r = tor_malloc(sizeof(crypto_digest_env_t));
897 SHA1_Init(&r->d);
898 return r;
901 void
902 crypto_free_digest_env(crypto_digest_env_t *digest) {
903 tor_free(digest);
906 void
907 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
908 size_t len)
910 tor_assert(digest);
911 tor_assert(data);
912 SHA1_Update(&digest->d, (void*)data, len);
915 void crypto_digest_get_digest(crypto_digest_env_t *digest,
916 char *out, size_t out_len)
918 static char r[DIGEST_LEN];
919 tor_assert(digest && out);
920 tor_assert(out_len <= DIGEST_LEN);
921 SHA1_Final(r, &digest->d);
922 memcpy(out, r, out_len);
925 crypto_digest_env_t *
926 crypto_digest_dup(const crypto_digest_env_t *digest)
928 crypto_digest_env_t *r;
929 tor_assert(digest);
930 r = tor_malloc(sizeof(crypto_digest_env_t));
931 memcpy(r,digest,sizeof(crypto_digest_env_t));
932 return r;
935 void
936 crypto_digest_assign(crypto_digest_env_t *into,
937 const crypto_digest_env_t *from)
939 tor_assert(into && from);
940 memcpy(into,from,sizeof(crypto_digest_env_t));
943 /* DH */
944 static BIGNUM *dh_param_p = NULL;
945 static BIGNUM *dh_param_g = NULL;
947 static void init_dh_param() {
948 BIGNUM *p, *g;
949 int r;
950 if (dh_param_p && dh_param_g)
951 return;
953 p = BN_new();
954 g = BN_new();
955 tor_assert(p && g);
957 #if 0
958 /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
959 prime, and supposedly it equals:
960 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
962 r = BN_hex2bn(&p,
963 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
964 "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
965 "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
966 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
967 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
968 "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
969 "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
970 "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
971 #endif
973 /* This is from rfc2409, section 6.2. It's a safe prime, and
974 supposedly it equals:
975 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
977 /* See also rfc 3536 */
978 r = BN_hex2bn(&p,
979 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
980 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
981 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
982 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
983 "49286651ECE65381FFFFFFFFFFFFFFFF");
984 tor_assert(r);
986 r = BN_set_word(g, 2);
987 tor_assert(r);
988 dh_param_p = p;
989 dh_param_g = g;
992 crypto_dh_env_t *crypto_dh_new()
994 crypto_dh_env_t *res = NULL;
996 if (!dh_param_p)
997 init_dh_param();
999 res = tor_malloc(sizeof(crypto_dh_env_t));
1000 res->dh = NULL;
1002 if (!(res->dh = DH_new()))
1003 goto err;
1005 if (!(res->dh->p = BN_dup(dh_param_p)))
1006 goto err;
1008 if (!(res->dh->g = BN_dup(dh_param_g)))
1009 goto err;
1011 return res;
1012 err:
1013 crypto_log_errors(LOG_WARN, "creating DH object");
1014 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
1015 if (res) free(res);
1016 return NULL;
1018 int crypto_dh_get_bytes(crypto_dh_env_t *dh)
1020 tor_assert(dh);
1021 return DH_size(dh->dh);
1023 int crypto_dh_generate_public(crypto_dh_env_t *dh)
1025 if (!DH_generate_key(dh->dh)) {
1026 crypto_log_errors(LOG_WARN, "generating DH key");
1027 return -1;
1029 return 0;
1031 int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, int pubkey_len)
1033 int bytes;
1034 tor_assert(dh);
1035 if (!dh->dh->pub_key) {
1036 if (crypto_dh_generate_public(dh)<0)
1037 return -1;
1040 tor_assert(dh->dh->pub_key);
1041 bytes = BN_num_bytes(dh->dh->pub_key);
1042 if (pubkey_len < bytes)
1043 return -1;
1045 memset(pubkey, 0, pubkey_len);
1046 BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
1048 return 0;
1051 #undef MIN
1052 #define MIN(a,b) ((a)<(b)?(a):(b))
1053 int crypto_dh_compute_secret(crypto_dh_env_t *dh,
1054 const char *pubkey, int pubkey_len,
1055 char *secret_out, int secret_bytes_out)
1057 unsigned char hash[DIGEST_LEN];
1058 unsigned char *secret_tmp = NULL;
1059 BIGNUM *pubkey_bn = NULL;
1060 int secret_len;
1061 int i;
1062 tor_assert(dh);
1063 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
1065 if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
1066 goto error;
1067 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
1068 secret_len = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
1069 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1070 for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
1071 secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
1072 if (crypto_digest(secret_tmp, secret_len+1, hash))
1073 goto error;
1074 memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
1076 secret_len = secret_bytes_out;
1078 goto done;
1079 error:
1080 secret_len = -1;
1081 done:
1082 crypto_log_errors(LOG_WARN, "completing DH handshake");
1083 if (pubkey_bn)
1084 BN_free(pubkey_bn);
1085 tor_free(secret_tmp);
1086 return secret_len;
1088 void crypto_dh_free(crypto_dh_env_t *dh)
1090 tor_assert(dh && dh->dh);
1091 DH_free(dh->dh);
1092 free(dh);
1095 /* random numbers */
1096 #ifdef MS_WINDOWS
1097 int crypto_seed_rng()
1099 static int provider_set = 0;
1100 static HCRYPTPROV provider;
1101 char buf[DIGEST_LEN+1];
1103 if (!provider_set) {
1104 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, 0)) {
1105 if (GetLastError() != NTE_BAD_KEYSET) {
1106 log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
1107 return -1;
1109 /* Yes, we need to try it twice. */
1110 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1111 CRYPT_NEWKEYSET)) {
1112 log_fn(LOG_ERR,"Can't get CryptoAPI provider [2]");
1113 return -1;
1116 provider_set = 1;
1118 if (!CryptGenRandom(provider, DIGEST_LEN, buf)) {
1119 log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
1120 return -1;
1122 RAND_seed(buf, DIGEST_LEN);
1123 /* And add the current screen state to the entopy pool for
1124 * good measure. */
1125 RAND_screen();
1126 return 0;
1128 #else
1129 int crypto_seed_rng()
1131 static char *filenames[] = {
1132 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1134 int fd;
1135 int i, n;
1136 char buf[DIGEST_LEN+1];
1138 for (i = 0; filenames[i]; ++i) {
1139 fd = open(filenames[i], O_RDONLY, 0);
1140 if (fd<0) continue;
1141 log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
1142 n = read(fd, buf, DIGEST_LEN);
1143 close(fd);
1144 if (n != DIGEST_LEN) {
1145 log_fn(LOG_WARN, "Error reading from entropy source");
1146 return -1;
1148 RAND_seed(buf, DIGEST_LEN);
1149 return 0;
1152 log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
1153 return -1;
1155 #endif
1157 int crypto_rand(unsigned int n, unsigned char *to)
1159 int r;
1160 tor_assert(to);
1161 r = RAND_bytes(to, n);
1162 if (r == 0)
1163 crypto_log_errors(LOG_WARN, "generating random data");
1164 return (r != 1);
1167 void crypto_pseudo_rand(unsigned int n, unsigned char *to)
1169 tor_assert(to);
1170 if (RAND_pseudo_bytes(to, n) == -1) {
1171 log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
1172 crypto_log_errors(LOG_WARN, "generating random data");
1173 exit(1);
1177 /* return a pseudo random number between 0 and max-1 */
1178 int crypto_pseudo_rand_int(unsigned int max) {
1179 unsigned int val;
1180 unsigned int cutoff;
1181 tor_assert(max < UINT_MAX);
1182 tor_assert(max > 0); /* don't div by 0 */
1184 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1185 * distribution with clipping at the upper end of unsigned int's
1186 * range.
1188 cutoff = UINT_MAX - (UINT_MAX%max);
1189 while(1) {
1190 crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
1191 if (val < cutoff)
1192 return val % max;
1197 base64_encode(char *dest, int destlen, const char *src, int srclen)
1199 EVP_ENCODE_CTX ctx;
1200 int len, ret;
1202 /* 48 bytes of input -> 64 bytes of output plus newline.
1203 Plus one more byte, in case I'm wrong.
1205 if (destlen < ((srclen/48)+1)*66)
1206 return -1;
1208 EVP_EncodeInit(&ctx);
1209 EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1210 EVP_EncodeFinal(&ctx, dest+len, &ret);
1211 ret += len;
1212 return ret;
1215 base64_decode(char *dest, int destlen, const char *src, int srclen)
1217 EVP_ENCODE_CTX ctx;
1218 int len, ret;
1219 /* 64 bytes of input -> *up to* 48 bytes of output.
1220 Plus one more byte, in caes I'm wrong.
1222 if (destlen < ((srclen/64)+1)*49)
1223 return -1;
1225 EVP_DecodeInit(&ctx);
1226 EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1227 EVP_DecodeFinal(&ctx, dest, &ret);
1228 ret += len;
1229 return ret;
1232 /* Implement base32 encoding as in rfc3548. Limitation: Requires that
1233 * srclen is a multiple of 5.
1236 base32_encode(char *dest, int destlen, const char *src, int srclen)
1238 int nbits, i, bit, v, u;
1239 nbits = srclen * 8;
1241 if ((nbits%5) != 0)
1242 /* We need an even multiple of 5 bits. */
1243 return -1;
1244 if ((nbits/5)+1 > destlen)
1245 /* Not enough space. */
1246 return -1;
1248 for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
1249 /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
1250 v = ((uint8_t)src[bit/8]) << 8;
1251 if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
1252 /* set u to the 5-bit value at the bit'th bit of src. */
1253 u = (v >> (11-(bit%8))) & 0x1F;
1254 dest[i] = BASE32_CHARS[u];
1256 dest[i] = '\0';
1257 return 0;
1261 Local Variables:
1262 mode:c
1263 indent-tabs-mode:nil
1264 c-basic-offset:2
1265 End: