Make OP work on windows! (Also misc logging tweaks)
[tor.git] / src / common / crypto.c
blobd5a5a9c1e288f792ebdaf47efd0a702e040f3452
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "../or/or.h"
7 #include <string.h>
9 #include <openssl/err.h>
10 #include <openssl/rsa.h>
11 #include <openssl/pem.h>
12 #include <openssl/evp.h>
13 #include <openssl/rand.h>
14 #include <openssl/opensslv.h>
15 #include <openssl/bn.h>
16 #include <openssl/dh.h>
18 #include <stdlib.h>
19 #include <assert.h>
20 #include <stdio.h>
21 #include <limits.h>
23 #include "crypto.h"
24 #include "log.h"
25 #include "aes.h"
27 #ifdef MS_WINDOWS
28 #include <wincrypt.h>
29 #endif
31 #if OPENSSL_VERSION_NUMBER < 0x00905000l
32 #error "We require openssl >= 0.9.5"
33 #elif OPENSSL_VERSION_NUMBER < 0x00906000l
34 #define OPENSSL_095
35 #endif
38 * Certain functions that return a success code in OpenSSL 0.9.6 return void
39 * (and don't indicate errors) in OpenSSL version 0.9.5.
41 * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
43 #ifdef OPENSSL_095
44 #define RETURN_SSL_OUTCOME(exp) (exp); return 0
45 #else
46 #define RETURN_SSL_OUTCOME(exp) return !(exp)
47 #endif
49 struct crypto_pk_env_t
51 int type;
52 int refs; /* reference counting; so we don't have to copy keys */
53 unsigned char *key;
54 /* auxiliary data structure(s) used by the underlying crypto library */
55 unsigned char *aux;
58 struct crypto_cipher_env_t
60 int type;
61 unsigned char *key;
62 unsigned char *iv;
63 /* auxiliary data structure(s) used by the underlying crypto library */
64 unsigned char *aux;
67 /* static INLINE const EVP_CIPHER *
68 crypto_cipher_evp_cipher(int type, int enc);
71 static INLINE int
72 crypto_cipher_iv_length(int type) {
74 printf("%d -> %d IV\n",type,
75 EVP_CIPHER_iv_length(crypto_cipher_evp_cipher(type,0)));
77 switch(type)
79 case CRYPTO_CIPHER_IDENTITY: return 0;
80 case CRYPTO_CIPHER_DES: return 8;
81 case CRYPTO_CIPHER_RC4: return 16;
82 case CRYPTO_CIPHER_3DES: return 8;
83 case CRYPTO_CIPHER_AES_CTR: return 0;
84 default: assert(0); return -1;
88 static INLINE int
89 crypto_cipher_key_length(int type) {
91 printf("%d -> %d\n",type,
92 EVP_CIPHER_key_length(crypto_cipher_evp_cipher(type,0)));
94 switch(type)
96 case CRYPTO_CIPHER_IDENTITY: return 0;
97 case CRYPTO_CIPHER_DES: return 8;
98 case CRYPTO_CIPHER_RC4: return 16;
99 case CRYPTO_CIPHER_3DES: return 16;
100 case CRYPTO_CIPHER_AES_CTR: return 16;
101 default: assert(0); return -1;
105 static INLINE const EVP_CIPHER *
106 crypto_cipher_evp_cipher(int type, int enc) {
107 switch(type)
109 case CRYPTO_CIPHER_IDENTITY: return EVP_enc_null();
110 case CRYPTO_CIPHER_DES: return EVP_des_ofb();
111 case CRYPTO_CIPHER_RC4: return EVP_rc4();
112 case CRYPTO_CIPHER_3DES: return EVP_des_ede_ofb();
113 default: return NULL;
117 static int _crypto_global_initialized = 0;
119 int crypto_global_init()
121 if (!_crypto_global_initialized) {
122 ERR_load_crypto_strings();
123 _crypto_global_initialized = 1;
125 return 0;
128 int crypto_global_cleanup()
130 ERR_free_strings();
131 return 0;
134 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
136 crypto_pk_env_t *env;
137 assert(rsa);
138 env = (crypto_pk_env_t *)tor_malloc(sizeof(crypto_pk_env_t));
139 env->type = CRYPTO_PK_RSA;
140 env->refs = 1;
141 env->key = (unsigned char*)rsa;
142 env->aux = NULL;
143 return env;
146 RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
148 if (env->type != CRYPTO_PK_RSA)
149 return NULL;
150 return (RSA*)env->key;
153 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env)
155 RSA *key = NULL;
156 EVP_PKEY *pkey = NULL;
157 if (env->type != CRYPTO_PK_RSA)
158 return NULL;
159 assert(env->key);
160 if (!(key = RSAPrivateKey_dup((RSA*)env->key)))
161 goto error;
162 if (!(pkey = EVP_PKEY_new()))
163 goto error;
164 if (!(EVP_PKEY_assign_RSA(pkey, key)))
165 goto error;
166 return pkey;
167 error:
168 if (pkey)
169 EVP_PKEY_free(pkey);
170 if (key)
171 RSA_free(key);
172 return NULL;
175 crypto_pk_env_t *crypto_new_pk_env(int type)
177 RSA *rsa;
179 switch(type) {
180 case CRYPTO_PK_RSA:
181 rsa = RSA_new();
182 if (!rsa) return NULL;
183 return _crypto_new_pk_env_rsa(rsa);
184 default:
185 return NULL;
189 void crypto_free_pk_env(crypto_pk_env_t *env)
191 assert(env);
193 if(--env->refs > 0)
194 return;
196 switch(env->type) {
197 case CRYPTO_PK_RSA:
198 if (env->key)
199 RSA_free((RSA *)env->key);
200 break;
201 default:
202 break;
205 free(env);
209 /* Create a new crypto_cipher_env_t for a given onion cipher type, key,
210 * iv, and encryption flag (1=encrypt, 0=decrypt). Return the crypto object
211 * on success; NULL on failure.
213 crypto_cipher_env_t *
214 crypto_create_init_cipher(int cipher_type, char *key, char *iv, int encrypt_mode)
216 int r;
217 crypto_cipher_env_t *crypto = NULL;
219 if (! (crypto = crypto_new_cipher_env(cipher_type))) {
220 log_fn(LOG_WARN, "Unable to allocate crypto object");
221 return NULL;
224 if (crypto_cipher_set_key(crypto, key)) {
225 log_fn(LOG_WARN, "Unable to set key: %s", crypto_perror());
226 goto error;
229 if (crypto_cipher_set_iv(crypto, iv)) {
230 log_fn(LOG_WARN, "Unable to set iv: %s", crypto_perror());
231 goto error;
234 if (encrypt_mode)
235 r = crypto_cipher_encrypt_init_cipher(crypto);
236 else
237 r = crypto_cipher_decrypt_init_cipher(crypto);
239 if (r) {
240 log_fn(LOG_WARN, "Unable to initialize cipher: %s", crypto_perror());
241 goto error;
243 return crypto;
245 error:
246 if (crypto)
247 crypto_free_cipher_env(crypto);
248 return NULL;
251 crypto_cipher_env_t *crypto_new_cipher_env(int type)
253 crypto_cipher_env_t *env;
254 int iv_len, key_len;
256 env = (crypto_cipher_env_t *)tor_malloc(sizeof(crypto_cipher_env_t));
258 env->type = type;
259 env->key = NULL;
260 env->iv = NULL;
261 env->aux = NULL;
263 iv_len = crypto_cipher_iv_length(type);
264 key_len = crypto_cipher_key_length(type);
266 if (type == CRYPTO_CIPHER_AES_CTR) {
267 env->aux = (unsigned char *)aes_new_cipher();
268 } else if (! crypto_cipher_evp_cipher(type,0))
269 /* This is not an openssl cipher */
270 goto err;
271 else {
272 env->aux = (unsigned char *)tor_malloc(sizeof(EVP_CIPHER_CTX));
273 EVP_CIPHER_CTX_init((EVP_CIPHER_CTX *)env->aux);
276 if(iv_len)
277 env->iv = (unsigned char *)tor_malloc(iv_len);
279 if(key_len)
280 env->key = (unsigned char *)tor_malloc(key_len);
282 return env;
283 err:
284 if (env->key)
285 free(env->key);
286 if (env->iv)
287 free(env->iv);
288 if (env->aux)
289 free(env->aux);
290 if (env)
291 free(env);
292 return NULL;
295 void crypto_free_cipher_env(crypto_cipher_env_t *env)
297 assert(env);
299 if (env->type == CRYPTO_CIPHER_AES_CTR) {
300 assert(env->aux);
301 aes_free_cipher((aes_cnt_cipher_t*)env->aux);
302 env->aux = NULL;
303 } else if (crypto_cipher_evp_cipher(env->type,0)) {
304 /* This is an openssl cipher */
305 assert(env->aux);
306 EVP_CIPHER_CTX_cleanup((EVP_CIPHER_CTX *)env->aux);
309 if (env->aux)
310 free((void *)env->aux);
311 if (env->iv)
312 free((void *)env->iv);
313 if (env->key)
314 free((void *)env->key);
316 free((void *)env);
319 /* public key crypto */
320 int crypto_pk_generate_key(crypto_pk_env_t *env)
322 assert(env);
324 switch(env->type) {
325 case CRYPTO_PK_RSA:
326 if (env->key)
327 RSA_free((RSA *)env->key);
328 env->key = (unsigned char *)RSA_generate_key(1024,65537, NULL, NULL);
329 if (!env->key)
330 return -1;
331 break;
332 default:
333 return -1;
336 return 0;
339 int crypto_pk_read_private_key_from_file(crypto_pk_env_t *env, FILE *src)
341 assert(env && src);
343 switch(env->type) {
344 case CRYPTO_PK_RSA:
345 if (env->key)
346 RSA_free((RSA *)env->key);
347 env->key = (unsigned char *)PEM_read_RSAPrivateKey(src, NULL, NULL, NULL);
348 if (!env->key)
349 return -1;
350 break;
351 default :
352 return -1;
355 return 0;
358 int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
360 FILE *f_pr;
362 assert(env && keyfile);
364 if(strspn(keyfile,CONFIG_LEGAL_FILENAME_CHARACTERS) != strlen(keyfile)) {
365 /* filename contains nonlegal characters */
366 return -1;
369 /* open the keyfile */
370 f_pr=fopen(keyfile,"rb");
371 if (!f_pr)
372 return -1;
374 /* read the private key */
375 if(crypto_pk_read_private_key_from_file(env, f_pr) < 0) {
376 log_fn(LOG_WARN,"Error reading private key : %s",crypto_perror());
377 fclose(f_pr);
378 return -1;
380 fclose(f_pr);
382 /* check the private key */
383 switch(crypto_pk_check_key(env)) {
384 case 0:
385 log_fn(LOG_WARN,"Private key read but is invalid : %s.", crypto_perror());
386 return -1;
387 case -1:
388 log_fn(LOG_WARN,"Private key read but validity checking failed : %s",crypto_perror());
389 return -1;
390 /* case 1: fall through */
392 return 0;
395 int crypto_pk_read_public_key_from_file(crypto_pk_env_t *env, FILE *src)
397 assert(env && src);
399 switch(env->type) {
400 case CRYPTO_PK_RSA:
401 if(env->key)
402 RSA_free((RSA *)env->key);
403 env->key = (unsigned char *)PEM_read_RSAPublicKey(src, NULL, NULL, NULL);
404 if (!env->key)
405 return -1;
406 break;
407 default :
408 return -1;
411 return 0;
414 int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, int *len) {
415 BUF_MEM *buf;
416 BIO *b;
418 assert(env && env->key && dest);
420 switch(env->type) {
421 case CRYPTO_PK_RSA:
423 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
425 /* Now you can treat b as if it were a file. Just use the
426 * PEM_*_bio_* functions instead of the non-bio variants.
428 if(!PEM_write_bio_RSAPublicKey(b, (RSA *)env->key))
429 return -1;
431 BIO_get_mem_ptr(b, &buf);
432 BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
433 BIO_free(b);
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 break;
442 default:
443 return -1;
446 return 0;
449 int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, int len) {
450 BIO *b;
452 assert(env && src);
454 switch(env->type) {
455 case CRYPTO_PK_RSA:
456 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
458 BIO_write(b, src, len);
460 RSA_free((RSA *)env->key);
461 env->key = (unsigned char *)PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
462 if(!env->key)
463 return -1;
465 BIO_free(b);
466 break;
467 default:
468 return -1;
471 return 0;
475 crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
476 const char *fname)
478 BIO *bio;
479 char *cp;
480 long len;
481 char *s;
482 int r;
483 assert(env->type == CRYPTO_PK_RSA);
484 if (!(bio = BIO_new(BIO_s_mem())))
485 return -1;
486 if (PEM_write_bio_RSAPrivateKey(bio, (RSA*)env->key, NULL,NULL,0,NULL,NULL)
487 == 0) {
488 BIO_free(bio);
489 return -1;
491 len = BIO_get_mem_data(bio, &cp);
492 s = tor_malloc(len+1);
493 strncpy(s, cp, len);
494 s[len] = '\0';
495 r = write_str_to_file(fname, s);
496 BIO_free(bio);
497 free(s);
498 return r;
501 int crypto_pk_write_private_key_to_file(crypto_pk_env_t *env, FILE *dest)
503 assert(env && dest);
505 switch(env->type) {
506 case CRYPTO_PK_RSA:
507 if (!env->key)
508 return -1;
509 if (PEM_write_RSAPrivateKey(dest, (RSA *)env->key, NULL, NULL, 0,0, NULL) == 0)
510 return -1;
511 break;
512 default :
513 return -1;
516 return 0;
518 int crypto_pk_write_public_key_to_file(crypto_pk_env_t *env, FILE *dest)
520 assert(env && dest);
522 switch(env->type) {
523 case CRYPTO_PK_RSA:
524 if (!env->key)
525 return -1;
526 if (PEM_write_RSAPublicKey(dest, (RSA *)env->key) == 0)
527 return -1;
528 break;
529 default :
530 return -1;
533 return 0;
536 int crypto_pk_check_key(crypto_pk_env_t *env)
538 assert(env);
540 switch(env->type) {
541 case CRYPTO_PK_RSA:
542 return RSA_check_key((RSA *)env->key);
543 default:
544 return -1;
548 int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
549 int result;
551 if (!a || !b)
552 return -1;
554 if (!a->key || !b->key)
555 return -1;
557 if (a->type != b->type)
558 return -1;
560 switch(a->type) {
561 case CRYPTO_PK_RSA:
562 assert(((RSA *)a->key)->n && ((RSA *)a->key)->e && ((RSA *)b->key)->n && ((RSA *)b->key)->e);
563 result = BN_cmp(((RSA *)a->key)->n, ((RSA *)b->key)->n);
564 if (result)
565 return result;
566 return BN_cmp(((RSA *)a->key)->e, ((RSA *)b->key)->e);
567 default:
568 return -1;
572 int crypto_pk_keysize(crypto_pk_env_t *env)
574 assert(env && env->key);
576 return RSA_size((RSA *)env->key);
579 crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
580 assert(env && env->key);
582 switch(env->type) {
583 case CRYPTO_PK_RSA:
584 env->refs++;
585 break;
586 default:
587 return NULL;
590 return env;
593 int crypto_pk_public_encrypt(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to, int padding)
595 assert(env && from && to);
597 switch(env->type) {
598 case CRYPTO_PK_RSA:
599 return RSA_public_encrypt(fromlen, from, to, (RSA *)env->key, padding);
600 default:
601 return -1;
605 int crypto_pk_private_decrypt(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to, int padding)
607 assert(env && from && to);
609 switch(env->type) {
610 case CRYPTO_PK_RSA:
611 if (!(((RSA*)env->key)->p))
612 return -1;
613 return RSA_private_decrypt(fromlen, from, to, (RSA *)env->key, padding);
614 default:
615 return -1;
619 int crypto_pk_public_checksig(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
621 assert(env && from && to);
623 switch(env->type) {
624 case CRYPTO_PK_RSA:
625 return RSA_public_decrypt(fromlen, from, to, (RSA *)env->key,
626 RSA_PKCS1_PADDING);
627 default:
628 return -1;
632 int crypto_pk_private_sign(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
634 assert(env && from && to);
636 switch(env->type) {
637 case CRYPTO_PK_RSA:
638 if (!(((RSA*)env->key)->p))
639 return -1;
640 return RSA_private_encrypt(fromlen, from, to, (RSA *)env->key,
641 RSA_PKCS1_PADDING);
642 default:
643 return -1;
647 /* Given a private or public key pk, put a fingerprint of the
648 * public key into fp_out.
651 crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out)
653 unsigned char *buf, *bufp;
654 unsigned char digest[20];
655 int len;
656 int i;
657 assert(pk->type == CRYPTO_PK_RSA);
658 len = i2d_RSAPublicKey((RSA*)pk->key, NULL);
659 if (len < 0)
660 return -1;
661 if (len<FINGERPRINT_LEN+1) len = FINGERPRINT_LEN+1;
662 buf = bufp = tor_malloc(len+1);
663 len = i2d_RSAPublicKey((RSA*)pk->key, &bufp);
664 if (len < 0) {
665 free(buf);
666 return -1;
668 if (crypto_SHA_digest(buf, len, digest) < 0) {
669 free(buf);
670 return -1;
672 bufp = buf;
673 for (i = 0; i < 20; ++i) {
674 sprintf(bufp,"%02X",digest[i]);
675 bufp += 2;
676 if (i%2 && i != 19) {
677 *bufp++ = ' ';
680 *bufp = '\0';
681 assert(strlen(buf) == FINGERPRINT_LEN);
682 assert(crypto_pk_check_fingerprint_syntax(buf));
683 strcpy(fp_out, buf);
684 free(buf);
685 return 0;
689 crypto_pk_check_fingerprint_syntax(const char *s)
691 int i;
692 for (i = 0; i < FINGERPRINT_LEN; ++i) {
693 if ((i%5) == 4) {
694 if (!isspace(s[i])) return 0;
695 } else {
696 if (!isxdigit(s[i])) return 0;
699 if (s[FINGERPRINT_LEN]) return 0;
700 return 1;
703 /* symmetric crypto */
704 int crypto_cipher_generate_key(crypto_cipher_env_t *env)
706 int key_len;
707 assert(env);
709 key_len = crypto_cipher_key_length(env->type);
711 if (key_len > 0)
712 return crypto_rand(key_len, env->key);
713 else if (key_len == 0)
714 return 0;
715 else
716 return -1;
719 int crypto_cipher_set_iv(crypto_cipher_env_t *env, unsigned char *iv)
721 int iv_len;
722 assert(env && iv);
724 iv_len = crypto_cipher_iv_length(env->type);
725 if (!iv_len)
726 return 0;
728 if (!env->iv)
729 return -1;
731 memcpy((void*)env->iv, (void*)iv, iv_len);
733 return 0;
736 int crypto_cipher_set_key(crypto_cipher_env_t *env, unsigned char *key)
738 int key_len;
739 assert(env && key);
741 key_len = crypto_cipher_key_length(env->type);
742 if (!key_len)
743 return 0;
745 if (!env->key)
746 return -1;
748 memcpy((void*)env->key, (void*)key, key_len);
750 return 0;
753 unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
755 return env->key;
758 int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
760 assert(env);
762 if (crypto_cipher_evp_cipher(env->type, 1)) {
763 RETURN_SSL_OUTCOME(EVP_EncryptInit((EVP_CIPHER_CTX *)env->aux,
764 crypto_cipher_evp_cipher(env->type, 1),
765 env->key, env->iv));
766 } else if (env->type == CRYPTO_CIPHER_AES_CTR) {
767 aes_set_key((aes_cnt_cipher_t*)env->aux, env->key, 128);
768 return 0;
769 } else {
770 return -1;
774 int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
776 assert(env);
778 if (crypto_cipher_evp_cipher(env->type, 0)) {
779 RETURN_SSL_OUTCOME(EVP_EncryptInit((EVP_CIPHER_CTX *)env->aux,
780 crypto_cipher_evp_cipher(env->type, 0),
781 env->key, env->iv));
782 } else if (env->type == CRYPTO_CIPHER_AES_CTR) {
783 aes_set_key((aes_cnt_cipher_t*)env->aux, env->key, 128);
784 return 0;
785 } else {
786 return -1;
790 int crypto_cipher_encrypt(crypto_cipher_env_t *env, unsigned char *from, unsigned int fromlen, unsigned char *to)
792 int tolen;
794 assert(env && from && to);
796 if (env->type == CRYPTO_CIPHER_AES_CTR) {
797 aes_crypt((aes_cnt_cipher_t*)env->aux, from, fromlen, to);
798 return 0;
799 } else {
800 RETURN_SSL_OUTCOME(EVP_EncryptUpdate((EVP_CIPHER_CTX *)env->aux, to, &tolen, from, fromlen));
804 int crypto_cipher_decrypt(crypto_cipher_env_t *env, unsigned char *from, unsigned int fromlen, unsigned char *to)
806 int tolen;
808 assert(env && from && to);
810 if (env->type == CRYPTO_CIPHER_AES_CTR) {
811 aes_crypt((aes_cnt_cipher_t*)env->aux, from, fromlen, to);
812 return 0;
813 } else {
814 RETURN_SSL_OUTCOME(EVP_DecryptUpdate((EVP_CIPHER_CTX *)env->aux, to, &tolen, from, fromlen));
819 crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
821 return crypto_cipher_advance(env, -delta);
825 crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
827 if (env->type == CRYPTO_CIPHER_AES_CTR) {
828 aes_adjust_counter((aes_cnt_cipher_t*)env->aux, delta);
829 return 0;
830 } else {
831 return -1;
835 /* SHA-1 */
836 int crypto_SHA_digest(const unsigned char *m, int len, unsigned char *digest)
838 assert(m && digest);
839 return (SHA1(m,len,digest) == NULL);
842 struct crypto_digest_env_t {
843 SHA_CTX d;
846 crypto_digest_env_t *
847 crypto_new_digest_env(int type)
849 crypto_digest_env_t *r;
850 assert(type == CRYPTO_SHA1_DIGEST);
851 r = tor_malloc(sizeof(crypto_digest_env_t));
852 SHA1_Init(&r->d);
853 return r;
856 void
857 crypto_free_digest_env(crypto_digest_env_t *digest) {
858 if(digest)
859 free(digest);
862 void
863 crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
864 size_t len)
866 assert(digest);
867 assert(data);
868 SHA1_Update(&digest->d, (void*)data, len);
871 void crypto_digest_get_digest(crypto_digest_env_t *digest,
872 char *out, size_t out_len)
874 static char r[SHA_DIGEST_LENGTH];
875 assert(digest && out);
876 assert(out_len <= SHA_DIGEST_LENGTH);
877 SHA1_Final(r, &digest->d);
878 memcpy(out, r, out_len);
881 crypto_digest_env_t *
882 crypto_digest_dup(const crypto_digest_env_t *digest)
884 crypto_digest_env_t *r;
885 assert(digest);
886 r = tor_malloc(sizeof(crypto_digest_env_t));
887 memcpy(r,digest,sizeof(crypto_digest_env_t));
888 return r;
891 void
892 crypto_digest_assign(crypto_digest_env_t *into,
893 const crypto_digest_env_t *from)
895 assert(into && from);
896 memcpy(into,from,sizeof(crypto_digest_env_t));
899 /* DH */
900 static BIGNUM *dh_param_p = NULL;
901 static BIGNUM *dh_param_g = NULL;
903 static void init_dh_param() {
904 BIGNUM *p, *g;
905 int r;
906 if (dh_param_p && dh_param_g)
907 return;
909 p = BN_new();
910 g = BN_new();
911 assert(p && g);
913 #if 0
914 /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
915 prime, and supposedly it equals:
916 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
918 r = BN_hex2bn(&p,
919 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
920 "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
921 "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
922 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
923 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
924 "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
925 "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
926 "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
927 #endif
929 /* This is from rfc2409, section 6.2. It's a safe prime, and
930 supposedly it equals:
931 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
933 /* See also rfc 3536 */
934 r = BN_hex2bn(&p,
935 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
936 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
937 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
938 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
939 "49286651ECE65381FFFFFFFFFFFFFFFF");
940 assert(r);
942 r = BN_set_word(g, 2);
943 assert(r);
944 dh_param_p = p;
945 dh_param_g = g;
948 crypto_dh_env_t *crypto_dh_new()
950 crypto_dh_env_t *res = NULL;
952 if (!dh_param_p)
953 init_dh_param();
955 res = tor_malloc(sizeof(crypto_dh_env_t));
956 res->dh = NULL;
958 if (!(res->dh = DH_new()))
959 goto err;
961 if (!(res->dh->p = BN_dup(dh_param_p)))
962 goto err;
964 if (!(res->dh->g = BN_dup(dh_param_g)))
965 goto err;
967 return res;
968 err:
969 if (res && res->dh) DH_free(res->dh); /* frees p and g too */
970 if (res) free(res);
971 return NULL;
973 int crypto_dh_get_bytes(crypto_dh_env_t *dh)
975 assert(dh);
976 return DH_size(dh->dh);
978 int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, int pubkey_len)
980 int bytes;
981 assert(dh);
982 if (!DH_generate_key(dh->dh))
983 return -1;
985 assert(dh->dh->pub_key);
986 bytes = BN_num_bytes(dh->dh->pub_key);
987 if (pubkey_len < bytes)
988 return -1;
990 memset(pubkey, 0, pubkey_len);
991 BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
993 return 0;
996 #undef MIN
997 #define MIN(a,b) ((a)<(b)?(a):(b))
998 int crypto_dh_compute_secret(crypto_dh_env_t *dh,
999 char *pubkey, int pubkey_len,
1000 char *secret_out, int secret_bytes_out)
1002 unsigned char hash[20];
1003 unsigned char *secret_tmp = NULL;
1004 BIGNUM *pubkey_bn = NULL;
1005 int secret_len;
1006 int i;
1007 assert(dh);
1008 assert(secret_bytes_out/20 <= 255);
1010 if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
1011 goto error;
1012 secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
1013 secret_len = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
1014 /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
1015 for (i = 0; i < secret_bytes_out; i += 20) {
1016 secret_tmp[secret_len] = (unsigned char) i/20;
1017 if (crypto_SHA_digest(secret_tmp, secret_len+1, hash))
1018 goto error;
1019 memcpy(secret_out+i, hash, MIN(20, secret_bytes_out-i));
1021 secret_len = secret_bytes_out;
1023 goto done;
1024 error:
1025 secret_len = -1;
1026 done:
1027 if (pubkey_bn)
1028 BN_free(pubkey_bn);
1029 tor_free(secret_tmp);
1030 return secret_len;
1032 void crypto_dh_free(crypto_dh_env_t *dh)
1034 assert(dh && dh->dh);
1035 DH_free(dh->dh);
1036 free(dh);
1039 /* random numbers */
1040 #ifdef MS_WINDOWS
1041 int crypto_seed_rng()
1043 static int provider_set = 0;
1044 static HCRYPTPROV provider;
1045 char buf[21];
1047 if (!provider_set) {
1048 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, 0)) {
1049 if (GetLastError() != NTE_BAD_KEYSET) {
1050 log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
1051 return -1;
1053 /* Yes, we need to try it twice. */
1054 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
1055 CRYPT_NEWKEYSET)) {
1056 log_fn(LOG_ERR,"Can't get CryptoAPI provider [2]");
1057 return -1;
1060 provider_set = 1;
1062 if (!CryptGenRandom(provider, 20, buf)) {
1063 log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
1064 return -1;
1066 RAND_seed(buf, 20);
1067 /* And add the current screen state to the entopy pool for
1068 * good measure. */
1069 RAND_screen();
1070 return 0;
1072 #else
1073 int crypto_seed_rng()
1075 static char *filenames[] = {
1076 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
1078 int i, n;
1079 char buf[21];
1080 FILE *f;
1082 for (i = 0; filenames[i]; ++i) {
1083 f = fopen(filenames[i], "rb");
1084 if (!f) continue;
1085 log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
1086 n = fread(buf, 1, 20, f);
1087 fclose(f);
1088 if (n != 20) {
1089 log_fn(LOG_WARN, "Error reading from entropy source");
1090 return -1;
1092 RAND_seed(buf, 20);
1093 return 0;
1096 log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
1097 return -1;
1099 #endif
1101 int crypto_rand(unsigned int n, unsigned char *to)
1103 assert(to);
1104 return (RAND_bytes(to, n) != 1);
1107 void crypto_pseudo_rand(unsigned int n, unsigned char *to)
1109 assert(to);
1110 if (RAND_pseudo_bytes(to, n) == -1) {
1111 log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
1112 exit(1);
1116 /* return a pseudo random number between 0 and max-1 */
1117 int crypto_pseudo_rand_int(unsigned int max) {
1118 unsigned int val;
1119 unsigned int cutoff;
1120 assert(max < UINT_MAX);
1121 assert(max > 0); /* don't div by 0 */
1123 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
1124 * distribution with clipping at the upper end of unsigned int's
1125 * range.
1127 cutoff = UINT_MAX - (UINT_MAX%max);
1128 while(1) {
1129 crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
1130 if (val < cutoff)
1131 return val % max;
1135 /* errors */
1136 char *crypto_perror()
1138 return (char *)ERR_reason_error_string(ERR_get_error());
1142 base64_encode(char *dest, int destlen, const char *src, int srclen)
1144 EVP_ENCODE_CTX ctx;
1145 int len, ret;
1147 /* 48 bytes of input -> 64 bytes of output plus newline.
1148 Plus one more byte, in case I'm wrong.
1150 if (destlen < ((srclen/48)+1)*66)
1151 return -1;
1153 EVP_EncodeInit(&ctx);
1154 EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1155 EVP_EncodeFinal(&ctx, dest+len, &ret);
1156 ret += len;
1157 return ret;
1160 base64_decode(char *dest, int destlen, const char *src, int srclen)
1162 EVP_ENCODE_CTX ctx;
1163 int len, ret;
1164 /* 64 bytes of input -> *up to* 48 bytes of output.
1165 Plus one more byte, in caes I'm wrong.
1167 if (destlen < ((srclen/64)+1)*49)
1168 return -1;
1170 EVP_DecodeInit(&ctx);
1171 EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
1172 EVP_DecodeFinal(&ctx, dest, &ret);
1173 ret += len;
1174 return ret;