Back to index

tor  0.2.3.18-rc
crypto.c
Go to the documentation of this file.
00001 /* Copyright (c) 2001, Matej Pfajfar.
00002  * Copyright (c) 2001-2004, Roger Dingledine.
00003  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00004  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00005 /* See LICENSE for licensing information */
00006 
00013 #include "orconfig.h"
00014 
00015 #ifdef _WIN32
00016 #ifndef _WIN32_WINNT
00017 #define _WIN32_WINNT 0x0501
00018 #endif
00019 #define WIN32_LEAN_AND_MEAN
00020 #include <windows.h>
00021 #include <wincrypt.h>
00022 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
00023  * use either definition. */
00024 #undef OCSP_RESPONSE
00025 #endif
00026 
00027 #include <openssl/err.h>
00028 #include <openssl/rsa.h>
00029 #include <openssl/pem.h>
00030 #include <openssl/evp.h>
00031 #include <openssl/engine.h>
00032 #include <openssl/rand.h>
00033 #include <openssl/opensslv.h>
00034 #include <openssl/bn.h>
00035 #include <openssl/dh.h>
00036 #include <openssl/conf.h>
00037 #include <openssl/hmac.h>
00038 
00039 #ifdef HAVE_CTYPE_H
00040 #include <ctype.h>
00041 #endif
00042 #ifdef HAVE_UNISTD_H
00043 #include <unistd.h>
00044 #endif
00045 #ifdef HAVE_FCNTL_H
00046 #include <fcntl.h>
00047 #endif
00048 #ifdef HAVE_SYS_FCNTL_H
00049 #include <sys/fcntl.h>
00050 #endif
00051 
00052 #define CRYPTO_PRIVATE
00053 #include "crypto.h"
00054 #include "../common/torlog.h"
00055 #include "aes.h"
00056 #include "../common/util.h"
00057 #include "container.h"
00058 #include "compat.h"
00059 
00060 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,7)
00061 #error "We require OpenSSL >= 0.9.7"
00062 #endif
00063 
00064 #ifdef ANDROID
00065 /* Android's OpenSSL seems to have removed all of its Engine support. */
00066 #define DISABLE_ENGINES
00067 #endif
00068 
00070 #define MAX_DNS_LABEL_SIZE 63
00071 
00072 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8) && \
00073   !defined(RUNNING_DOXYGEN)
00074 
00078 #define SHA256_CTX sha256_state
00079 #define SHA256_Init sha256_init
00080 #define SHA256_Update sha256_process
00081 #define LTC_ARGCHK(x) tor_assert(x)
00082 
00083 #include "sha256.c"
00084 #define SHA256_Final(a,b) sha256_done(b,a)
00085 
00086 static unsigned char *
00087 SHA256(const unsigned char *m, size_t len, unsigned char *d)
00088 {
00089   SHA256_CTX ctx;
00090   SHA256_Init(&ctx);
00091   SHA256_Update(&ctx, m, len);
00092   SHA256_Final(d, &ctx);
00093   return d;
00094 }
00095 #endif
00096 
00098 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
00099 
00100 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
00101 
00102 #ifdef TOR_IS_MULTITHREADED
00103 
00104 static tor_mutex_t **_openssl_mutexes = NULL;
00106 static int _n_openssl_mutexes = 0;
00107 #endif
00108 
00110 struct crypto_pk_t
00111 {
00112   int refs; 
00113   RSA *key; 
00114 };
00115 
00117 struct crypto_cipher_t
00118 {
00119   char key[CIPHER_KEY_LEN]; 
00120   char iv[CIPHER_IV_LEN]; 
00121   aes_cnt_cipher_t *cipher; 
00123 };
00124 
00127 struct crypto_dh_t {
00128   DH *dh; 
00129 };
00130 
00131 static int setup_openssl_threading(void);
00132 static int tor_check_dh_key(int severity, BIGNUM *bn);
00133 
00136 static INLINE int
00137 crypto_get_rsa_padding_overhead(int padding)
00138 {
00139   switch (padding)
00140     {
00141     case RSA_PKCS1_OAEP_PADDING: return 42;
00142     case RSA_PKCS1_PADDING: return 11;
00143     default: tor_assert(0); return -1;
00144     }
00145 }
00146 
00149 static INLINE int
00150 crypto_get_rsa_padding(int padding)
00151 {
00152   switch (padding)
00153     {
00154     case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
00155     case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
00156     default: tor_assert(0); return -1;
00157     }
00158 }
00159 
00161 static int _crypto_global_initialized = 0;
00162 
00166 static void
00167 crypto_log_errors(int severity, const char *doing)
00168 {
00169   unsigned long err;
00170   const char *msg, *lib, *func;
00171   while ((err = ERR_get_error()) != 0) {
00172     msg = (const char*)ERR_reason_error_string(err);
00173     lib = (const char*)ERR_lib_error_string(err);
00174     func = (const char*)ERR_func_error_string(err);
00175     if (!msg) msg = "(null)";
00176     if (!lib) lib = "(null)";
00177     if (!func) func = "(null)";
00178     if (doing) {
00179       log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
00180           doing, msg, lib, func);
00181     } else {
00182       log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
00183     }
00184   }
00185 }
00186 
00187 #ifndef DISABLE_ENGINES
00188 
00189 static void
00190 log_engine(const char *fn, ENGINE *e)
00191 {
00192   if (e) {
00193     const char *name, *id;
00194     name = ENGINE_get_name(e);
00195     id = ENGINE_get_id(e);
00196     log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
00197         name?name:"?", id?id:"?", fn);
00198   } else {
00199     log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
00200   }
00201 }
00202 #endif
00203 
00204 #ifndef DISABLE_ENGINES
00205 
00207 static ENGINE *
00208 try_load_engine(const char *path, const char *engine)
00209 {
00210   ENGINE *e = ENGINE_by_id("dynamic");
00211   if (e) {
00212     if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
00213         !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
00214         !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
00215         !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
00216       ENGINE_free(e);
00217       e = NULL;
00218     }
00219   }
00220   return e;
00221 }
00222 #endif
00223 
00226 int
00227 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
00228 {
00229   if (!_crypto_global_initialized) {
00230     ERR_load_crypto_strings();
00231     OpenSSL_add_all_algorithms();
00232     _crypto_global_initialized = 1;
00233     setup_openssl_threading();
00234     if (useAccel > 0) {
00235 #ifdef DISABLE_ENGINES
00236       (void)accelName;
00237       (void)accelDir;
00238       log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
00239 #else
00240       ENGINE *e = NULL;
00241 
00242       log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
00243       ENGINE_load_builtin_engines();
00244       ENGINE_register_all_complete();
00245 
00246       if (accelName) {
00247         if (accelDir) {
00248           log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
00249                    " via path \"%s\".", accelName, accelDir);
00250           e = try_load_engine(accelName, accelDir);
00251         } else {
00252           log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
00253                    " acceleration support.", accelName);
00254           e = ENGINE_by_id(accelName);
00255         }
00256         if (!e) {
00257           log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
00258                    accelName);
00259         } else {
00260           log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
00261                    accelName);
00262         }
00263       }
00264       if (e) {
00265         log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
00266                  " setting default ciphers.");
00267         ENGINE_set_default(e, ENGINE_METHOD_ALL);
00268       }
00269       log_engine("RSA", ENGINE_get_default_RSA());
00270       log_engine("DH", ENGINE_get_default_DH());
00271       log_engine("RAND", ENGINE_get_default_RAND());
00272       log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
00273       log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
00274       log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
00275 #endif
00276     } else {
00277       log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
00278     }
00279 
00280     evaluate_evp_for_aes(-1);
00281     evaluate_ctr_for_aes();
00282 
00283     return crypto_seed_rng(1);
00284   }
00285   return 0;
00286 }
00287 
00289 void
00290 crypto_thread_cleanup(void)
00291 {
00292   ERR_remove_state(0);
00293 }
00294 
00296 crypto_pk_t *
00297 _crypto_new_pk_from_rsa(RSA *rsa)
00298 {
00299   crypto_pk_t *env;
00300   tor_assert(rsa);
00301   env = tor_malloc(sizeof(crypto_pk_t));
00302   env->refs = 1;
00303   env->key = rsa;
00304   return env;
00305 }
00306 
00309 RSA *
00310 _crypto_pk_get_rsa(crypto_pk_t *env)
00311 {
00312   return env->key;
00313 }
00314 
00317 EVP_PKEY *
00318 _crypto_pk_get_evp_pkey(crypto_pk_t *env, int private)
00319 {
00320   RSA *key = NULL;
00321   EVP_PKEY *pkey = NULL;
00322   tor_assert(env->key);
00323   if (private) {
00324     if (!(key = RSAPrivateKey_dup(env->key)))
00325       goto error;
00326   } else {
00327     if (!(key = RSAPublicKey_dup(env->key)))
00328       goto error;
00329   }
00330   if (!(pkey = EVP_PKEY_new()))
00331     goto error;
00332   if (!(EVP_PKEY_assign_RSA(pkey, key)))
00333     goto error;
00334   return pkey;
00335  error:
00336   if (pkey)
00337     EVP_PKEY_free(pkey);
00338   if (key)
00339     RSA_free(key);
00340   return NULL;
00341 }
00342 
00345 DH *
00346 _crypto_dh_get_dh(crypto_dh_t *dh)
00347 {
00348   return dh->dh;
00349 }
00350 
00354 crypto_pk_t *
00355 crypto_pk_new(void)
00356 {
00357   RSA *rsa;
00358 
00359   rsa = RSA_new();
00360   tor_assert(rsa);
00361   return _crypto_new_pk_from_rsa(rsa);
00362 }
00363 
00367 void
00368 crypto_pk_free(crypto_pk_t *env)
00369 {
00370   if (!env)
00371     return;
00372 
00373   if (--env->refs > 0)
00374     return;
00375   tor_assert(env->refs == 0);
00376 
00377   if (env->key)
00378     RSA_free(env->key);
00379 
00380   tor_free(env);
00381 }
00382 
00387 crypto_cipher_t *
00388 crypto_cipher_new_with_iv(const char *key, const char *iv)
00389 {
00390   crypto_cipher_t *env;
00391 
00392   env = tor_malloc_zero(sizeof(crypto_cipher_t));
00393 
00394   if (key == NULL)
00395     crypto_rand(env->key, CIPHER_KEY_LEN);
00396   else
00397     memcpy(env->key, key, CIPHER_KEY_LEN);
00398   if (iv == NULL)
00399     crypto_rand(env->iv, CIPHER_IV_LEN);
00400   else
00401     memcpy(env->iv, iv, CIPHER_IV_LEN);
00402 
00403   env->cipher = aes_new_cipher(env->key, env->iv);
00404 
00405   return env;
00406 }
00407 
00410 crypto_cipher_t *
00411 crypto_cipher_new(const char *key)
00412 {
00413   char zeroiv[CIPHER_IV_LEN];
00414   memset(zeroiv, 0, sizeof(zeroiv));
00415   return crypto_cipher_new_with_iv(key, zeroiv);
00416 }
00417 
00420 void
00421 crypto_cipher_free(crypto_cipher_t *env)
00422 {
00423   if (!env)
00424     return;
00425 
00426   tor_assert(env->cipher);
00427   aes_cipher_free(env->cipher);
00428   memset(env, 0, sizeof(crypto_cipher_t));
00429   tor_free(env);
00430 }
00431 
00432 /* public key crypto */
00433 
00437 int
00438 crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
00439 {
00440   tor_assert(env);
00441 
00442   if (env->key)
00443     RSA_free(env->key);
00444 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
00445   /* In OpenSSL 0.9.7, RSA_generate_key is all we have. */
00446   env->key = RSA_generate_key(bits, 65537, NULL, NULL);
00447 #else
00448   /* In OpenSSL 0.9.8, RSA_generate_key is deprecated. */
00449   {
00450     BIGNUM *e = BN_new();
00451     RSA *r = NULL;
00452     if (!e)
00453       goto done;
00454     if (! BN_set_word(e, 65537))
00455       goto done;
00456     r = RSA_new();
00457     if (!r)
00458       goto done;
00459     if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
00460       goto done;
00461 
00462     env->key = r;
00463     r = NULL;
00464   done:
00465     if (e)
00466       BN_free(e);
00467     if (r)
00468       RSA_free(r);
00469     }
00470 #endif
00471   if (!env->key) {
00472     crypto_log_errors(LOG_WARN, "generating RSA key");
00473     return -1;
00474   }
00475 
00476   return 0;
00477 }
00478 
00483 /* Used here, and used for testing. */
00484 int
00485 crypto_pk_read_private_key_from_string(crypto_pk_t *env,
00486                                        const char *s, ssize_t len)
00487 {
00488   BIO *b;
00489 
00490   tor_assert(env);
00491   tor_assert(s);
00492   tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
00493 
00494   /* Create a read-only memory BIO, backed by the string 's' */
00495   b = BIO_new_mem_buf((char*)s, (int)len);
00496   if (!b)
00497     return -1;
00498 
00499   if (env->key)
00500     RSA_free(env->key);
00501 
00502   env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
00503 
00504   BIO_free(b);
00505 
00506   if (!env->key) {
00507     crypto_log_errors(LOG_WARN, "Error parsing private key");
00508     return -1;
00509   }
00510   return 0;
00511 }
00512 
00516 int
00517 crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
00518                                          const char *keyfile)
00519 {
00520   char *contents;
00521   int r;
00522 
00523   /* Read the file into a string. */
00524   contents = read_file_to_str(keyfile, 0, NULL);
00525   if (!contents) {
00526     log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
00527     return -1;
00528   }
00529 
00530   /* Try to parse it. */
00531   r = crypto_pk_read_private_key_from_string(env, contents, -1);
00532   memset(contents, 0, strlen(contents));
00533   tor_free(contents);
00534   if (r)
00535     return -1; /* read_private_key_from_string already warned, so we don't.*/
00536 
00537   /* Make sure it's valid. */
00538   if (crypto_pk_check_key(env) <= 0)
00539     return -1;
00540 
00541   return 0;
00542 }
00543 
00545 static int
00546 crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
00547                                    size_t *len, int is_public)
00548 {
00549   BUF_MEM *buf;
00550   BIO *b;
00551   int r;
00552 
00553   tor_assert(env);
00554   tor_assert(env->key);
00555   tor_assert(dest);
00556 
00557   b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
00558   if (!b)
00559     return -1;
00560 
00561   /* Now you can treat b as if it were a file.  Just use the
00562    * PEM_*_bio_* functions instead of the non-bio variants.
00563    */
00564   if (is_public)
00565     r = PEM_write_bio_RSAPublicKey(b, env->key);
00566   else
00567     r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
00568 
00569   if (!r) {
00570     crypto_log_errors(LOG_WARN, "writing RSA key to string");
00571     BIO_free(b);
00572     return -1;
00573   }
00574 
00575   BIO_get_mem_ptr(b, &buf);
00576   (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
00577   BIO_free(b);
00578 
00579   *dest = tor_malloc(buf->length+1);
00580   memcpy(*dest, buf->data, buf->length);
00581   (*dest)[buf->length] = 0; /* nul terminate it */
00582   *len = buf->length;
00583   BUF_MEM_free(buf);
00584 
00585   return 0;
00586 }
00587 
00593 int
00594 crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
00595                                      size_t *len)
00596 {
00597   return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
00598 }
00599 
00605 int
00606 crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
00607                                      size_t *len)
00608 {
00609   return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
00610 }
00611 
00616 int
00617 crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
00618                                       size_t len)
00619 {
00620   BIO *b;
00621 
00622   tor_assert(env);
00623   tor_assert(src);
00624   tor_assert(len<INT_MAX);
00625 
00626   b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
00627   if (!b)
00628     return -1;
00629 
00630   BIO_write(b, src, (int)len);
00631 
00632   if (env->key)
00633     RSA_free(env->key);
00634   env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
00635   BIO_free(b);
00636   if (!env->key) {
00637     crypto_log_errors(LOG_WARN, "reading public key from string");
00638     return -1;
00639   }
00640 
00641   return 0;
00642 }
00643 
00647 int
00648 crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
00649                                         const char *fname)
00650 {
00651   BIO *bio;
00652   char *cp;
00653   long len;
00654   char *s;
00655   int r;
00656 
00657   tor_assert(PRIVATE_KEY_OK(env));
00658 
00659   if (!(bio = BIO_new(BIO_s_mem())))
00660     return -1;
00661   if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
00662       == 0) {
00663     crypto_log_errors(LOG_WARN, "writing private key");
00664     BIO_free(bio);
00665     return -1;
00666   }
00667   len = BIO_get_mem_data(bio, &cp);
00668   tor_assert(len >= 0);
00669   s = tor_malloc(len+1);
00670   memcpy(s, cp, len);
00671   s[len]='\0';
00672   r = write_str_to_file(fname, s, 0);
00673   BIO_free(bio);
00674   memset(s, 0, strlen(s));
00675   tor_free(s);
00676   return r;
00677 }
00678 
00681 int
00682 crypto_pk_check_key(crypto_pk_t *env)
00683 {
00684   int r;
00685   tor_assert(env);
00686 
00687   r = RSA_check_key(env->key);
00688   if (r <= 0)
00689     crypto_log_errors(LOG_WARN,"checking RSA key");
00690   return r;
00691 }
00692 
00695 int
00696 crypto_pk_key_is_private(const crypto_pk_t *key)
00697 {
00698   tor_assert(key);
00699   return PRIVATE_KEY_OK(key);
00700 }
00701 
00705 int
00706 crypto_pk_public_exponent_ok(crypto_pk_t *env)
00707 {
00708   tor_assert(env);
00709   tor_assert(env->key);
00710 
00711   return BN_is_word(env->key->e, 65537);
00712 }
00713 
00717 int
00718 crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
00719 {
00720   int result;
00721 
00722   if (!a || !b)
00723     return -1;
00724 
00725   if (!a->key || !b->key)
00726     return -1;
00727 
00728   tor_assert(PUBLIC_KEY_OK(a));
00729   tor_assert(PUBLIC_KEY_OK(b));
00730   result = BN_cmp((a->key)->n, (b->key)->n);
00731   if (result)
00732     return result;
00733   return BN_cmp((a->key)->e, (b->key)->e);
00734 }
00735 
00737 size_t
00738 crypto_pk_keysize(crypto_pk_t *env)
00739 {
00740   tor_assert(env);
00741   tor_assert(env->key);
00742 
00743   return (size_t) RSA_size(env->key);
00744 }
00745 
00747 int
00748 crypto_pk_num_bits(crypto_pk_t *env)
00749 {
00750   tor_assert(env);
00751   tor_assert(env->key);
00752   tor_assert(env->key->n);
00753 
00754   return BN_num_bits(env->key->n);
00755 }
00756 
00759 crypto_pk_t *
00760 crypto_pk_dup_key(crypto_pk_t *env)
00761 {
00762   tor_assert(env);
00763   tor_assert(env->key);
00764 
00765   env->refs++;
00766   return env;
00767 }
00768 
00770 crypto_pk_t *
00771 crypto_pk_copy_full(crypto_pk_t *env)
00772 {
00773   RSA *new_key;
00774   int privatekey = 0;
00775   tor_assert(env);
00776   tor_assert(env->key);
00777 
00778   if (PRIVATE_KEY_OK(env)) {
00779     new_key = RSAPrivateKey_dup(env->key);
00780     privatekey = 1;
00781   } else {
00782     new_key = RSAPublicKey_dup(env->key);
00783   }
00784   if (!new_key) {
00785     log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
00786             privatekey?"private":"public");
00787     crypto_log_errors(LOG_ERR,
00788                       privatekey ? "Duplicating a private key" :
00789                       "Duplicating a public key");
00790     tor_fragile_assert();
00791     return NULL;
00792   }
00793 
00794   return _crypto_new_pk_from_rsa(new_key);
00795 }
00796 
00805 int
00806 crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
00807                          const char *from, size_t fromlen, int padding)
00808 {
00809   int r;
00810   tor_assert(env);
00811   tor_assert(from);
00812   tor_assert(to);
00813   tor_assert(fromlen<INT_MAX);
00814   tor_assert(tolen >= crypto_pk_keysize(env));
00815 
00816   r = RSA_public_encrypt((int)fromlen,
00817                          (unsigned char*)from, (unsigned char*)to,
00818                          env->key, crypto_get_rsa_padding(padding));
00819   if (r<0) {
00820     crypto_log_errors(LOG_WARN, "performing RSA encryption");
00821     return -1;
00822   }
00823   return r;
00824 }
00825 
00834 int
00835 crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
00836                           size_t tolen,
00837                           const char *from, size_t fromlen,
00838                           int padding, int warnOnFailure)
00839 {
00840   int r;
00841   tor_assert(env);
00842   tor_assert(from);
00843   tor_assert(to);
00844   tor_assert(env->key);
00845   tor_assert(fromlen<INT_MAX);
00846   tor_assert(tolen >= crypto_pk_keysize(env));
00847   if (!env->key->p)
00848     /* Not a private key */
00849     return -1;
00850 
00851   r = RSA_private_decrypt((int)fromlen,
00852                           (unsigned char*)from, (unsigned char*)to,
00853                           env->key, crypto_get_rsa_padding(padding));
00854 
00855   if (r<0) {
00856     crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
00857                       "performing RSA decryption");
00858     return -1;
00859   }
00860   return r;
00861 }
00862 
00871 int
00872 crypto_pk_public_checksig(crypto_pk_t *env, char *to,
00873                           size_t tolen,
00874                           const char *from, size_t fromlen)
00875 {
00876   int r;
00877   tor_assert(env);
00878   tor_assert(from);
00879   tor_assert(to);
00880   tor_assert(fromlen < INT_MAX);
00881   tor_assert(tolen >= crypto_pk_keysize(env));
00882   r = RSA_public_decrypt((int)fromlen,
00883                          (unsigned char*)from, (unsigned char*)to,
00884                          env->key, RSA_PKCS1_PADDING);
00885 
00886   if (r<0) {
00887     crypto_log_errors(LOG_WARN, "checking RSA signature");
00888     return -1;
00889   }
00890   return r;
00891 }
00892 
00898 int
00899 crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
00900                                size_t datalen, const char *sig, size_t siglen)
00901 {
00902   char digest[DIGEST_LEN];
00903   char *buf;
00904   size_t buflen;
00905   int r;
00906 
00907   tor_assert(env);
00908   tor_assert(data);
00909   tor_assert(sig);
00910   tor_assert(datalen < SIZE_T_CEILING);
00911   tor_assert(siglen < SIZE_T_CEILING);
00912 
00913   if (crypto_digest(digest,data,datalen)<0) {
00914     log_warn(LD_BUG, "couldn't compute digest");
00915     return -1;
00916   }
00917   buflen = crypto_pk_keysize(env);
00918   buf = tor_malloc(buflen);
00919   r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
00920   if (r != DIGEST_LEN) {
00921     log_warn(LD_CRYPTO, "Invalid signature");
00922     tor_free(buf);
00923     return -1;
00924   }
00925   if (tor_memneq(buf, digest, DIGEST_LEN)) {
00926     log_warn(LD_CRYPTO, "Signature mismatched with digest.");
00927     tor_free(buf);
00928     return -1;
00929   }
00930   tor_free(buf);
00931 
00932   return 0;
00933 }
00934 
00943 int
00944 crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
00945                        const char *from, size_t fromlen)
00946 {
00947   int r;
00948   tor_assert(env);
00949   tor_assert(from);
00950   tor_assert(to);
00951   tor_assert(fromlen < INT_MAX);
00952   tor_assert(tolen >= crypto_pk_keysize(env));
00953   if (!env->key->p)
00954     /* Not a private key */
00955     return -1;
00956 
00957   r = RSA_private_encrypt((int)fromlen,
00958                           (unsigned char*)from, (unsigned char*)to,
00959                           env->key, RSA_PKCS1_PADDING);
00960   if (r<0) {
00961     crypto_log_errors(LOG_WARN, "generating RSA signature");
00962     return -1;
00963   }
00964   return r;
00965 }
00966 
00975 int
00976 crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
00977                               const char *from, size_t fromlen)
00978 {
00979   int r;
00980   char digest[DIGEST_LEN];
00981   if (crypto_digest(digest,from,fromlen)<0)
00982     return -1;
00983   r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
00984   memset(digest, 0, sizeof(digest));
00985   return r;
00986 }
00987 
01002 int
01003 crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
01004                                 char *to, size_t tolen,
01005                                 const char *from,
01006                                 size_t fromlen,
01007                                 int padding, int force)
01008 {
01009   int overhead, outlen, r;
01010   size_t pkeylen, symlen;
01011   crypto_cipher_t *cipher = NULL;
01012   char *buf = NULL;
01013 
01014   tor_assert(env);
01015   tor_assert(from);
01016   tor_assert(to);
01017   tor_assert(fromlen < SIZE_T_CEILING);
01018 
01019   overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
01020   pkeylen = crypto_pk_keysize(env);
01021 
01022   if (!force && fromlen+overhead <= pkeylen) {
01023     /* It all fits in a single encrypt. */
01024     return crypto_pk_public_encrypt(env,to,
01025                                     tolen,
01026                                     from,fromlen,padding);
01027   }
01028   tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
01029   tor_assert(tolen >= pkeylen);
01030 
01031   cipher = crypto_cipher_new(NULL); /* generate a new key. */
01032 
01033   buf = tor_malloc(pkeylen+1);
01034   memcpy(buf, cipher->key, CIPHER_KEY_LEN);
01035   memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
01036 
01037   /* Length of symmetrically encrypted data. */
01038   symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
01039 
01040   outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
01041   if (outlen!=(int)pkeylen) {
01042     goto err;
01043   }
01044   r = crypto_cipher_encrypt(cipher, to+outlen,
01045                             from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
01046 
01047   if (r<0) goto err;
01048   memset(buf, 0, pkeylen);
01049   tor_free(buf);
01050   crypto_cipher_free(cipher);
01051   tor_assert(outlen+symlen < INT_MAX);
01052   return (int)(outlen + symlen);
01053  err:
01054 
01055   memset(buf, 0, pkeylen);
01056   tor_free(buf);
01057   crypto_cipher_free(cipher);
01058   return -1;
01059 }
01060 
01062 int
01063 crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
01064                                  char *to,
01065                                  size_t tolen,
01066                                  const char *from,
01067                                  size_t fromlen,
01068                                  int padding, int warnOnFailure)
01069 {
01070   int outlen, r;
01071   size_t pkeylen;
01072   crypto_cipher_t *cipher = NULL;
01073   char *buf = NULL;
01074 
01075   tor_assert(fromlen < SIZE_T_CEILING);
01076   pkeylen = crypto_pk_keysize(env);
01077 
01078   if (fromlen <= pkeylen) {
01079     return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
01080                                      warnOnFailure);
01081   }
01082 
01083   buf = tor_malloc(pkeylen);
01084   outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
01085                                      warnOnFailure);
01086   if (outlen<0) {
01087     log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
01088            "Error decrypting public-key data");
01089     goto err;
01090   }
01091   if (outlen < CIPHER_KEY_LEN) {
01092     log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
01093            "No room for a symmetric key");
01094     goto err;
01095   }
01096   cipher = crypto_cipher_new(buf);
01097   if (!cipher) {
01098     goto err;
01099   }
01100   memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
01101   outlen -= CIPHER_KEY_LEN;
01102   tor_assert(tolen - outlen >= fromlen - pkeylen);
01103   r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
01104   if (r<0)
01105     goto err;
01106   memset(buf,0,pkeylen);
01107   tor_free(buf);
01108   crypto_cipher_free(cipher);
01109   tor_assert(outlen + fromlen < INT_MAX);
01110   return (int)(outlen + (fromlen-pkeylen));
01111  err:
01112   memset(buf,0,pkeylen);
01113   tor_free(buf);
01114   crypto_cipher_free(cipher);
01115   return -1;
01116 }
01117 
01121 int
01122 crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
01123 {
01124   int len;
01125   unsigned char *buf, *cp;
01126   len = i2d_RSAPublicKey(pk->key, NULL);
01127   if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
01128     return -1;
01129   cp = buf = tor_malloc(len+1);
01130   len = i2d_RSAPublicKey(pk->key, &cp);
01131   if (len < 0) {
01132     crypto_log_errors(LOG_WARN,"encoding public key");
01133     tor_free(buf);
01134     return -1;
01135   }
01136   /* We don't encode directly into 'dest', because that would be illegal
01137    * type-punning.  (C99 is smarter than me, C99 is smarter than me...)
01138    */
01139   memcpy(dest,buf,len);
01140   tor_free(buf);
01141   return len;
01142 }
01143 
01147 crypto_pk_t *
01148 crypto_pk_asn1_decode(const char *str, size_t len)
01149 {
01150   RSA *rsa;
01151   unsigned char *buf;
01152   const unsigned char *cp;
01153   cp = buf = tor_malloc(len);
01154   memcpy(buf,str,len);
01155   rsa = d2i_RSAPublicKey(NULL, &cp, len);
01156   tor_free(buf);
01157   if (!rsa) {
01158     crypto_log_errors(LOG_WARN,"decoding public key");
01159     return NULL;
01160   }
01161   return _crypto_new_pk_from_rsa(rsa);
01162 }
01163 
01168 int
01169 crypto_pk_get_digest(crypto_pk_t *pk, char *digest_out)
01170 {
01171   unsigned char *buf, *bufp;
01172   int len;
01173 
01174   len = i2d_RSAPublicKey(pk->key, NULL);
01175   if (len < 0)
01176     return -1;
01177   buf = bufp = tor_malloc(len+1);
01178   len = i2d_RSAPublicKey(pk->key, &bufp);
01179   if (len < 0) {
01180     crypto_log_errors(LOG_WARN,"encoding public key");
01181     tor_free(buf);
01182     return -1;
01183   }
01184   if (crypto_digest(digest_out, (char*)buf, len) < 0) {
01185     tor_free(buf);
01186     return -1;
01187   }
01188   tor_free(buf);
01189   return 0;
01190 }
01191 
01194 int
01195 crypto_pk_get_all_digests(crypto_pk_t *pk, digests_t *digests_out)
01196 {
01197   unsigned char *buf, *bufp;
01198   int len;
01199 
01200   len = i2d_RSAPublicKey(pk->key, NULL);
01201   if (len < 0)
01202     return -1;
01203   buf = bufp = tor_malloc(len+1);
01204   len = i2d_RSAPublicKey(pk->key, &bufp);
01205   if (len < 0) {
01206     crypto_log_errors(LOG_WARN,"encoding public key");
01207     tor_free(buf);
01208     return -1;
01209   }
01210   if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
01211     tor_free(buf);
01212     return -1;
01213   }
01214   tor_free(buf);
01215   return 0;
01216 }
01217 
01220 /* static */ void
01221 add_spaces_to_fp(char *out, size_t outlen, const char *in)
01222 {
01223   int n = 0;
01224   char *end = out+outlen;
01225   tor_assert(outlen < SIZE_T_CEILING);
01226 
01227   while (*in && out<end) {
01228     *out++ = *in++;
01229     if (++n == 4 && *in && out<end) {
01230       n = 0;
01231       *out++ = ' ';
01232     }
01233   }
01234   tor_assert(out<end);
01235   *out = '\0';
01236 }
01237 
01248 int
01249 crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
01250 {
01251   char digest[DIGEST_LEN];
01252   char hexdigest[HEX_DIGEST_LEN+1];
01253   if (crypto_pk_get_digest(pk, digest)) {
01254     return -1;
01255   }
01256   base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
01257   if (add_space) {
01258     add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
01259   } else {
01260     strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
01261   }
01262   return 0;
01263 }
01264 
01267 int
01268 crypto_pk_check_fingerprint_syntax(const char *s)
01269 {
01270   int i;
01271   for (i = 0; i < FINGERPRINT_LEN; ++i) {
01272     if ((i%5) == 4) {
01273       if (!TOR_ISSPACE(s[i])) return 0;
01274     } else {
01275       if (!TOR_ISXDIGIT(s[i])) return 0;
01276     }
01277   }
01278   if (s[FINGERPRINT_LEN]) return 0;
01279   return 1;
01280 }
01281 
01282 /* symmetric crypto */
01283 
01286 const char *
01287 crypto_cipher_get_key(crypto_cipher_t *env)
01288 {
01289   return env->key;
01290 }
01291 
01296 int
01297 crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
01298                       const char *from, size_t fromlen)
01299 {
01300   tor_assert(env);
01301   tor_assert(env->cipher);
01302   tor_assert(from);
01303   tor_assert(fromlen);
01304   tor_assert(to);
01305   tor_assert(fromlen < SIZE_T_CEILING);
01306 
01307   aes_crypt(env->cipher, from, fromlen, to);
01308   return 0;
01309 }
01310 
01315 int
01316 crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
01317                       const char *from, size_t fromlen)
01318 {
01319   tor_assert(env);
01320   tor_assert(from);
01321   tor_assert(to);
01322   tor_assert(fromlen < SIZE_T_CEILING);
01323 
01324   aes_crypt(env->cipher, from, fromlen, to);
01325   return 0;
01326 }
01327 
01331 int
01332 crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
01333 {
01334   tor_assert(len < SIZE_T_CEILING);
01335   aes_crypt_inplace(env->cipher, buf, len);
01336   return 0;
01337 }
01338 
01345 int
01346 crypto_cipher_encrypt_with_iv(const char *key,
01347                               char *to, size_t tolen,
01348                               const char *from, size_t fromlen)
01349 {
01350   crypto_cipher_t *cipher;
01351   tor_assert(from);
01352   tor_assert(to);
01353   tor_assert(fromlen < INT_MAX);
01354 
01355   if (fromlen < 1)
01356     return -1;
01357   if (tolen < fromlen + CIPHER_IV_LEN)
01358     return -1;
01359 
01360   cipher = crypto_cipher_new_with_iv(key, NULL);
01361 
01362   memcpy(to, cipher->iv, CIPHER_IV_LEN);
01363   crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
01364   crypto_cipher_free(cipher);
01365   return (int)(fromlen + CIPHER_IV_LEN);
01366 }
01367 
01374 int
01375 crypto_cipher_decrypt_with_iv(const char *key,
01376                               char *to, size_t tolen,
01377                               const char *from, size_t fromlen)
01378 {
01379   crypto_cipher_t *cipher;
01380   tor_assert(key);
01381   tor_assert(from);
01382   tor_assert(to);
01383   tor_assert(fromlen < INT_MAX);
01384 
01385   if (fromlen <= CIPHER_IV_LEN)
01386     return -1;
01387   if (tolen < fromlen - CIPHER_IV_LEN)
01388     return -1;
01389 
01390   cipher = crypto_cipher_new_with_iv(key, from);
01391 
01392   crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
01393   crypto_cipher_free(cipher);
01394   return (int)(fromlen - CIPHER_IV_LEN);
01395 }
01396 
01397 /* SHA-1 */
01398 
01403 int
01404 crypto_digest(char *digest, const char *m, size_t len)
01405 {
01406   tor_assert(m);
01407   tor_assert(digest);
01408   return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
01409 }
01410 
01414 int
01415 crypto_digest256(char *digest, const char *m, size_t len,
01416                  digest_algorithm_t algorithm)
01417 {
01418   tor_assert(m);
01419   tor_assert(digest);
01420   tor_assert(algorithm == DIGEST_SHA256);
01421   return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
01422 }
01423 
01427 int
01428 crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
01429 {
01430   digest_algorithm_t i;
01431   tor_assert(ds_out);
01432   memset(ds_out, 0, sizeof(*ds_out));
01433   if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
01434     return -1;
01435   for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
01436     if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
01437       return -1;
01438   }
01439   return 0;
01440 }
01441 
01443 const char *
01444 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
01445 {
01446   switch (alg) {
01447     case DIGEST_SHA1:
01448       return "sha1";
01449     case DIGEST_SHA256:
01450       return "sha256";
01451     default:
01452       tor_fragile_assert();
01453       return "??unknown_digest??";
01454   }
01455 }
01456 
01459 int
01460 crypto_digest_algorithm_parse_name(const char *name)
01461 {
01462   if (!strcmp(name, "sha1"))
01463     return DIGEST_SHA1;
01464   else if (!strcmp(name, "sha256"))
01465     return DIGEST_SHA256;
01466   else
01467     return -1;
01468 }
01469 
01471 struct crypto_digest_t {
01472   union {
01473     SHA_CTX sha1; 
01474     SHA256_CTX sha2; 
01475   } d; 
01477   digest_algorithm_t algorithm : 8; 
01478 };
01479 
01482 crypto_digest_t *
01483 crypto_digest_new(void)
01484 {
01485   crypto_digest_t *r;
01486   r = tor_malloc(sizeof(crypto_digest_t));
01487   SHA1_Init(&r->d.sha1);
01488   r->algorithm = DIGEST_SHA1;
01489   return r;
01490 }
01491 
01494 crypto_digest_t *
01495 crypto_digest256_new(digest_algorithm_t algorithm)
01496 {
01497   crypto_digest_t *r;
01498   tor_assert(algorithm == DIGEST_SHA256);
01499   r = tor_malloc(sizeof(crypto_digest_t));
01500   SHA256_Init(&r->d.sha2);
01501   r->algorithm = algorithm;
01502   return r;
01503 }
01504 
01507 void
01508 crypto_digest_free(crypto_digest_t *digest)
01509 {
01510   if (!digest)
01511     return;
01512   memset(digest, 0, sizeof(crypto_digest_t));
01513   tor_free(digest);
01514 }
01515 
01518 void
01519 crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
01520                         size_t len)
01521 {
01522   tor_assert(digest);
01523   tor_assert(data);
01524   /* Using the SHA*_*() calls directly means we don't support doing
01525    * SHA in hardware. But so far the delay of getting the question
01526    * to the hardware, and hearing the answer, is likely higher than
01527    * just doing it ourselves. Hashes are fast.
01528    */
01529   switch (digest->algorithm) {
01530     case DIGEST_SHA1:
01531       SHA1_Update(&digest->d.sha1, (void*)data, len);
01532       break;
01533     case DIGEST_SHA256:
01534       SHA256_Update(&digest->d.sha2, (void*)data, len);
01535       break;
01536     default:
01537       tor_fragile_assert();
01538       break;
01539   }
01540 }
01541 
01546 void
01547 crypto_digest_get_digest(crypto_digest_t *digest,
01548                          char *out, size_t out_len)
01549 {
01550   unsigned char r[DIGEST256_LEN];
01551   crypto_digest_t tmpenv;
01552   tor_assert(digest);
01553   tor_assert(out);
01554   /* memcpy into a temporary ctx, since SHA*_Final clears the context */
01555   memcpy(&tmpenv, digest, sizeof(crypto_digest_t));
01556   switch (digest->algorithm) {
01557     case DIGEST_SHA1:
01558       tor_assert(out_len <= DIGEST_LEN);
01559       SHA1_Final(r, &tmpenv.d.sha1);
01560       break;
01561     case DIGEST_SHA256:
01562       tor_assert(out_len <= DIGEST256_LEN);
01563       SHA256_Final(r, &tmpenv.d.sha2);
01564       break;
01565     default:
01566       log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
01567       /* If fragile_assert is not enabled, then we should at least not
01568        * leak anything. */
01569       memset(r, 0xff, sizeof(r));
01570       tor_fragile_assert();
01571       break;
01572   }
01573   memcpy(out, r, out_len);
01574   memset(r, 0, sizeof(r));
01575 }
01576 
01580 crypto_digest_t *
01581 crypto_digest_dup(const crypto_digest_t *digest)
01582 {
01583   crypto_digest_t *r;
01584   tor_assert(digest);
01585   r = tor_malloc(sizeof(crypto_digest_t));
01586   memcpy(r,digest,sizeof(crypto_digest_t));
01587   return r;
01588 }
01589 
01593 void
01594 crypto_digest_assign(crypto_digest_t *into,
01595                      const crypto_digest_t *from)
01596 {
01597   tor_assert(into);
01598   tor_assert(from);
01599   memcpy(into,from,sizeof(crypto_digest_t));
01600 }
01601 
01606 void
01607 crypto_hmac_sha1(char *hmac_out,
01608                  const char *key, size_t key_len,
01609                  const char *msg, size_t msg_len)
01610 {
01611   tor_assert(key_len < INT_MAX);
01612   tor_assert(msg_len < INT_MAX);
01613   HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
01614        (unsigned char*)hmac_out, NULL);
01615 }
01616 
01621 void
01622 crypto_hmac_sha256(char *hmac_out,
01623                    const char *key, size_t key_len,
01624                    const char *msg, size_t msg_len)
01625 {
01626 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(0,9,8)
01627   /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
01628   tor_assert(key_len < INT_MAX);
01629   tor_assert(msg_len < INT_MAX);
01630   HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
01631        (unsigned char*)hmac_out, NULL);
01632 #else
01633   /* OpenSSL doesn't have an EVP implementation for SHA256. We'll need
01634      to do HMAC on our own.
01635 
01636      HMAC isn't so hard: To compute HMAC(key, msg):
01637       1. If len(key) > blocksize, key = H(key).
01638       2. If len(key) < blocksize, right-pad key up to blocksize with 0 bytes.
01639       3. let ipad = key xor 0x363636363636....36
01640          let opad = key xor 0x5c5c5c5c5c5c....5c
01641          The result is H(opad | H( ipad | msg ) )
01642   */
01643 #define BLOCKSIZE 64
01644 #define DIGESTSIZE 32
01645   uint8_t k[BLOCKSIZE];
01646   uint8_t pad[BLOCKSIZE];
01647   uint8_t d[DIGESTSIZE];
01648   int i;
01649   SHA256_CTX st;
01650 
01651   tor_assert(key_len < INT_MAX);
01652   tor_assert(msg_len < INT_MAX);
01653 
01654   if (key_len <= BLOCKSIZE) {
01655     memset(k, 0, sizeof(k));
01656     memcpy(k, key, key_len); /* not time invariant in key_len */
01657   } else {
01658     SHA256((const uint8_t *)key, key_len, k);
01659     memset(k+DIGESTSIZE, 0, sizeof(k)-DIGESTSIZE);
01660   }
01661   for (i = 0; i < BLOCKSIZE; ++i)
01662     pad[i] = k[i] ^ 0x36;
01663   SHA256_Init(&st);
01664   SHA256_Update(&st, pad, BLOCKSIZE);
01665   SHA256_Update(&st, (uint8_t*)msg, msg_len);
01666   SHA256_Final(d, &st);
01667 
01668   for (i = 0; i < BLOCKSIZE; ++i)
01669     pad[i] = k[i] ^ 0x5c;
01670   SHA256_Init(&st);
01671   SHA256_Update(&st, pad, BLOCKSIZE);
01672   SHA256_Update(&st, d, DIGESTSIZE);
01673   SHA256_Final((uint8_t*)hmac_out, &st);
01674 
01675   /* Now clear everything. */
01676   memset(k, 0, sizeof(k));
01677   memset(pad, 0, sizeof(pad));
01678   memset(d, 0, sizeof(d));
01679   memset(&st, 0, sizeof(st));
01680 #undef BLOCKSIZE
01681 #undef DIGESTSIZE
01682 #endif
01683 }
01684 
01685 /* DH */
01686 
01688 #define DH_GENERATOR 2
01689 
01691 static BIGNUM *dh_param_p = NULL;
01693 static BIGNUM *dh_param_p_tls = NULL;
01695 static BIGNUM *dh_param_g = NULL;
01696 
01698 static BIGNUM *
01699 crypto_generate_dynamic_dh_modulus(void)
01700 {
01701   BIGNUM *dynamic_dh_modulus;
01702   DH *dh_parameters;
01703   int r, dh_codes;
01704   char *s;
01705 
01706   dynamic_dh_modulus = BN_new();
01707   tor_assert(dynamic_dh_modulus);
01708 
01709   dh_parameters = DH_generate_parameters(DH_BYTES*8, DH_GENERATOR, NULL, NULL);
01710   tor_assert(dh_parameters);
01711 
01712   r = DH_check(dh_parameters, &dh_codes);
01713   tor_assert(r && !dh_codes);
01714 
01715   BN_copy(dynamic_dh_modulus, dh_parameters->p);
01716   tor_assert(dynamic_dh_modulus);
01717 
01718   DH_free(dh_parameters);
01719 
01720   { /* log the dynamic DH modulus: */
01721     s = BN_bn2hex(dynamic_dh_modulus);
01722     tor_assert(s);
01723     log_info(LD_OR, "Dynamic DH modulus generated: [%s]", s);
01724     OPENSSL_free(s);
01725   }
01726 
01727   return dynamic_dh_modulus;
01728 }
01729 
01732 static int
01733 crypto_store_dynamic_dh_modulus(const char *fname)
01734 {
01735   int len, new_len;
01736   DH *dh = NULL;
01737   unsigned char *dh_string_repr = NULL, *cp = NULL;
01738   char *base64_encoded_dh = NULL;
01739   char *file_string = NULL;
01740   int retval = -1;
01741   static const char file_header[] = "# This file contains stored Diffie-"
01742     "Hellman parameters for future use.\n# You *do not* need to edit this "
01743     "file.\n\n";
01744 
01745   tor_assert(fname);
01746 
01747   if (!dh_param_p_tls) {
01748     log_info(LD_CRYPTO, "Tried to store a DH modulus that does not exist.");
01749     goto done;
01750   }
01751 
01752   if (!(dh = DH_new()))
01753     goto done;
01754   if (!(dh->p = BN_dup(dh_param_p_tls)))
01755     goto done;
01756   if (!(dh->g = BN_new()))
01757     goto done;
01758   if (!BN_set_word(dh->g, DH_GENERATOR))
01759     goto done;
01760 
01761   len = i2d_DHparams(dh, NULL);
01762   if (len < 0) {
01763     log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (1).");
01764     goto done;
01765   }
01766 
01767   cp = dh_string_repr = tor_malloc_zero(len+1);
01768   len = i2d_DHparams(dh, &cp);
01769   if ((len < 0) || ((cp - dh_string_repr) != len)) {
01770     log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (2).");
01771     goto done;
01772   }
01773 
01774   base64_encoded_dh = tor_malloc_zero(len * 2); /* should be enough */
01775   new_len = base64_encode(base64_encoded_dh, len * 2,
01776                           (char *)dh_string_repr, len);
01777   if (new_len < 0) {
01778     log_warn(LD_CRYPTO, "Error occured while base64-encoding DH modulus.");
01779     goto done;
01780   }
01781 
01782   /* concatenate file header and the dh parameters blob */
01783   new_len = tor_asprintf(&file_string, "%s%s", file_header, base64_encoded_dh);
01784 
01785   /* write to file */
01786   if (write_bytes_to_new_file(fname, file_string, new_len, 0) < 0) {
01787     log_info(LD_CRYPTO, "'%s' was already occupied.", fname);
01788     goto done;
01789   }
01790 
01791   retval = 0;
01792 
01793  done:
01794   if (dh)
01795     DH_free(dh);
01796   tor_free(dh_string_repr);
01797   tor_free(base64_encoded_dh);
01798   tor_free(file_string);
01799 
01800   return retval;
01801 }
01802 
01805 static BIGNUM *
01806 crypto_get_stored_dynamic_dh_modulus(const char *fname)
01807 {
01808   int retval;
01809   char *contents = NULL;
01810   const char *contents_tmp = NULL;
01811   int dh_codes;
01812   DH *stored_dh = NULL;
01813   BIGNUM *dynamic_dh_modulus = NULL;
01814   int length = 0;
01815   unsigned char *base64_decoded_dh = NULL;
01816   const unsigned char *cp = NULL;
01817 
01818   tor_assert(fname);
01819 
01820   contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
01821   if (!contents) {
01822     log_info(LD_CRYPTO, "Could not open file '%s'", fname);
01823     goto done; /*usually means that ENOENT. don't try to move file to broken.*/
01824   }
01825 
01826   /* skip the file header */
01827   contents_tmp = eat_whitespace(contents);
01828   if (!*contents_tmp) {
01829     log_warn(LD_CRYPTO, "Stored dynamic DH modulus file "
01830              "seems corrupted (eat_whitespace).");
01831     goto err;
01832   }
01833 
01834   /* 'fname' contains the DH parameters stored in base64-ed DER
01835    *  format. We are only interested in the DH modulus.
01836    *  NOTE: We allocate more storage here than we need. Since we're already
01837    *  doing that, we can also add 1 byte extra to appease Coverity's
01838    *  scanner. */
01839 
01840   cp = base64_decoded_dh = tor_malloc_zero(strlen(contents_tmp) + 1);
01841   length = base64_decode((char *)base64_decoded_dh, strlen(contents_tmp),
01842                          contents_tmp, strlen(contents_tmp));
01843   if (length < 0) {
01844     log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (base64).");
01845     goto err;
01846   }
01847 
01848   stored_dh = d2i_DHparams(NULL, &cp, length);
01849   if ((!stored_dh) || (cp - base64_decoded_dh != length)) {
01850     log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (d2i).");
01851     goto err;
01852   }
01853 
01854   { /* check the cryptographic qualities of the stored dynamic DH modulus: */
01855     retval = DH_check(stored_dh, &dh_codes);
01856     if (!retval || dh_codes) {
01857       log_warn(LD_CRYPTO, "Stored dynamic DH modulus is not a safe prime.");
01858       goto err;
01859     }
01860 
01861     retval = DH_size(stored_dh);
01862     if (retval < DH_BYTES) {
01863       log_warn(LD_CRYPTO, "Stored dynamic DH modulus is smaller "
01864                "than '%d' bits.", DH_BYTES*8);
01865       goto err;
01866     }
01867 
01868     if (!BN_is_word(stored_dh->g, 2)) {
01869       log_warn(LD_CRYPTO, "Stored dynamic DH parameters do not use '2' "
01870                "as the group generator.");
01871       goto err;
01872     }
01873   }
01874 
01875   { /* log the dynamic DH modulus: */
01876     char *s = BN_bn2hex(stored_dh->p);
01877     tor_assert(s);
01878     log_info(LD_OR, "Found stored dynamic DH modulus: [%s]", s);
01879     OPENSSL_free(s);
01880   }
01881 
01882   goto done;
01883 
01884  err:
01885 
01886   {
01887     /* move broken prime to $filename.broken */
01888     char *fname_new=NULL;
01889     tor_asprintf(&fname_new, "%s.broken", fname);
01890 
01891     log_warn(LD_CRYPTO, "Moving broken dynamic DH prime to '%s'.", fname_new);
01892 
01893     if (replace_file(fname, fname_new))
01894       log_notice(LD_CRYPTO, "Error while moving '%s' to '%s'.",
01895                  fname, fname_new);
01896 
01897     tor_free(fname_new);
01898   }
01899 
01900   if (stored_dh) {
01901     DH_free(stored_dh);
01902     stored_dh = NULL;
01903   }
01904 
01905  done:
01906   tor_free(contents);
01907   tor_free(base64_decoded_dh);
01908 
01909   if (stored_dh) {
01910     dynamic_dh_modulus = BN_dup(stored_dh->p);
01911     DH_free(stored_dh);
01912   }
01913 
01914   return dynamic_dh_modulus;
01915 }
01916 
01923 void
01924 crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname)
01925 {
01926   BIGNUM *tls_prime = NULL;
01927   int store_dh_prime_afterwards = 0;
01928   int r;
01929 
01930   /* If the space is occupied, free the previous TLS DH prime */
01931   if (dh_param_p_tls) {
01932     BN_free(dh_param_p_tls);
01933     dh_param_p_tls = NULL;
01934   }
01935 
01936   if (dynamic_dh_modulus_fname) { /* use dynamic DH modulus: */
01937     log_info(LD_OR, "Using stored dynamic DH modulus.");
01938     tls_prime = crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname);
01939 
01940     if (!tls_prime) {
01941       log_notice(LD_OR, "Generating fresh dynamic DH modulus. "
01942                  "This might take a while...");
01943       tls_prime = crypto_generate_dynamic_dh_modulus();
01944 
01945       store_dh_prime_afterwards++;
01946     }
01947   } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
01948     tls_prime = BN_new();
01949     tor_assert(tls_prime);
01950 
01951     /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
01952      * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
01953      * prime.
01954      */
01955     r =BN_hex2bn(&tls_prime,
01956                  "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
01957                  "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
01958                  "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
01959                  "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
01960                  "B0E7393E0F24218EB3");
01961     tor_assert(r);
01962   }
01963 
01964   tor_assert(tls_prime);
01965 
01966   dh_param_p_tls = tls_prime;
01967 
01968   if (store_dh_prime_afterwards)
01969     /* save the new dynamic DH modulus to disk. */
01970     if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname)) {
01971       log_notice(LD_CRYPTO, "Failed while storing dynamic DH modulus. "
01972                  "Make sure your data directory is sane.");
01973     }
01974 }
01975 
01978 static void
01979 init_dh_param(void)
01980 {
01981   BIGNUM *circuit_dh_prime, *generator;
01982   int r;
01983   if (dh_param_p && dh_param_g)
01984     return;
01985 
01986   circuit_dh_prime = BN_new();
01987   generator = BN_new();
01988   tor_assert(circuit_dh_prime && generator);
01989 
01990   /* Set our generator for all DH parameters */
01991   r = BN_set_word(generator, DH_GENERATOR);
01992   tor_assert(r);
01993 
01994   /* This is from rfc2409, section 6.2.  It's a safe prime, and
01995      supposedly it equals:
01996         2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
01997   */
01998   r = BN_hex2bn(&circuit_dh_prime,
01999                 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
02000                 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
02001                 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
02002                 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
02003                 "49286651ECE65381FFFFFFFFFFFFFFFF");
02004   tor_assert(r);
02005 
02006   /* Set the new values as the global DH parameters. */
02007   dh_param_p = circuit_dh_prime;
02008   dh_param_g = generator;
02009 
02010   /* Ensure that we have TLS DH parameters set up, too, even if we're
02011      going to change them soon. */
02012   if (!dh_param_p_tls) {
02013     crypto_set_tls_dh_prime(NULL);
02014   }
02015 }
02016 
02021 #define DH_PRIVATE_KEY_BITS 320
02022 
02025 crypto_dh_t *
02026 crypto_dh_new(int dh_type)
02027 {
02028   crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
02029 
02030   tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
02031              dh_type == DH_TYPE_REND);
02032 
02033   if (!dh_param_p)
02034     init_dh_param();
02035 
02036   if (!(res->dh = DH_new()))
02037     goto err;
02038 
02039   if (dh_type == DH_TYPE_TLS) {
02040     if (!(res->dh->p = BN_dup(dh_param_p_tls)))
02041       goto err;
02042   } else {
02043     if (!(res->dh->p = BN_dup(dh_param_p)))
02044       goto err;
02045   }
02046 
02047   if (!(res->dh->g = BN_dup(dh_param_g)))
02048     goto err;
02049 
02050   res->dh->length = DH_PRIVATE_KEY_BITS;
02051 
02052   return res;
02053  err:
02054   crypto_log_errors(LOG_WARN, "creating DH object");
02055   if (res->dh) DH_free(res->dh); /* frees p and g too */
02056   tor_free(res);
02057   return NULL;
02058 }
02059 
02062 int
02063 crypto_dh_get_bytes(crypto_dh_t *dh)
02064 {
02065   tor_assert(dh);
02066   return DH_size(dh->dh);
02067 }
02068 
02072 int
02073 crypto_dh_generate_public(crypto_dh_t *dh)
02074 {
02075  again:
02076   if (!DH_generate_key(dh->dh)) {
02077     crypto_log_errors(LOG_WARN, "generating DH key");
02078     return -1;
02079   }
02080   if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
02081     log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid.  I guess once-in-"
02082              "the-universe chances really do happen.  Trying again.");
02083     /* Free and clear the keys, so OpenSSL will actually try again. */
02084     BN_free(dh->dh->pub_key);
02085     BN_free(dh->dh->priv_key);
02086     dh->dh->pub_key = dh->dh->priv_key = NULL;
02087     goto again;
02088   }
02089   return 0;
02090 }
02091 
02096 int
02097 crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
02098 {
02099   int bytes;
02100   tor_assert(dh);
02101   if (!dh->dh->pub_key) {
02102     if (crypto_dh_generate_public(dh)<0)
02103       return -1;
02104   }
02105 
02106   tor_assert(dh->dh->pub_key);
02107   bytes = BN_num_bytes(dh->dh->pub_key);
02108   tor_assert(bytes >= 0);
02109   if (pubkey_len < (size_t)bytes) {
02110     log_warn(LD_CRYPTO,
02111              "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
02112              (int) pubkey_len, bytes);
02113     return -1;
02114   }
02115 
02116   memset(pubkey, 0, pubkey_len);
02117   BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
02118 
02119   return 0;
02120 }
02121 
02126 static int
02127 tor_check_dh_key(int severity, BIGNUM *bn)
02128 {
02129   BIGNUM *x;
02130   char *s;
02131   tor_assert(bn);
02132   x = BN_new();
02133   tor_assert(x);
02134   if (!dh_param_p)
02135     init_dh_param();
02136   BN_set_word(x, 1);
02137   if (BN_cmp(bn,x)<=0) {
02138     log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
02139     goto err;
02140   }
02141   BN_copy(x,dh_param_p);
02142   BN_sub_word(x, 1);
02143   if (BN_cmp(bn,x)>=0) {
02144     log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
02145     goto err;
02146   }
02147   BN_free(x);
02148   return 0;
02149  err:
02150   BN_free(x);
02151   s = BN_bn2hex(bn);
02152   log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
02153   OPENSSL_free(s);
02154   return -1;
02155 }
02156 
02157 #undef MIN
02158 #define MIN(a,b) ((a)<(b)?(a):(b))
02159 
02169 ssize_t
02170 crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
02171                          const char *pubkey, size_t pubkey_len,
02172                          char *secret_out, size_t secret_bytes_out)
02173 {
02174   char *secret_tmp = NULL;
02175   BIGNUM *pubkey_bn = NULL;
02176   size_t secret_len=0, secret_tmp_len=0;
02177   int result=0;
02178   tor_assert(dh);
02179   tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
02180   tor_assert(pubkey_len < INT_MAX);
02181 
02182   if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
02183                               (int)pubkey_len, NULL)))
02184     goto error;
02185   if (tor_check_dh_key(severity, pubkey_bn)<0) {
02186     /* Check for invalid public keys. */
02187     log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
02188     goto error;
02189   }
02190   secret_tmp_len = crypto_dh_get_bytes(dh);
02191   secret_tmp = tor_malloc(secret_tmp_len);
02192   result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
02193   if (result < 0) {
02194     log_warn(LD_CRYPTO,"DH_compute_key() failed.");
02195     goto error;
02196   }
02197   secret_len = result;
02198   if (crypto_expand_key_material(secret_tmp, secret_len,
02199                                  secret_out, secret_bytes_out)<0)
02200     goto error;
02201   secret_len = secret_bytes_out;
02202 
02203   goto done;
02204  error:
02205   result = -1;
02206  done:
02207   crypto_log_errors(LOG_WARN, "completing DH handshake");
02208   if (pubkey_bn)
02209     BN_free(pubkey_bn);
02210   if (secret_tmp) {
02211     memset(secret_tmp, 0, secret_tmp_len);
02212     tor_free(secret_tmp);
02213   }
02214   if (result < 0)
02215     return result;
02216   else
02217     return secret_len;
02218 }
02219 
02227 int
02228 crypto_expand_key_material(const char *key_in, size_t key_in_len,
02229                            char *key_out, size_t key_out_len)
02230 {
02231   int i;
02232   char *cp, *tmp = tor_malloc(key_in_len+1);
02233   char digest[DIGEST_LEN];
02234 
02235   /* If we try to get more than this amount of key data, we'll repeat blocks.*/
02236   tor_assert(key_out_len <= DIGEST_LEN*256);
02237 
02238   memcpy(tmp, key_in, key_in_len);
02239   for (cp = key_out, i=0; cp < key_out+key_out_len;
02240        ++i, cp += DIGEST_LEN) {
02241     tmp[key_in_len] = i;
02242     if (crypto_digest(digest, tmp, key_in_len+1))
02243       goto err;
02244     memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
02245   }
02246   memset(tmp, 0, key_in_len+1);
02247   tor_free(tmp);
02248   memset(digest, 0, sizeof(digest));
02249   return 0;
02250 
02251  err:
02252   memset(tmp, 0, key_in_len+1);
02253   tor_free(tmp);
02254   memset(digest, 0, sizeof(digest));
02255   return -1;
02256 }
02257 
02260 void
02261 crypto_dh_free(crypto_dh_t *dh)
02262 {
02263   if (!dh)
02264     return;
02265   tor_assert(dh->dh);
02266   DH_free(dh->dh);
02267   tor_free(dh);
02268 }
02269 
02270 /* random numbers */
02271 
02276 #define ADD_ENTROPY 32
02277 
02284 #define RAND_POLL_IS_SAFE                       \
02285   ((OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,7,'j') &&        \
02286     OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)) ||     \
02287    OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
02288 
02290 static void
02291 seed_weak_rng(void)
02292 {
02293   unsigned seed;
02294   crypto_rand((void*)&seed, sizeof(seed));
02295   tor_init_weak_random(seed);
02296 }
02297 
02302 int
02303 crypto_seed_rng(int startup)
02304 {
02305   int rand_poll_status = 0;
02306 
02307   /* local variables */
02308 #ifdef _WIN32
02309   unsigned char buf[ADD_ENTROPY];
02310   static int provider_set = 0;
02311   static HCRYPTPROV provider;
02312 #else
02313   char buf[ADD_ENTROPY];
02314   static const char *filenames[] = {
02315     "/dev/srandom", "/dev/urandom", "/dev/random", NULL
02316   };
02317   int fd, i;
02318   size_t n;
02319 #endif
02320 
02321   /* OpenSSL has a RAND_poll function that knows about more kinds of
02322    * entropy than we do.  We'll try calling that, *and* calling our own entropy
02323    * functions.  If one succeeds, we'll accept the RNG as seeded. */
02324   if (startup || RAND_POLL_IS_SAFE) {
02325     rand_poll_status = RAND_poll();
02326     if (rand_poll_status == 0)
02327       log_warn(LD_CRYPTO, "RAND_poll() failed.");
02328   }
02329 
02330 #ifdef _WIN32
02331   if (!provider_set) {
02332     if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
02333                              CRYPT_VERIFYCONTEXT)) {
02334       if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
02335         log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
02336         return rand_poll_status ? 0 : -1;
02337       }
02338     }
02339     provider_set = 1;
02340   }
02341   if (!CryptGenRandom(provider, sizeof(buf), buf)) {
02342     log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
02343     return rand_poll_status ? 0 : -1;
02344   }
02345   RAND_seed(buf, sizeof(buf));
02346   memset(buf, 0, sizeof(buf));
02347   seed_weak_rng();
02348   return 0;
02349 #else
02350   for (i = 0; filenames[i]; ++i) {
02351     fd = open(filenames[i], O_RDONLY, 0);
02352     if (fd<0) continue;
02353     log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
02354     n = read_all(fd, buf, sizeof(buf), 0);
02355     close(fd);
02356     if (n != sizeof(buf)) {
02357       log_warn(LD_CRYPTO,
02358                "Error reading from entropy source (read only %lu bytes).",
02359                (unsigned long)n);
02360       return -1;
02361     }
02362     RAND_seed(buf, (int)sizeof(buf));
02363     memset(buf, 0, sizeof(buf));
02364     seed_weak_rng();
02365     return 0;
02366   }
02367 
02368   log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
02369   return rand_poll_status ? 0 : -1;
02370 #endif
02371 }
02372 
02376 int
02377 crypto_rand(char *to, size_t n)
02378 {
02379   int r;
02380   tor_assert(n < INT_MAX);
02381   tor_assert(to);
02382   r = RAND_bytes((unsigned char*)to, (int)n);
02383   if (r == 0)
02384     crypto_log_errors(LOG_WARN, "generating random data");
02385   return (r == 1) ? 0 : -1;
02386 }
02387 
02391 int
02392 crypto_rand_int(unsigned int max)
02393 {
02394   unsigned int val;
02395   unsigned int cutoff;
02396   tor_assert(max <= ((unsigned int)INT_MAX)+1);
02397   tor_assert(max > 0); /* don't div by 0 */
02398 
02399   /* We ignore any values that are >= 'cutoff,' to avoid biasing the
02400    * distribution with clipping at the upper end of unsigned int's
02401    * range.
02402    */
02403   cutoff = UINT_MAX - (UINT_MAX%max);
02404   while (1) {
02405     crypto_rand((char*)&val, sizeof(val));
02406     if (val < cutoff)
02407       return val % max;
02408   }
02409 }
02410 
02413 uint64_t
02414 crypto_rand_uint64(uint64_t max)
02415 {
02416   uint64_t val;
02417   uint64_t cutoff;
02418   tor_assert(max < UINT64_MAX);
02419   tor_assert(max > 0); /* don't div by 0 */
02420 
02421   /* We ignore any values that are >= 'cutoff,' to avoid biasing the
02422    * distribution with clipping at the upper end of unsigned int's
02423    * range.
02424    */
02425   cutoff = UINT64_MAX - (UINT64_MAX%max);
02426   while (1) {
02427     crypto_rand((char*)&val, sizeof(val));
02428     if (val < cutoff)
02429       return val % max;
02430   }
02431 }
02432 
02436 double
02437 crypto_rand_double(void)
02438 {
02439   /* We just use an unsigned int here; we don't really care about getting
02440    * more than 32 bits of resolution */
02441   unsigned int uint;
02442   crypto_rand((char*)&uint, sizeof(uint));
02443 #if SIZEOF_INT == 4
02444 #define UINT_MAX_AS_DOUBLE 4294967296.0
02445 #elif SIZEOF_INT == 8
02446 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
02447 #else
02448 #error SIZEOF_INT is neither 4 nor 8
02449 #endif
02450   return ((double)uint) / UINT_MAX_AS_DOUBLE;
02451 }
02452 
02460 char *
02461 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
02462                        const char *suffix)
02463 {
02464   char *result, *rand_bytes;
02465   int randlen, rand_bytes_len;
02466   size_t resultlen, prefixlen;
02467 
02468   if (max_rand_len > MAX_DNS_LABEL_SIZE)
02469     max_rand_len = MAX_DNS_LABEL_SIZE;
02470   if (min_rand_len > max_rand_len)
02471     min_rand_len = max_rand_len;
02472 
02473   randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
02474 
02475   prefixlen = strlen(prefix);
02476   resultlen = prefixlen + strlen(suffix) + randlen + 16;
02477 
02478   rand_bytes_len = ((randlen*5)+7)/8;
02479   if (rand_bytes_len % 5)
02480     rand_bytes_len += 5 - (rand_bytes_len%5);
02481   rand_bytes = tor_malloc(rand_bytes_len);
02482   crypto_rand(rand_bytes, rand_bytes_len);
02483 
02484   result = tor_malloc(resultlen);
02485   memcpy(result, prefix, prefixlen);
02486   base32_encode(result+prefixlen, resultlen-prefixlen,
02487                 rand_bytes, rand_bytes_len);
02488   tor_free(rand_bytes);
02489   strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
02490 
02491   return result;
02492 }
02493 
02496 void *
02497 smartlist_choose(const smartlist_t *sl)
02498 {
02499   int len = smartlist_len(sl);
02500   if (len)
02501     return smartlist_get(sl,crypto_rand_int(len));
02502   return NULL; /* no elements to choose from */
02503 }
02504 
02506 void
02507 smartlist_shuffle(smartlist_t *sl)
02508 {
02509   int i;
02510   /* From the end of the list to the front, choose at random from the
02511      positions we haven't looked at yet, and swap that position into the
02512      current position.  Remember to give "no swap" the same probability as
02513      any other swap. */
02514   for (i = smartlist_len(sl)-1; i > 0; --i) {
02515     int j = crypto_rand_int(i+1);
02516     smartlist_swap(sl, i, j);
02517   }
02518 }
02519 
02525 int
02526 base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
02527 {
02528   /* FFFF we might want to rewrite this along the lines of base64_decode, if
02529    * it ever shows up in the profile. */
02530   EVP_ENCODE_CTX ctx;
02531   int len, ret;
02532   tor_assert(srclen < INT_MAX);
02533 
02534   /* 48 bytes of input -> 64 bytes of output plus newline.
02535      Plus one more byte, in case I'm wrong.
02536   */
02537   if (destlen < ((srclen/48)+1)*66)
02538     return -1;
02539   if (destlen > SIZE_T_CEILING)
02540     return -1;
02541 
02542   EVP_EncodeInit(&ctx);
02543   EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
02544                    (unsigned char*)src, (int)srclen);
02545   EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
02546   ret += len;
02547   return ret;
02548 }
02549 
02552 #define X 255
02553 #define SP 64
02554 #define PAD 65
02555 
02560 static const uint8_t base64_decode_table[256] = {
02561   X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
02562   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02563   SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
02564   52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
02565   X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
02566   15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
02567   X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
02568   41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
02569   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02570   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02571   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02572   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02573   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02574   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02575   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02576   X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
02577 };
02578 
02591 int
02592 base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
02593 {
02594 #ifdef USE_OPENSSL_BASE64
02595   EVP_ENCODE_CTX ctx;
02596   int len, ret;
02597   /* 64 bytes of input -> *up to* 48 bytes of output.
02598      Plus one more byte, in case I'm wrong.
02599   */
02600   if (destlen < ((srclen/64)+1)*49)
02601     return -1;
02602   if (destlen > SIZE_T_CEILING)
02603     return -1;
02604 
02605   EVP_DecodeInit(&ctx);
02606   EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
02607                    (unsigned char*)src, srclen);
02608   EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
02609   ret += len;
02610   return ret;
02611 #else
02612   const char *eos = src+srclen;
02613   uint32_t n=0;
02614   int n_idx=0;
02615   char *dest_orig = dest;
02616 
02617   /* Max number of bits == srclen*6.
02618    * Number of bytes required to hold all bits == (srclen*6)/8.
02619    * Yes, we want to round down: anything that hangs over the end of a
02620    * byte is padding. */
02621   if (destlen < (srclen*3)/4)
02622     return -1;
02623   if (destlen > SIZE_T_CEILING)
02624     return -1;
02625 
02626   /* Iterate over all the bytes in src.  Each one will add 0 or 6 bits to the
02627    * value we're decoding.  Accumulate bits in <b>n</b>, and whenever we have
02628    * 24 bits, batch them into 3 bytes and flush those bytes to dest.
02629    */
02630   for ( ; src < eos; ++src) {
02631     unsigned char c = (unsigned char) *src;
02632     uint8_t v = base64_decode_table[c];
02633     switch (v) {
02634       case X:
02635         /* This character isn't allowed in base64. */
02636         return -1;
02637       case SP:
02638         /* This character is whitespace, and has no effect. */
02639         continue;
02640       case PAD:
02641         /* We've hit an = character: the data is over. */
02642         goto end_of_loop;
02643       default:
02644         /* We have an actual 6-bit value.  Append it to the bits in n. */
02645         n = (n<<6) | v;
02646         if ((++n_idx) == 4) {
02647           /* We've accumulated 24 bits in n. Flush them. */
02648           *dest++ = (n>>16);
02649           *dest++ = (n>>8) & 0xff;
02650           *dest++ = (n) & 0xff;
02651           n_idx = 0;
02652           n = 0;
02653         }
02654     }
02655   }
02656  end_of_loop:
02657   /* If we have leftover bits, we need to cope. */
02658   switch (n_idx) {
02659     case 0:
02660     default:
02661       /* No leftover bits.  We win. */
02662       break;
02663     case 1:
02664       /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
02665       return -1;
02666     case 2:
02667       /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
02668       *dest++ = n >> 4;
02669       break;
02670     case 3:
02671       /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
02672       *dest++ = n >> 10;
02673       *dest++ = n >> 2;
02674   }
02675 
02676   tor_assert((dest-dest_orig) <= (ssize_t)destlen);
02677   tor_assert((dest-dest_orig) <= INT_MAX);
02678 
02679   return (int)(dest-dest_orig);
02680 #endif
02681 }
02682 #undef X
02683 #undef SP
02684 #undef PAD
02685 
02689 int
02690 digest_to_base64(char *d64, const char *digest)
02691 {
02692   char buf[256];
02693   base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
02694   buf[BASE64_DIGEST_LEN] = '\0';
02695   memcpy(d64, buf, BASE64_DIGEST_LEN+1);
02696   return 0;
02697 }
02698 
02702 int
02703 digest_from_base64(char *digest, const char *d64)
02704 {
02705 #ifdef USE_OPENSSL_BASE64
02706   char buf_in[BASE64_DIGEST_LEN+3];
02707   char buf[256];
02708   if (strlen(d64) != BASE64_DIGEST_LEN)
02709     return -1;
02710   memcpy(buf_in, d64, BASE64_DIGEST_LEN);
02711   memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
02712   if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
02713     return -1;
02714   memcpy(digest, buf, DIGEST_LEN);
02715   return 0;
02716 #else
02717   if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
02718     return 0;
02719   else
02720     return -1;
02721 #endif
02722 }
02723 
02727 int
02728 digest256_to_base64(char *d64, const char *digest)
02729 {
02730   char buf[256];
02731   base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
02732   buf[BASE64_DIGEST256_LEN] = '\0';
02733   memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
02734   return 0;
02735 }
02736 
02740 int
02741 digest256_from_base64(char *digest, const char *d64)
02742 {
02743 #ifdef USE_OPENSSL_BASE64
02744   char buf_in[BASE64_DIGEST256_LEN+3];
02745   char buf[256];
02746   if (strlen(d64) != BASE64_DIGEST256_LEN)
02747     return -1;
02748   memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
02749   memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
02750   if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
02751     return -1;
02752   memcpy(digest, buf, DIGEST256_LEN);
02753   return 0;
02754 #else
02755   if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
02756     return 0;
02757   else
02758     return -1;
02759 #endif
02760 }
02761 
02765 void
02766 base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
02767 {
02768   unsigned int i, v, u;
02769   size_t nbits = srclen * 8, bit;
02770 
02771   tor_assert(srclen < SIZE_T_CEILING/8);
02772   tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
02773   tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
02774   tor_assert(destlen < SIZE_T_CEILING);
02775 
02776   for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
02777     /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
02778     v = ((uint8_t)src[bit/8]) << 8;
02779     if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
02780     /* set u to the 5-bit value at the bit'th bit of src. */
02781     u = (v >> (11-(bit%8))) & 0x1F;
02782     dest[i] = BASE32_CHARS[u];
02783   }
02784   dest[i] = '\0';
02785 }
02786 
02790 int
02791 base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
02792 {
02793   /* XXXX we might want to rewrite this along the lines of base64_decode, if
02794    * it ever shows up in the profile. */
02795   unsigned int i;
02796   size_t nbits, j, bit;
02797   char *tmp;
02798   nbits = srclen * 5;
02799 
02800   tor_assert(srclen < SIZE_T_CEILING / 5);
02801   tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
02802   tor_assert((nbits/8) <= destlen); /* We need enough space. */
02803   tor_assert(destlen < SIZE_T_CEILING);
02804 
02805   /* Convert base32 encoded chars to the 5-bit values that they represent. */
02806   tmp = tor_malloc_zero(srclen);
02807   for (j = 0; j < srclen; ++j) {
02808     if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
02809     else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
02810     else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
02811     else {
02812       log_warn(LD_BUG, "illegal character in base32 encoded string");
02813       tor_free(tmp);
02814       return -1;
02815     }
02816   }
02817 
02818   /* Assemble result byte-wise by applying five possible cases. */
02819   for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
02820     switch (bit % 40) {
02821     case 0:
02822       dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
02823                 (((uint8_t)tmp[(bit/5)+1]) >> 2);
02824       break;
02825     case 8:
02826       dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
02827                 (((uint8_t)tmp[(bit/5)+1]) << 1) +
02828                 (((uint8_t)tmp[(bit/5)+2]) >> 4);
02829       break;
02830     case 16:
02831       dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
02832                 (((uint8_t)tmp[(bit/5)+1]) >> 1);
02833       break;
02834     case 24:
02835       dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
02836                 (((uint8_t)tmp[(bit/5)+1]) << 2) +
02837                 (((uint8_t)tmp[(bit/5)+2]) >> 3);
02838       break;
02839     case 32:
02840       dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
02841                 ((uint8_t)tmp[(bit/5)+1]);
02842       break;
02843     }
02844   }
02845 
02846   memset(tmp, 0, srclen);
02847   tor_free(tmp);
02848   tmp = NULL;
02849   return 0;
02850 }
02851 
02858 void
02859 secret_to_key(char *key_out, size_t key_out_len, const char *secret,
02860               size_t secret_len, const char *s2k_specifier)
02861 {
02862   crypto_digest_t *d;
02863   uint8_t c;
02864   size_t count, tmplen;
02865   char *tmp;
02866   tor_assert(key_out_len < SIZE_T_CEILING);
02867 
02868 #define EXPBIAS 6
02869   c = s2k_specifier[8];
02870   count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
02871 #undef EXPBIAS
02872 
02873   tor_assert(key_out_len <= DIGEST_LEN);
02874 
02875   d = crypto_digest_new();
02876   tmplen = 8+secret_len;
02877   tmp = tor_malloc(tmplen);
02878   memcpy(tmp,s2k_specifier,8);
02879   memcpy(tmp+8,secret,secret_len);
02880   secret_len += 8;
02881   while (count) {
02882     if (count >= secret_len) {
02883       crypto_digest_add_bytes(d, tmp, secret_len);
02884       count -= secret_len;
02885     } else {
02886       crypto_digest_add_bytes(d, tmp, count);
02887       count = 0;
02888     }
02889   }
02890   crypto_digest_get_digest(d, key_out, key_out_len);
02891   memset(tmp, 0, tmplen);
02892   tor_free(tmp);
02893   crypto_digest_free(d);
02894 }
02895 
02896 #ifdef TOR_IS_MULTITHREADED
02897 
02898 static void
02899 _openssl_locking_cb(int mode, int n, const char *file, int line)
02900 {
02901   (void)file;
02902   (void)line;
02903   if (!_openssl_mutexes)
02904     /* This is not a really good  fix for the
02905      * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
02906      * it can't hurt. */
02907     return;
02908   if (mode & CRYPTO_LOCK)
02909     tor_mutex_acquire(_openssl_mutexes[n]);
02910   else
02911     tor_mutex_release(_openssl_mutexes[n]);
02912 }
02913 
02916 struct CRYPTO_dynlock_value {
02917   tor_mutex_t *lock;
02918 };
02919 
02922 static struct CRYPTO_dynlock_value *
02923 _openssl_dynlock_create_cb(const char *file, int line)
02924 {
02925   struct CRYPTO_dynlock_value *v;
02926   (void)file;
02927   (void)line;
02928   v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
02929   v->lock = tor_mutex_new();
02930   return v;
02931 }
02932 
02935 static void
02936 _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
02937                          const char *file, int line)
02938 {
02939   (void)file;
02940   (void)line;
02941   if (mode & CRYPTO_LOCK)
02942     tor_mutex_acquire(v->lock);
02943   else
02944     tor_mutex_release(v->lock);
02945 }
02946 
02949 static void
02950 _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
02951                             const char *file, int line)
02952 {
02953   (void)file;
02954   (void)line;
02955   tor_mutex_free(v->lock);
02956   tor_free(v);
02957 }
02958 
02962 static int
02963 setup_openssl_threading(void)
02964 {
02965   int i;
02966   int n = CRYPTO_num_locks();
02967   _n_openssl_mutexes = n;
02968   _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
02969   for (i=0; i < n; ++i)
02970     _openssl_mutexes[i] = tor_mutex_new();
02971   CRYPTO_set_locking_callback(_openssl_locking_cb);
02972   CRYPTO_set_id_callback(tor_get_thread_id);
02973   CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
02974   CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
02975   CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
02976   return 0;
02977 }
02978 #else
02979 static int
02980 setup_openssl_threading(void)
02981 {
02982   return 0;
02983 }
02984 #endif
02985 
02988 int
02989 crypto_global_cleanup(void)
02990 {
02991   EVP_cleanup();
02992   ERR_remove_state(0);
02993   ERR_free_strings();
02994 
02995   if (dh_param_p)
02996     BN_free(dh_param_p);
02997   if (dh_param_p_tls)
02998     BN_free(dh_param_p_tls);
02999   if (dh_param_g)
03000     BN_free(dh_param_g);
03001 
03002 #ifndef DISABLE_ENGINES
03003   ENGINE_cleanup();
03004 #endif
03005 
03006   CONF_modules_unload(1);
03007   CRYPTO_cleanup_all_ex_data();
03008 #ifdef TOR_IS_MULTITHREADED
03009   if (_n_openssl_mutexes) {
03010     int n = _n_openssl_mutexes;
03011     tor_mutex_t **ms = _openssl_mutexes;
03012     int i;
03013     _openssl_mutexes = NULL;
03014     _n_openssl_mutexes = 0;
03015     for (i=0;i<n;++i) {
03016       tor_mutex_free(ms[i]);
03017     }
03018     tor_free(ms);
03019   }
03020 #endif
03021   return 0;
03022 }
03023