Back to index

tor  0.2.3.18-rc
tortls.c
Go to the documentation of this file.
00001 /* Copyright (c) 2003, Roger Dingledine.
00002  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00003  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00004 /* See LICENSE for licensing information */
00005 
00012 /* (Unlike other tor functions, these
00013  * are prefixed with tor_ in order to avoid conflicting with OpenSSL
00014  * functions and variables.)
00015  */
00016 
00017 #include "orconfig.h"
00018 
00019 #if defined (WINCE)
00020 #include <WinSock2.h>
00021 #endif
00022 
00023 #include <assert.h>
00024 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
00025  #ifndef _WIN32_WINNT
00026  #define _WIN32_WINNT 0x0501
00027  #endif
00028  #define WIN32_LEAN_AND_MEAN
00029  #if defined(_MSC_VER) && (_MSC_VER < 1300)
00030     #include <winsock.h>
00031  #else
00032     #include <winsock2.h>
00033     #include <ws2tcpip.h>
00034  #endif
00035 #endif
00036 #include <openssl/ssl.h>
00037 #include <openssl/ssl3.h>
00038 #include <openssl/err.h>
00039 #include <openssl/tls1.h>
00040 #include <openssl/asn1.h>
00041 #include <openssl/bio.h>
00042 #include <openssl/opensslv.h>
00043 
00044 #ifdef USE_BUFFEREVENTS
00045 #include <event2/bufferevent_ssl.h>
00046 #include <event2/buffer.h>
00047 #include <event2/event.h>
00048 #include "compat_libevent.h"
00049 #endif
00050 
00051 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
00052 #define TORTLS_PRIVATE
00053 
00054 #include "crypto.h"
00055 #include "tortls.h"
00056 #include "util.h"
00057 #include "torlog.h"
00058 #include "container.h"
00059 #include <string.h>
00060 
00061 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,7)
00062 #error "We require OpenSSL >= 0.9.7"
00063 #endif
00064 
00065 /* Enable the "v2" TLS handshake.
00066  */
00067 #define V2_HANDSHAKE_SERVER
00068 #define V2_HANDSHAKE_CLIENT
00069 
00070 /* Copied from or.h */
00071 #define LEGAL_NICKNAME_CHARACTERS \
00072   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
00073 
00075 #define IDENTITY_CERT_LIFETIME  (365*24*60*60)
00076 
00077 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
00078 
00079 #if (OPENSSL_VERSION_NUMBER  <  OPENSSL_V(0,9,8,'s') ||         \
00080      (OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(0,9,9) &&      \
00081       OPENSSL_VERSION_NUMBER <  OPENSSL_V(1,0,0,'f')))
00082 /* This is a version of OpenSSL before 0.9.8s/1.0.0f. It does not have
00083  * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
00084  * SSL3 safely at the same time.
00085  */
00086 #define DISABLE_SSL3_HANDSHAKE
00087 #endif
00088 
00089 /* We redefine these so that we can run correctly even if the vendor gives us
00090  * a version of OpenSSL that does not match its header files.  (Apple: I am
00091  * looking at you.)
00092  */
00093 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
00094 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
00095 #endif
00096 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
00097 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
00098 #endif
00099 
00102 static int use_unsafe_renegotiation_op = 0;
00105 static int use_unsafe_renegotiation_flag = 0;
00106 
00108 struct tor_cert_t {
00109   X509 *cert;
00110   uint8_t *encoded;
00111   size_t encoded_len;
00112   unsigned pkey_digests_set : 1;
00113   digests_t cert_digests;
00114   digests_t pkey_digests;
00115 };
00116 
00120 typedef struct tor_tls_context_t {
00121   int refcnt;
00122   SSL_CTX *ctx;
00123   tor_cert_t *my_link_cert;
00124   tor_cert_t *my_id_cert;
00125   tor_cert_t *my_auth_cert;
00126   crypto_pk_t *link_key;
00127   crypto_pk_t *auth_key;
00128 } tor_tls_context_t;
00129 
00130 #define TOR_TLS_MAGIC 0x71571571
00131 
00135 struct tor_tls_t {
00136   uint32_t magic;
00137   tor_tls_context_t *context; 
00138   SSL *ssl; 
00139   int socket; 
00140   char *address; 
00141   enum {
00142     TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
00143     TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
00144     TOR_TLS_ST_BUFFEREVENT
00145   } state : 3; 
00147   unsigned int isServer:1; 
00148   unsigned int wasV2Handshake:1; 
00154   unsigned int got_renegotiate:1;
00156   uint8_t server_handshake_count;
00157   size_t wantwrite_n; 
00162   unsigned long last_write_count;
00163   unsigned long last_read_count;
00166   void (*negotiated_callback)(tor_tls_t *tls, void *arg);
00168   void *callback_arg;
00169 };
00170 
00171 #ifdef V2_HANDSHAKE_CLIENT
00172 
00175 static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
00178 static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
00179 #endif
00180 
00183 static int tor_tls_object_ex_data_index = -1;
00184 
00186 static void
00187 tor_tls_allocate_tor_tls_object_ex_data_index(void)
00188 {
00189   if (tor_tls_object_ex_data_index == -1) {
00190     tor_tls_object_ex_data_index =
00191       SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
00192     tor_assert(tor_tls_object_ex_data_index != -1);
00193   }
00194 }
00195 
00198 static INLINE tor_tls_t *
00199 tor_tls_get_by_ssl(const SSL *ssl)
00200 {
00201   tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
00202   if (result)
00203     tor_assert(result->magic == TOR_TLS_MAGIC);
00204   return result;
00205 }
00206 
00207 static void tor_tls_context_decref(tor_tls_context_t *ctx);
00208 static void tor_tls_context_incref(tor_tls_context_t *ctx);
00209 static X509* tor_tls_create_certificate(crypto_pk_t *rsa,
00210                                         crypto_pk_t *rsa_sign,
00211                                         const char *cname,
00212                                         const char *cname_sign,
00213                                         unsigned int lifetime);
00214 
00215 static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
00216                                     crypto_pk_t *identity,
00217                                     unsigned int key_lifetime,
00218                                     int is_client);
00219 static tor_tls_context_t *tor_tls_context_new(crypto_pk_t *identity,
00220                                               unsigned int key_lifetime,
00221                                               int is_client);
00222 static int check_cert_lifetime_internal(int severity, const X509 *cert,
00223                                    int past_tolerance, int future_tolerance);
00224 
00229 static tor_tls_context_t *server_tls_context = NULL;
00230 static tor_tls_context_t *client_tls_context = NULL;
00234 static int tls_library_is_initialized = 0;
00235 
00236 /* Module-internal error codes. */
00237 #define _TOR_TLS_SYSCALL    (_MIN_TOR_TLS_ERROR_VAL - 2)
00238 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
00239 
00242 void
00243 tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
00244 {
00245   const char *ssl_state;
00246   const char *tortls_state;
00247 
00248   if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
00249     strlcpy(buf, "(No SSL object)", sz);
00250     return;
00251   }
00252 
00253   ssl_state = SSL_state_string_long(tls->ssl);
00254   switch (tls->state) {
00255 #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
00256     CASE(HANDSHAKE);
00257     CASE(OPEN);
00258     CASE(GOTCLOSE);
00259     CASE(SENTCLOSE);
00260     CASE(CLOSED);
00261     CASE(RENEGOTIATE);
00262 #undef CASE
00263   case TOR_TLS_ST_BUFFEREVENT:
00264     tortls_state = "";
00265     break;
00266   default:
00267     tortls_state = " in unknown TLS state";
00268     break;
00269   }
00270 
00271   tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
00272 }
00273 
00277 void
00278 tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
00279                   int severity, int domain, const char *doing)
00280 {
00281   const char *state = NULL, *addr;
00282   const char *msg, *lib, *func;
00283 
00284   state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
00285 
00286   addr = tls ? tls->address : NULL;
00287 
00288   /* Some errors are known-benign, meaning they are the fault of the other
00289    * side of the connection. The caller doesn't know this, so override the
00290    * priority for those cases. */
00291   switch (ERR_GET_REASON(err)) {
00292     case SSL_R_HTTP_REQUEST:
00293     case SSL_R_HTTPS_PROXY_REQUEST:
00294     case SSL_R_RECORD_LENGTH_MISMATCH:
00295     case SSL_R_RECORD_TOO_LARGE:
00296     case SSL_R_UNKNOWN_PROTOCOL:
00297     case SSL_R_UNSUPPORTED_PROTOCOL:
00298       severity = LOG_INFO;
00299       break;
00300     default:
00301       break;
00302   }
00303 
00304   msg = (const char*)ERR_reason_error_string(err);
00305   lib = (const char*)ERR_lib_error_string(err);
00306   func = (const char*)ERR_func_error_string(err);
00307   if (!msg) msg = "(null)";
00308   if (!lib) lib = "(null)";
00309   if (!func) func = "(null)";
00310   if (doing) {
00311     log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
00312         doing, addr?" with ":"", addr?addr:"",
00313         msg, lib, func, state);
00314   } else {
00315     log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
00316         addr?" with ":"", addr?addr:"",
00317         msg, lib, func, state);
00318   }
00319 }
00320 
00324 static void
00325 tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
00326 {
00327   unsigned long err;
00328 
00329   while ((err = ERR_get_error()) != 0) {
00330     tor_tls_log_one_error(tls, err, severity, domain, doing);
00331   }
00332 }
00333 
00336 static int
00337 tor_errno_to_tls_error(int e)
00338 {
00339 #if defined(_WIN32)
00340   switch (e) {
00341     case WSAECONNRESET: // most common
00342       return TOR_TLS_ERROR_CONNRESET;
00343     case WSAETIMEDOUT:
00344       return TOR_TLS_ERROR_TIMEOUT;
00345     case WSAENETUNREACH:
00346     case WSAEHOSTUNREACH:
00347       return TOR_TLS_ERROR_NO_ROUTE;
00348     case WSAECONNREFUSED:
00349       return TOR_TLS_ERROR_CONNREFUSED; // least common
00350     default:
00351       return TOR_TLS_ERROR_MISC;
00352   }
00353 #else
00354   switch (e) {
00355     case ECONNRESET: // most common
00356       return TOR_TLS_ERROR_CONNRESET;
00357     case ETIMEDOUT:
00358       return TOR_TLS_ERROR_TIMEOUT;
00359     case EHOSTUNREACH:
00360     case ENETUNREACH:
00361       return TOR_TLS_ERROR_NO_ROUTE;
00362     case ECONNREFUSED:
00363       return TOR_TLS_ERROR_CONNREFUSED; // least common
00364     default:
00365       return TOR_TLS_ERROR_MISC;
00366   }
00367 #endif
00368 }
00369 
00371 const char *
00372 tor_tls_err_to_string(int err)
00373 {
00374   if (err >= 0)
00375     return "[Not an error.]";
00376   switch (err) {
00377     case TOR_TLS_ERROR_MISC: return "misc error";
00378     case TOR_TLS_ERROR_IO: return "unexpected close";
00379     case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
00380     case TOR_TLS_ERROR_CONNRESET: return "connection reset";
00381     case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
00382     case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
00383     case TOR_TLS_CLOSE: return "closed";
00384     case TOR_TLS_WANTREAD: return "want to read";
00385     case TOR_TLS_WANTWRITE: return "want to write";
00386     default: return "(unknown error code)";
00387   }
00388 }
00389 
00390 #define CATCH_SYSCALL 1
00391 #define CATCH_ZERO    2
00392 
00403 static int
00404 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
00405                   const char *doing, int severity, int domain)
00406 {
00407   int err = SSL_get_error(tls->ssl, r);
00408   int tor_error = TOR_TLS_ERROR_MISC;
00409   switch (err) {
00410     case SSL_ERROR_NONE:
00411       return TOR_TLS_DONE;
00412     case SSL_ERROR_WANT_READ:
00413       return TOR_TLS_WANTREAD;
00414     case SSL_ERROR_WANT_WRITE:
00415       return TOR_TLS_WANTWRITE;
00416     case SSL_ERROR_SYSCALL:
00417       if (extra&CATCH_SYSCALL)
00418         return _TOR_TLS_SYSCALL;
00419       if (r == 0) {
00420         log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
00421             doing, SSL_state_string_long(tls->ssl));
00422         tor_error = TOR_TLS_ERROR_IO;
00423       } else {
00424         int e = tor_socket_errno(tls->socket);
00425         log(severity, LD_NET,
00426             "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
00427             doing, e, tor_socket_strerror(e),
00428             SSL_state_string_long(tls->ssl));
00429         tor_error = tor_errno_to_tls_error(e);
00430       }
00431       tls_log_errors(tls, severity, domain, doing);
00432       return tor_error;
00433     case SSL_ERROR_ZERO_RETURN:
00434       if (extra&CATCH_ZERO)
00435         return _TOR_TLS_ZERORETURN;
00436       log(severity, LD_NET, "TLS connection closed while %s in state %s",
00437           doing, SSL_state_string_long(tls->ssl));
00438       tls_log_errors(tls, severity, domain, doing);
00439       return TOR_TLS_CLOSE;
00440     default:
00441       tls_log_errors(tls, severity, domain, doing);
00442       return TOR_TLS_ERROR_MISC;
00443   }
00444 }
00445 
00448 static void
00449 tor_tls_init(void)
00450 {
00451   if (!tls_library_is_initialized) {
00452     long version;
00453     SSL_library_init();
00454     SSL_load_error_strings();
00455 
00456     version = SSLeay();
00457 
00458     /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
00459      * here, but without thinking too hard about it: it turns out that the
00460      * flag in question needed to be set at the last minute, and that it
00461      * conflicted with an existing flag number that had already been added
00462      * in the OpenSSL 1.0.0 betas.  OpenSSL 0.9.8m thoughtfully replaced
00463      * the flag with an option and (it seems) broke anything that used
00464      * SSL3_FLAGS_* for the purpose.  So we need to know how to do both,
00465      * and we mustn't use the SSL3_FLAGS option with anything besides
00466      * OpenSSL 0.9.8l.
00467      *
00468      * No, we can't just set flag 0x0010 everywhere.  It breaks Tor with
00469      * OpenSSL 1.0.0beta3 and later.  On the other hand, we might be able to
00470      * set option 0x00040000L everywhere.
00471      *
00472      * No, we can't simply detect whether the flag or the option is present
00473      * in the headers at build-time: some vendors (notably Apple) like to
00474      * leave their headers out of sync with their libraries.
00475      *
00476      * Yes, it _is_ almost as if the OpenSSL developers decided that no
00477      * program should be allowed to use renegotiation unless it first passed
00478      * a test of intelligence and determination.
00479      */
00480     if (version > OPENSSL_V(0,9,8,'k') && version <= OPENSSL_V(0,9,8,'l')) {
00481       log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l, but "
00482                  "some vendors have backported renegotiation code from "
00483                  "0.9.8m without updating the version number. "
00484                  "I will try SSL3_FLAGS and SSL_OP to enable renegotation.",
00485                  SSLeay_version(SSLEAY_VERSION));
00486       use_unsafe_renegotiation_flag = 1;
00487       use_unsafe_renegotiation_op = 1;
00488     } else if (version > OPENSSL_V(0,9,8,'l')) {
00489       log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
00490                  "I will try SSL_OP to enable renegotiation",
00491                  SSLeay_version(SSLEAY_VERSION));
00492       use_unsafe_renegotiation_op = 1;
00493     } else if (version <= OPENSSL_V(0,9,8,'k')) {
00494       log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
00495                  "0.9.8l, but some vendors have backported 0.9.8l's "
00496                  "renegotiation code to earlier versions, and some have "
00497                  "backported the code from 0.9.8m or 0.9.8n.  I'll set both "
00498                  "SSL3_FLAGS and SSL_OP just to be safe.",
00499                  SSLeay_version(SSLEAY_VERSION), version);
00500       use_unsafe_renegotiation_flag = 1;
00501       use_unsafe_renegotiation_op = 1;
00502     } else {
00503       /* this is dead code, yes? */
00504       log_info(LD_GENERAL, "OpenSSL %s has version %lx",
00505                SSLeay_version(SSLEAY_VERSION), version);
00506     }
00507 
00508     tor_tls_allocate_tor_tls_object_ex_data_index();
00509 
00510     tls_library_is_initialized = 1;
00511   }
00512 }
00513 
00515 void
00516 tor_tls_free_all(void)
00517 {
00518   if (server_tls_context) {
00519     tor_tls_context_t *ctx = server_tls_context;
00520     server_tls_context = NULL;
00521     tor_tls_context_decref(ctx);
00522   }
00523   if (client_tls_context) {
00524     tor_tls_context_t *ctx = client_tls_context;
00525     client_tls_context = NULL;
00526     tor_tls_context_decref(ctx);
00527   }
00528 #ifdef V2_HANDSHAKE_CLIENT
00529   if (CLIENT_CIPHER_DUMMIES)
00530     tor_free(CLIENT_CIPHER_DUMMIES);
00531   if (CLIENT_CIPHER_STACK)
00532     sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
00533 #endif
00534 }
00535 
00540 static int
00541 always_accept_verify_cb(int preverify_ok,
00542                         X509_STORE_CTX *x509_ctx)
00543 {
00544   (void) preverify_ok;
00545   (void) x509_ctx;
00546   return 1;
00547 }
00548 
00550 static X509_NAME *
00551 tor_x509_name_new(const char *cname)
00552 {
00553   int nid;
00554   X509_NAME *name;
00555   if (!(name = X509_NAME_new()))
00556     return NULL;
00557   if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
00558   if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
00559                                    (unsigned char*)cname, -1, -1, 0)))
00560     goto error;
00561   return name;
00562  error:
00563   X509_NAME_free(name);
00564   return NULL;
00565 }
00566 
00574 static X509 *
00575 tor_tls_create_certificate(crypto_pk_t *rsa,
00576                            crypto_pk_t *rsa_sign,
00577                            const char *cname,
00578                            const char *cname_sign,
00579                            unsigned int cert_lifetime)
00580 {
00581   /* OpenSSL generates self-signed certificates with random 64-bit serial
00582    * numbers, so let's do that too. */
00583 #define SERIAL_NUMBER_SIZE 8
00584 
00585   time_t start_time, end_time;
00586   BIGNUM *serial_number = NULL;
00587   unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
00588   EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
00589   X509 *x509 = NULL;
00590   X509_NAME *name = NULL, *name_issuer=NULL;
00591 
00592   tor_tls_init();
00593 
00594   start_time = time(NULL);
00595 
00596   tor_assert(rsa);
00597   tor_assert(cname);
00598   tor_assert(rsa_sign);
00599   tor_assert(cname_sign);
00600   if (!(sign_pkey = _crypto_pk_get_evp_pkey(rsa_sign,1)))
00601     goto error;
00602   if (!(pkey = _crypto_pk_get_evp_pkey(rsa,0)))
00603     goto error;
00604   if (!(x509 = X509_new()))
00605     goto error;
00606   if (!(X509_set_version(x509, 2)))
00607     goto error;
00608 
00609   { /* our serial number is 8 random bytes. */
00610     if (crypto_rand((char *)serial_tmp, sizeof(serial_tmp)) < 0)
00611       goto error;
00612     if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
00613       goto error;
00614     if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
00615       goto error;
00616   }
00617 
00618   if (!(name = tor_x509_name_new(cname)))
00619     goto error;
00620   if (!(X509_set_subject_name(x509, name)))
00621     goto error;
00622   if (!(name_issuer = tor_x509_name_new(cname_sign)))
00623     goto error;
00624   if (!(X509_set_issuer_name(x509, name_issuer)))
00625     goto error;
00626 
00627   if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
00628     goto error;
00629   end_time = start_time + cert_lifetime;
00630   if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
00631     goto error;
00632   if (!X509_set_pubkey(x509, pkey))
00633     goto error;
00634   if (!X509_sign(x509, sign_pkey, EVP_sha1()))
00635     goto error;
00636 
00637   goto done;
00638  error:
00639   if (x509) {
00640     X509_free(x509);
00641     x509 = NULL;
00642   }
00643  done:
00644   tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
00645   if (sign_pkey)
00646     EVP_PKEY_free(sign_pkey);
00647   if (pkey)
00648     EVP_PKEY_free(pkey);
00649   if (serial_number)
00650     BN_free(serial_number);
00651   if (name)
00652     X509_NAME_free(name);
00653   if (name_issuer)
00654     X509_NAME_free(name_issuer);
00655   return x509;
00656 
00657 #undef SERIAL_NUMBER_SIZE
00658 }
00659 
00661 #define SERVER_CIPHER_LIST                         \
00662   (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"           \
00663    TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"           \
00664    SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
00665 /* Note: to set up your own private testing network with link crypto
00666  * disabled, set your Tors' cipher list to
00667  * (SSL3_TXT_RSA_NULL_SHA).  If you do this, you won't be able to communicate
00668  * with any of the "real" Tors, though. */
00669 
00670 #ifdef V2_HANDSHAKE_CLIENT
00671 #define CIPHER(id, name) name ":"
00672 #define XCIPHER(id, name)
00673 
00675 static const char CLIENT_CIPHER_LIST[] =
00676 #include "./ciphers.inc"
00677   /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
00678    * of any cipher we say. */
00679   "!SSLv2"
00680   ;
00681 #undef CIPHER
00682 #undef XCIPHER
00683 
00685 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
00688 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
00689 #define CIPHER(id, name) { id, name },
00690 #define XCIPHER(id, name) { id, #name },
00691 #include "./ciphers.inc"
00692 #undef CIPHER
00693 #undef XCIPHER
00694 };
00695 
00697 static const int N_CLIENT_CIPHERS =
00698   sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
00699 #endif
00700 
00701 #ifndef V2_HANDSHAKE_CLIENT
00702 #undef CLIENT_CIPHER_LIST
00703 #define CLIENT_CIPHER_LIST  (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"      \
00704                              SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
00705 #endif
00706 
00708 void
00709 tor_cert_free(tor_cert_t *cert)
00710 {
00711   if (! cert)
00712     return;
00713   if (cert->cert)
00714     X509_free(cert->cert);
00715   tor_free(cert->encoded);
00716   memset(cert, 0x03, sizeof(*cert));
00717   tor_free(cert);
00718 }
00719 
00725 static tor_cert_t *
00726 tor_cert_new(X509 *x509_cert)
00727 {
00728   tor_cert_t *cert;
00729   EVP_PKEY *pkey;
00730   RSA *rsa;
00731   int length, length2;
00732   unsigned char *cp;
00733 
00734   if (!x509_cert)
00735     return NULL;
00736 
00737   length = i2d_X509(x509_cert, NULL);
00738   cert = tor_malloc_zero(sizeof(tor_cert_t));
00739   if (length <= 0) {
00740     tor_free(cert);
00741     log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
00742     X509_free(x509_cert);
00743     return NULL;
00744   }
00745   cert->encoded_len = (size_t) length;
00746   cp = cert->encoded = tor_malloc(length);
00747   length2 = i2d_X509(x509_cert, &cp);
00748   tor_assert(length2 == length);
00749 
00750   cert->cert = x509_cert;
00751 
00752   crypto_digest_all(&cert->cert_digests,
00753                     (char*)cert->encoded, cert->encoded_len);
00754 
00755   if ((pkey = X509_get_pubkey(x509_cert)) &&
00756       (rsa = EVP_PKEY_get1_RSA(pkey))) {
00757     crypto_pk_t *pk = _crypto_new_pk_from_rsa(rsa);
00758     crypto_pk_get_all_digests(pk, &cert->pkey_digests);
00759     cert->pkey_digests_set = 1;
00760     crypto_pk_free(pk);
00761     EVP_PKEY_free(pkey);
00762   }
00763 
00764   return cert;
00765 }
00766 
00770 tor_cert_t *
00771 tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
00772 {
00773   X509 *x509;
00774   const unsigned char *cp = (const unsigned char *)certificate;
00775   tor_cert_t *newcert;
00776   tor_assert(certificate);
00777 
00778   if (certificate_len > INT_MAX)
00779     return NULL;
00780 
00781 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
00782   /* This ifdef suppresses a type warning.  Take out this case once everybody
00783    * is using OpenSSL 0.9.8 or later. */
00784   x509 = d2i_X509(NULL, (unsigned char**)&cp, (int)certificate_len);
00785 #else
00786   x509 = d2i_X509(NULL, &cp, (int)certificate_len);
00787 #endif
00788   if (!x509)
00789     return NULL; /* Couldn't decode */
00790   if (cp - certificate != (int)certificate_len) {
00791     X509_free(x509);
00792     return NULL; /* Didn't use all the bytes */
00793   }
00794   newcert = tor_cert_new(x509);
00795   if (!newcert) {
00796     return NULL;
00797   }
00798   if (newcert->encoded_len != certificate_len ||
00799       fast_memneq(newcert->encoded, certificate, certificate_len)) {
00800     /* Cert wasn't in DER */
00801     tor_cert_free(newcert);
00802     return NULL;
00803   }
00804   return newcert;
00805 }
00806 
00809 void
00810 tor_cert_get_der(const tor_cert_t *cert,
00811                  const uint8_t **encoded_out, size_t *size_out)
00812 {
00813   tor_assert(cert);
00814   tor_assert(encoded_out);
00815   tor_assert(size_out);
00816   *encoded_out = cert->encoded;
00817   *size_out = cert->encoded_len;
00818 }
00819 
00822 const digests_t *
00823 tor_cert_get_id_digests(const tor_cert_t *cert)
00824 {
00825   if (cert->pkey_digests_set)
00826     return &cert->pkey_digests;
00827   else
00828     return NULL;
00829 }
00830 
00832 const digests_t *
00833 tor_cert_get_cert_digests(const tor_cert_t *cert)
00834 {
00835   return &cert->cert_digests;
00836 }
00837 
00840 static void
00841 tor_tls_context_decref(tor_tls_context_t *ctx)
00842 {
00843   tor_assert(ctx);
00844   if (--ctx->refcnt == 0) {
00845     SSL_CTX_free(ctx->ctx);
00846     tor_cert_free(ctx->my_link_cert);
00847     tor_cert_free(ctx->my_id_cert);
00848     tor_cert_free(ctx->my_auth_cert);
00849     crypto_pk_free(ctx->link_key);
00850     crypto_pk_free(ctx->auth_key);
00851     tor_free(ctx);
00852   }
00853 }
00854 
00860 int
00861 tor_tls_get_my_certs(int server,
00862                      const tor_cert_t **link_cert_out,
00863                      const tor_cert_t **id_cert_out)
00864 {
00865   tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
00866   if (! ctx)
00867     return -1;
00868   if (link_cert_out)
00869     *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
00870   if (id_cert_out)
00871     *id_cert_out = ctx->my_id_cert;
00872   return 0;
00873 }
00874 
00879 crypto_pk_t *
00880 tor_tls_get_my_client_auth_key(void)
00881 {
00882   if (! client_tls_context)
00883     return NULL;
00884   return client_tls_context->auth_key;
00885 }
00886 
00891 crypto_pk_t *
00892 tor_tls_cert_get_key(tor_cert_t *cert)
00893 {
00894   crypto_pk_t *result = NULL;
00895   EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
00896   RSA *rsa;
00897   if (!pkey)
00898     return NULL;
00899   rsa = EVP_PKEY_get1_RSA(pkey);
00900   if (!rsa) {
00901     EVP_PKEY_free(pkey);
00902     return NULL;
00903   }
00904   result = _crypto_new_pk_from_rsa(rsa);
00905   EVP_PKEY_free(pkey);
00906   return result;
00907 }
00908 
00910 static int
00911 pkey_eq(EVP_PKEY *a, EVP_PKEY *b)
00912 {
00913   /* We'd like to do this, but openssl 0.9.7 doesn't have it:
00914      return EVP_PKEY_cmp(a,b) == 1;
00915   */
00916   unsigned char *a_enc=NULL, *b_enc=NULL, *a_ptr, *b_ptr;
00917   int a_len1, b_len1, a_len2, b_len2, result;
00918   a_len1 = i2d_PublicKey(a, NULL);
00919   b_len1 = i2d_PublicKey(b, NULL);
00920   if (a_len1 != b_len1)
00921     return 0;
00922   a_ptr = a_enc = tor_malloc(a_len1);
00923   b_ptr = b_enc = tor_malloc(b_len1);
00924   a_len2 = i2d_PublicKey(a, &a_ptr);
00925   b_len2 = i2d_PublicKey(b, &b_ptr);
00926   tor_assert(a_len2 == a_len1);
00927   tor_assert(b_len2 == b_len1);
00928   result = tor_memeq(a_enc, b_enc, a_len1);
00929   tor_free(a_enc);
00930   tor_free(b_enc);
00931   return result;
00932 }
00933 
00937 int
00938 tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
00939 {
00940   X509 *peercert = SSL_get_peer_certificate(tls->ssl);
00941   EVP_PKEY *link_key = NULL, *cert_key = NULL;
00942   int result;
00943 
00944   if (!peercert)
00945     return 0;
00946   link_key = X509_get_pubkey(peercert);
00947   cert_key = X509_get_pubkey(cert->cert);
00948 
00949   result = link_key && cert_key && pkey_eq(cert_key, link_key);
00950 
00951   X509_free(peercert);
00952   if (link_key)
00953     EVP_PKEY_free(link_key);
00954   if (cert_key)
00955     EVP_PKEY_free(cert_key);
00956 
00957   return result;
00958 }
00959 
00965 int
00966 tor_tls_cert_is_valid(int severity,
00967                       const tor_cert_t *cert,
00968                       const tor_cert_t *signing_cert,
00969                       int check_rsa_1024)
00970 {
00971   EVP_PKEY *cert_key;
00972   EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
00973   int r, key_ok = 0;
00974   if (!signing_key)
00975     return 0;
00976   r = X509_verify(cert->cert, signing_key);
00977   EVP_PKEY_free(signing_key);
00978   if (r <= 0)
00979     return 0;
00980 
00981   /* okay, the signature checked out right.  Now let's check the check the
00982    * lifetime. */
00983   if (check_cert_lifetime_internal(severity, cert->cert,
00984                                    48*60*60, 30*24*60*60) < 0)
00985     return 0;
00986 
00987   cert_key = X509_get_pubkey(cert->cert);
00988   if (check_rsa_1024 && cert_key) {
00989     RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
00990     if (rsa && BN_num_bits(rsa->n) == 1024)
00991       key_ok = 1;
00992     if (rsa)
00993       RSA_free(rsa);
00994   } else if (cert_key) {
00995     int min_bits = 1024;
00996 #ifdef EVP_PKEY_EC
00997     if (EVP_PKEY_type(cert_key->type) == EVP_PKEY_EC)
00998       min_bits = 128;
00999 #endif
01000     if (EVP_PKEY_bits(cert_key) >= min_bits)
01001       key_ok = 1;
01002   }
01003   EVP_PKEY_free(cert_key);
01004   if (!key_ok)
01005     return 0;
01006 
01007   /* XXXX compare DNs or anything? */
01008 
01009   return 1;
01010 }
01011 
01013 static void
01014 tor_tls_context_incref(tor_tls_context_t *ctx)
01015 {
01016   ++ctx->refcnt;
01017 }
01018 
01025 int
01026 tor_tls_context_init(int is_public_server,
01027                      crypto_pk_t *client_identity,
01028                      crypto_pk_t *server_identity,
01029                      unsigned int key_lifetime)
01030 {
01031   int rv1 = 0;
01032   int rv2 = 0;
01033 
01034   if (is_public_server) {
01035     tor_tls_context_t *new_ctx;
01036     tor_tls_context_t *old_ctx;
01037 
01038     tor_assert(server_identity != NULL);
01039 
01040     rv1 = tor_tls_context_init_one(&server_tls_context,
01041                                    server_identity,
01042                                    key_lifetime, 0);
01043 
01044     if (rv1 >= 0) {
01045       new_ctx = server_tls_context;
01046       tor_tls_context_incref(new_ctx);
01047       old_ctx = client_tls_context;
01048       client_tls_context = new_ctx;
01049 
01050       if (old_ctx != NULL) {
01051         tor_tls_context_decref(old_ctx);
01052       }
01053     }
01054   } else {
01055     if (server_identity != NULL) {
01056       rv1 = tor_tls_context_init_one(&server_tls_context,
01057                                      server_identity,
01058                                      key_lifetime,
01059                                      0);
01060     } else {
01061       tor_tls_context_t *old_ctx = server_tls_context;
01062       server_tls_context = NULL;
01063 
01064       if (old_ctx != NULL) {
01065         tor_tls_context_decref(old_ctx);
01066       }
01067     }
01068 
01069     rv2 = tor_tls_context_init_one(&client_tls_context,
01070                                    client_identity,
01071                                    key_lifetime,
01072                                    1);
01073   }
01074 
01075   return MIN(rv1, rv2);
01076 }
01077 
01084 static int
01085 tor_tls_context_init_one(tor_tls_context_t **ppcontext,
01086                          crypto_pk_t *identity,
01087                          unsigned int key_lifetime,
01088                          int is_client)
01089 {
01090   tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
01091                                                    key_lifetime,
01092                                                    is_client);
01093   tor_tls_context_t *old_ctx = *ppcontext;
01094 
01095   if (new_ctx != NULL) {
01096     *ppcontext = new_ctx;
01097 
01098     /* Free the old context if one existed. */
01099     if (old_ctx != NULL) {
01100       /* This is safe even if there are open connections: we reference-
01101        * count tor_tls_context_t objects. */
01102       tor_tls_context_decref(old_ctx);
01103     }
01104   }
01105 
01106   return ((new_ctx != NULL) ? 0 : -1);
01107 }
01108 
01113 static tor_tls_context_t *
01114 tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
01115                     int is_client)
01116 {
01117   crypto_pk_t *rsa = NULL, *rsa_auth = NULL;
01118   EVP_PKEY *pkey = NULL;
01119   tor_tls_context_t *result = NULL;
01120   X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
01121   char *nickname = NULL, *nn2 = NULL;
01122 
01123   tor_tls_init();
01124   nickname = crypto_random_hostname(8, 20, "www.", ".net");
01125 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
01126   nn2 = crypto_random_hostname(8, 20, "www.", ".net");
01127 #else
01128   nn2 = crypto_random_hostname(8, 20, "www.", ".com");
01129 #endif
01130 
01131   /* Generate short-term RSA key for use with TLS. */
01132   if (!(rsa = crypto_pk_new()))
01133     goto error;
01134   if (crypto_pk_generate_key(rsa)<0)
01135     goto error;
01136   if (!is_client) {
01137     /* Generate short-term RSA key for use in the in-protocol ("v3")
01138      * authentication handshake. */
01139     if (!(rsa_auth = crypto_pk_new()))
01140       goto error;
01141     if (crypto_pk_generate_key(rsa_auth)<0)
01142       goto error;
01143     /* Create a link certificate signed by identity key. */
01144     cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
01145                                       key_lifetime);
01146     /* Create self-signed certificate for identity key. */
01147     idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
01148                                         IDENTITY_CERT_LIFETIME);
01149     /* Create an authentication certificate signed by identity key. */
01150     authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
01151                                           key_lifetime);
01152     if (!cert || !idcert || !authcert) {
01153       log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
01154       goto error;
01155     }
01156   }
01157 
01158   result = tor_malloc_zero(sizeof(tor_tls_context_t));
01159   result->refcnt = 1;
01160   if (!is_client) {
01161     result->my_link_cert = tor_cert_new(X509_dup(cert));
01162     result->my_id_cert = tor_cert_new(X509_dup(idcert));
01163     result->my_auth_cert = tor_cert_new(X509_dup(authcert));
01164     if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
01165       goto error;
01166     result->link_key = crypto_pk_dup_key(rsa);
01167     result->auth_key = crypto_pk_dup_key(rsa_auth);
01168   }
01169 
01170 #if 0
01171   /* Tell OpenSSL to only use TLS1.  This may have subtly different results
01172    * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
01173    * investigation before we consider adjusting it. It should be compatible
01174    * with existing Tors. */
01175   if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
01176     goto error;
01177 #endif
01178 
01179   /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
01180   if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
01181     goto error;
01182   SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
01183 
01184   /* Disable TLS1.1 and TLS1.2 if they exist.  We need to do this to
01185    * workaround a bug present in all OpenSSL 1.0.1 versions (as of 1
01186    * June 2012), wherein renegotiating while using one of these TLS
01187    * protocols will cause the client to send a TLS 1.0 ServerHello
01188    * rather than a ServerHello written with the appropriate protocol
01189    * version.  Once some version of OpenSSL does TLS1.1 and TLS1.2
01190    * renegotiation properly, we can turn them back on when built with
01191    * that version. */
01192 #ifdef SSL_OP_NO_TLSv1_2
01193   SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_2);
01194 #endif
01195 #ifdef SSL_OP_NO_TLSv1_1
01196   SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_1);
01197 #endif
01198 
01199   if (
01200 #ifdef DISABLE_SSL3_HANDSHAKE
01201       1 ||
01202 #endif
01203       SSLeay()  <  OPENSSL_V(0,9,8,'s') ||
01204       (SSLeay() >= OPENSSL_V_SERIES(0,9,9) &&
01205        SSLeay() <  OPENSSL_V(1,0,0,'f'))) {
01206     /* And not SSL3 if it's subject to CVE-2011-4576. */
01207     log_info(LD_NET, "Disabling SSLv3 because this OpenSSL version "
01208              "might otherwise be vulnerable to CVE-2011-4576 "
01209              "(compile-time version %08lx (%s); "
01210              "runtime version %08lx (%s))",
01211              (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
01212              (unsigned long)SSLeay(), SSLeay_version(SSLEAY_VERSION));
01213     SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
01214   }
01215 
01216   SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
01217 
01218 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
01219   SSL_CTX_set_options(result->ctx,
01220                       SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
01221 #endif
01222   /* Yes, we know what we are doing here.  No, we do not treat a renegotiation
01223    * as authenticating any earlier-received data.
01224    */
01225   if (use_unsafe_renegotiation_op) {
01226     SSL_CTX_set_options(result->ctx,
01227                         SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
01228   }
01229   /* Don't actually allow compression; it uses ram and time, but the data
01230    * we transmit is all encrypted anyway. */
01231   if (result->ctx->comp_methods)
01232     result->ctx->comp_methods = NULL;
01233 #ifdef SSL_MODE_RELEASE_BUFFERS
01234   SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
01235 #endif
01236   if (! is_client) {
01237     if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
01238       goto error;
01239     X509_free(cert); /* We just added a reference to cert. */
01240     cert=NULL;
01241     if (idcert) {
01242       X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
01243       tor_assert(s);
01244       X509_STORE_add_cert(s, idcert);
01245       X509_free(idcert); /* The context now owns the reference to idcert */
01246       idcert = NULL;
01247     }
01248   }
01249   SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
01250   if (!is_client) {
01251     tor_assert(rsa);
01252     if (!(pkey = _crypto_pk_get_evp_pkey(rsa,1)))
01253       goto error;
01254     if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
01255       goto error;
01256     EVP_PKEY_free(pkey);
01257     pkey = NULL;
01258     if (!SSL_CTX_check_private_key(result->ctx))
01259       goto error;
01260   }
01261   {
01262     crypto_dh_t *dh = crypto_dh_new(DH_TYPE_TLS);
01263     tor_assert(dh);
01264     SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_get_dh(dh));
01265     crypto_dh_free(dh);
01266   }
01267   SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
01268                      always_accept_verify_cb);
01269   /* let us realloc bufs that we're writing from */
01270   SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
01271 
01272   if (rsa)
01273     crypto_pk_free(rsa);
01274   if (rsa_auth)
01275     crypto_pk_free(rsa_auth);
01276   X509_free(authcert);
01277   tor_free(nickname);
01278   tor_free(nn2);
01279   return result;
01280 
01281  error:
01282   tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
01283   tor_free(nickname);
01284   tor_free(nn2);
01285   if (pkey)
01286     EVP_PKEY_free(pkey);
01287   if (rsa)
01288     crypto_pk_free(rsa);
01289   if (rsa_auth)
01290     crypto_pk_free(rsa_auth);
01291   if (result)
01292     tor_tls_context_decref(result);
01293   if (cert)
01294     X509_free(cert);
01295   if (idcert)
01296     X509_free(idcert);
01297   if (authcert)
01298     X509_free(authcert);
01299   return NULL;
01300 }
01301 
01302 #ifdef V2_HANDSHAKE_SERVER
01303 
01306 static int
01307 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
01308 {
01309   int i;
01310   SSL_SESSION *session;
01311   /* If we reached this point, we just got a client hello.  See if there is
01312    * a cipher list. */
01313   if (!(session = SSL_get_session((SSL *)ssl))) {
01314     log_info(LD_NET, "No session on TLS?");
01315     return 0;
01316   }
01317   if (!session->ciphers) {
01318     log_info(LD_NET, "No ciphers on session");
01319     return 0;
01320   }
01321   /* Now we need to see if there are any ciphers whose presence means we're
01322    * dealing with an updated Tor. */
01323   for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
01324     SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
01325     const char *ciphername = SSL_CIPHER_get_name(cipher);
01326     if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
01327         strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
01328         strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
01329         strcmp(ciphername, "(NONE)")) {
01330       log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
01331       // return 1;
01332       goto dump_list;
01333     }
01334   }
01335   return 0;
01336  dump_list:
01337   {
01338     smartlist_t *elts = smartlist_new();
01339     char *s;
01340     for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
01341       SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
01342       const char *ciphername = SSL_CIPHER_get_name(cipher);
01343       smartlist_add(elts, (char*)ciphername);
01344     }
01345     s = smartlist_join_strings(elts, ":", 0, NULL);
01346     log_debug(LD_NET, "Got a non-version-1 cipher list from %s.  It is: '%s'",
01347               address, s);
01348     tor_free(s);
01349     smartlist_free(elts);
01350   }
01351   return 1;
01352 }
01353 
01355 static void
01356 tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
01357 {
01358   log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
01359             ssl, SSL_state_string_long(ssl), type, val);
01360 }
01361 
01368 static void
01369 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
01370 {
01371   tor_tls_t *tls;
01372   (void) val;
01373 
01374   tor_tls_debug_state_callback(ssl, type, val);
01375 
01376   if (type != SSL_CB_ACCEPT_LOOP)
01377     return;
01378   if ((ssl->state != SSL3_ST_SW_SRVR_HELLO_A) &&
01379       (ssl->state != SSL3_ST_SW_SRVR_HELLO_B))
01380     return;
01381 
01382   tls = tor_tls_get_by_ssl(ssl);
01383   if (tls) {
01384     /* Check whether we're watching for renegotiates.  If so, this is one! */
01385     if (tls->negotiated_callback)
01386       tls->got_renegotiate = 1;
01387     if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
01388       ++tls->server_handshake_count;
01389   } else {
01390     log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
01391     return;
01392   }
01393 
01394   /* Now check the cipher list. */
01395   if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
01396     if (tls->wasV2Handshake)
01397       return; /* We already turned this stuff off for the first handshake;
01398                * This is a renegotiation. */
01399 
01400     /* Yes, we're casting away the const from ssl.  This is very naughty of us.
01401      * Let's hope openssl doesn't notice! */
01402 
01403     /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
01404     SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
01405     /* Don't send a hello request. */
01406     SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
01407 
01408     if (tls) {
01409       tls->wasV2Handshake = 1;
01410 #ifdef USE_BUFFEREVENTS
01411       if (use_unsafe_renegotiation_flag)
01412         tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
01413 #endif
01414     } else {
01415       log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
01416     }
01417   }
01418 }
01419 #endif
01420 
01422 static void
01423 log_unsupported_ciphers(smartlist_t *unsupported)
01424 {
01425   char *joined;
01426 
01427   log_notice(LD_NET, "We weren't able to find support for all of the "
01428              "TLS ciphersuites that we wanted to advertise. This won't "
01429              "hurt security, but it might make your Tor (if run as a client) "
01430              "more easy for censors to block.");
01431 
01432   if (SSLeay() < 0x10000000L) {
01433     log_notice(LD_NET, "To correct this, use a more recent OpenSSL, "
01434                "built without disabling any secure ciphers or features.");
01435   } else {
01436     log_notice(LD_NET, "To correct this, use a version of OpenSSL "
01437                "built with none of its ciphers disabled.");
01438   }
01439 
01440   joined = smartlist_join_strings(unsupported, ":", 0, NULL);
01441   log_info(LD_NET, "The unsupported ciphers were: %s", joined);
01442   tor_free(joined);
01443 }
01444 
01455 static void
01456 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
01457 {
01458 #ifdef V2_HANDSHAKE_CLIENT
01459   if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
01460     /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
01461      * we want to use/advertise. */
01462     int i = 0, j = 0;
01463     smartlist_t *unsupported = smartlist_new();
01464 
01465     /* First, create a dummy SSL_CIPHER for every cipher. */
01466     CLIENT_CIPHER_DUMMIES =
01467       tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
01468     for (i=0; i < N_CLIENT_CIPHERS; ++i) {
01469       CLIENT_CIPHER_DUMMIES[i].valid = 1;
01470       /* The "3<<24" here signifies that the cipher is supposed to work with
01471        * SSL3 and TLS1. */
01472       CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
01473       CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
01474     }
01475 
01476     CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
01477     tor_assert(CLIENT_CIPHER_STACK);
01478 
01479     log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
01480     for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
01481       SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
01482       log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
01483     }
01484 
01485     /* Then copy as many ciphers as we can from the good list, inserting
01486      * dummies as needed. Let j be an index into list of ciphers we have
01487      * (*ciphers) and let i be an index into the ciphers we want
01488      * (CLIENT_INFO_CIPHER_LIST).  We are building a list of ciphers in
01489      * CLIENT_CIPHER_STACK.
01490      */
01491     for (i = j = 0; i < N_CLIENT_CIPHERS; ) {
01492       SSL_CIPHER *cipher = NULL;
01493       if (j < sk_SSL_CIPHER_num(*ciphers))
01494         cipher = sk_SSL_CIPHER_value(*ciphers, j);
01495       if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
01496         /* Skip over non-v3 ciphers entirely.  (This should no longer be
01497          * needed, thanks to saying !SSLv2 above.) */
01498         log_debug(LD_NET, "Skipping v%d cipher %s",
01499                   (int)((cipher->id>>24) & 0xff),
01500                   cipher->name);
01501         ++j;
01502       } else if (cipher &&
01503                  (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
01504         /* "cipher" is the cipher we expect. Put it on the list. */
01505         log_debug(LD_NET, "Found cipher %s", cipher->name);
01506         sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
01507         ++j;
01508         ++i;
01509       } else if (!strcmp(CLIENT_CIPHER_DUMMIES[i].name,
01510                          "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA")) {
01511         /* We found bogus cipher 0xfeff, which OpenSSL doesn't support and
01512          * never has.  For this one, we need a dummy. */
01513         log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
01514         sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
01515         ++i;
01516       } else {
01517         /* OpenSSL doesn't have this one. */
01518         log_debug(LD_NET, "Completely omitting unsupported cipher %s",
01519                   CLIENT_CIPHER_INFO_LIST[i].name);
01520         smartlist_add(unsupported, (char*) CLIENT_CIPHER_INFO_LIST[i].name);
01521         ++i;
01522       }
01523     }
01524 
01525     if (smartlist_len(unsupported))
01526       log_unsupported_ciphers(unsupported);
01527 
01528     smartlist_free(unsupported);
01529   }
01530 
01531   sk_SSL_CIPHER_free(*ciphers);
01532   *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
01533   tor_assert(*ciphers);
01534 
01535 #else
01536     (void)ciphers;
01537 #endif
01538 }
01539 
01543 tor_tls_t *
01544 tor_tls_new(int sock, int isServer)
01545 {
01546   BIO *bio = NULL;
01547   tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
01548   tor_tls_context_t *context = isServer ? server_tls_context :
01549     client_tls_context;
01550   result->magic = TOR_TLS_MAGIC;
01551 
01552   tor_assert(context); /* make sure somebody made it first */
01553   if (!(result->ssl = SSL_new(context->ctx))) {
01554     tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
01555     tor_free(result);
01556     return NULL;
01557   }
01558 
01559 #ifdef SSL_set_tlsext_host_name
01560   /* Browsers use the TLS hostname extension, so we should too. */
01561   if (!isServer) {
01562     char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
01563     SSL_set_tlsext_host_name(result->ssl, fake_hostname);
01564     tor_free(fake_hostname);
01565   }
01566 #endif
01567 
01568   if (!SSL_set_cipher_list(result->ssl,
01569                      isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
01570     tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
01571 #ifdef SSL_set_tlsext_host_name
01572     SSL_set_tlsext_host_name(result->ssl, NULL);
01573 #endif
01574     SSL_free(result->ssl);
01575     tor_free(result);
01576     return NULL;
01577   }
01578   if (!isServer)
01579     rectify_client_ciphers(&result->ssl->cipher_list);
01580   result->socket = sock;
01581   bio = BIO_new_socket(sock, BIO_NOCLOSE);
01582   if (! bio) {
01583     tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
01584 #ifdef SSL_set_tlsext_host_name
01585     SSL_set_tlsext_host_name(result->ssl, NULL);
01586 #endif
01587     SSL_free(result->ssl);
01588     tor_free(result);
01589     return NULL;
01590   }
01591   {
01592     int set_worked =
01593       SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
01594     if (!set_worked) {
01595       log_warn(LD_BUG,
01596                "Couldn't set the tls for an SSL*; connection will fail");
01597     }
01598   }
01599   SSL_set_bio(result->ssl, bio, bio);
01600   tor_tls_context_incref(context);
01601   result->context = context;
01602   result->state = TOR_TLS_ST_HANDSHAKE;
01603   result->isServer = isServer;
01604   result->wantwrite_n = 0;
01605   result->last_write_count = BIO_number_written(bio);
01606   result->last_read_count = BIO_number_read(bio);
01607   if (result->last_write_count || result->last_read_count) {
01608     log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
01609              result->last_read_count, result->last_write_count);
01610   }
01611 #ifdef V2_HANDSHAKE_SERVER
01612   if (isServer) {
01613     SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
01614   } else
01615 #endif
01616   {
01617     SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
01618   }
01619 
01620   /* Not expected to get called. */
01621   tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
01622   return result;
01623 }
01624 
01628 void
01629 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
01630 {
01631   tor_assert(tls);
01632   tor_free(tls->address);
01633   tls->address = tor_strdup(address);
01634 }
01635 
01640 void
01641 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
01642                                  void (*cb)(tor_tls_t *, void *arg),
01643                                  void *arg)
01644 {
01645   tls->negotiated_callback = cb;
01646   tls->callback_arg = arg;
01647   tls->got_renegotiate = 0;
01648 #ifdef V2_HANDSHAKE_SERVER
01649   if (cb) {
01650     SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
01651   } else {
01652     SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
01653   }
01654 #endif
01655 }
01656 
01660 void
01661 tor_tls_unblock_renegotiation(tor_tls_t *tls)
01662 {
01663   /* Yes, we know what we are doing here.  No, we do not treat a renegotiation
01664    * as authenticating any earlier-received data. */
01665   if (use_unsafe_renegotiation_flag) {
01666     tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
01667   }
01668   if (use_unsafe_renegotiation_op) {
01669     SSL_set_options(tls->ssl,
01670                     SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
01671   }
01672 }
01673 
01678 void
01679 tor_tls_block_renegotiation(tor_tls_t *tls)
01680 {
01681   tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
01682 }
01683 
01685 void
01686 tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
01687 {
01688   if (use_unsafe_renegotiation_flag) {
01689     tor_assert(0 != (tls->ssl->s3->flags &
01690                      SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
01691   }
01692   if (use_unsafe_renegotiation_op) {
01693     long options = SSL_get_options(tls->ssl);
01694     tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
01695   }
01696 }
01697 
01700 int
01701 tor_tls_is_server(tor_tls_t *tls)
01702 {
01703   tor_assert(tls);
01704   return tls->isServer;
01705 }
01706 
01710 void
01711 tor_tls_free(tor_tls_t *tls)
01712 {
01713   if (!tls)
01714     return;
01715   tor_assert(tls->ssl);
01716 #ifdef SSL_set_tlsext_host_name
01717   SSL_set_tlsext_host_name(tls->ssl, NULL);
01718 #endif
01719   SSL_free(tls->ssl);
01720   tls->ssl = NULL;
01721   tls->negotiated_callback = NULL;
01722   if (tls->context)
01723     tor_tls_context_decref(tls->context);
01724   tor_free(tls->address);
01725   tls->magic = 0x99999999;
01726   tor_free(tls);
01727 }
01728 
01734 int
01735 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
01736 {
01737   int r, err;
01738   tor_assert(tls);
01739   tor_assert(tls->ssl);
01740   tor_assert(tls->state == TOR_TLS_ST_OPEN);
01741   tor_assert(len<INT_MAX);
01742   r = SSL_read(tls->ssl, cp, (int)len);
01743   if (r > 0) {
01744 #ifdef V2_HANDSHAKE_SERVER
01745     if (tls->got_renegotiate) {
01746       /* Renegotiation happened! */
01747       log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
01748       if (tls->negotiated_callback)
01749         tls->negotiated_callback(tls, tls->callback_arg);
01750       tls->got_renegotiate = 0;
01751     }
01752 #endif
01753     return r;
01754   }
01755   err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
01756   if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
01757     log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
01758     tls->state = TOR_TLS_ST_CLOSED;
01759     return TOR_TLS_CLOSE;
01760   } else {
01761     tor_assert(err != TOR_TLS_DONE);
01762     log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
01763     return err;
01764   }
01765 }
01766 
01772 int
01773 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
01774 {
01775   int r, err;
01776   tor_assert(tls);
01777   tor_assert(tls->ssl);
01778   tor_assert(tls->state == TOR_TLS_ST_OPEN);
01779   tor_assert(n < INT_MAX);
01780   if (n == 0)
01781     return 0;
01782   if (tls->wantwrite_n) {
01783     /* if WANTWRITE last time, we must use the _same_ n as before */
01784     tor_assert(n >= tls->wantwrite_n);
01785     log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
01786               (int)n, (int)tls->wantwrite_n);
01787     n = tls->wantwrite_n;
01788     tls->wantwrite_n = 0;
01789   }
01790   r = SSL_write(tls->ssl, cp, (int)n);
01791   err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
01792   if (err == TOR_TLS_DONE) {
01793     return r;
01794   }
01795   if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
01796     tls->wantwrite_n = n;
01797   }
01798   return err;
01799 }
01800 
01805 int
01806 tor_tls_handshake(tor_tls_t *tls)
01807 {
01808   int r;
01809   int oldstate;
01810   tor_assert(tls);
01811   tor_assert(tls->ssl);
01812   tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
01813   check_no_tls_errors();
01814   oldstate = tls->ssl->state;
01815   if (tls->isServer) {
01816     log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
01817               SSL_state_string_long(tls->ssl));
01818     r = SSL_accept(tls->ssl);
01819   } else {
01820     log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
01821               SSL_state_string_long(tls->ssl));
01822     r = SSL_connect(tls->ssl);
01823   }
01824   if (oldstate != tls->ssl->state)
01825     log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
01826               tls, SSL_state_string_long(tls->ssl));
01827   /* We need to call this here and not earlier, since OpenSSL has a penchant
01828    * for clearing its flags when you say accept or connect. */
01829   tor_tls_unblock_renegotiation(tls);
01830   r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
01831   if (ERR_peek_error() != 0) {
01832     tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
01833                    "handshaking");
01834     return TOR_TLS_ERROR_MISC;
01835   }
01836   if (r == TOR_TLS_DONE) {
01837     tls->state = TOR_TLS_ST_OPEN;
01838     return tor_tls_finish_handshake(tls);
01839   }
01840   return r;
01841 }
01842 
01851 int
01852 tor_tls_finish_handshake(tor_tls_t *tls)
01853 {
01854   int r = TOR_TLS_DONE;
01855   if (tls->isServer) {
01856     SSL_set_info_callback(tls->ssl, NULL);
01857     SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
01858     /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
01859     tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
01860 #ifdef V2_HANDSHAKE_SERVER
01861     if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
01862       /* This check is redundant, but back when we did it in the callback,
01863        * we might have not been able to look up the tor_tls_t if the code
01864        * was buggy.  Fixing that. */
01865       if (!tls->wasV2Handshake) {
01866         log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
01867                  " get set. Fixing that.");
01868       }
01869       tls->wasV2Handshake = 1;
01870       log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
01871                 " for renegotiation.");
01872     } else {
01873       tls->wasV2Handshake = 0;
01874     }
01875 #endif
01876   } else {
01877 #ifdef V2_HANDSHAKE_CLIENT
01878     /* If we got no ID cert, we're a v2 handshake. */
01879     X509 *cert = SSL_get_peer_certificate(tls->ssl);
01880     STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
01881     int n_certs = sk_X509_num(chain);
01882     if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
01883       log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
01884                 "looks like a v1 handshake on %p", tls);
01885       tls->wasV2Handshake = 0;
01886     } else {
01887       log_debug(LD_HANDSHAKE,
01888                 "Server sent back a single certificate; looks like "
01889                 "a v2 handshake on %p.", tls);
01890       tls->wasV2Handshake = 1;
01891     }
01892     if (cert)
01893       X509_free(cert);
01894 #endif
01895     if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
01896       tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
01897       r = TOR_TLS_ERROR_MISC;
01898     }
01899   }
01900   return r;
01901 }
01902 
01903 #ifdef USE_BUFFEREVENTS
01904 
01906 int
01907 tor_tls_start_renegotiating(tor_tls_t *tls)
01908 {
01909   int r = SSL_renegotiate(tls->ssl);
01910   if (r <= 0) {
01911     return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
01912                              LD_HANDSHAKE);
01913   }
01914   return 0;
01915 }
01916 #endif
01917 
01922 int
01923 tor_tls_renegotiate(tor_tls_t *tls)
01924 {
01925   int r;
01926   tor_assert(tls);
01927   /* We could do server-initiated renegotiation too, but that would be tricky.
01928    * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
01929   tor_assert(!tls->isServer);
01930   if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
01931     int r = SSL_renegotiate(tls->ssl);
01932     if (r <= 0) {
01933       return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
01934                                LD_HANDSHAKE);
01935     }
01936     tls->state = TOR_TLS_ST_RENEGOTIATE;
01937   }
01938   r = SSL_do_handshake(tls->ssl);
01939   if (r == 1) {
01940     tls->state = TOR_TLS_ST_OPEN;
01941     return TOR_TLS_DONE;
01942   } else
01943     return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
01944                              LD_HANDSHAKE);
01945 }
01946 
01951 int
01952 tor_tls_shutdown(tor_tls_t *tls)
01953 {
01954   int r, err;
01955   char buf[128];
01956   tor_assert(tls);
01957   tor_assert(tls->ssl);
01958 
01959   while (1) {
01960     if (tls->state == TOR_TLS_ST_SENTCLOSE) {
01961       /* If we've already called shutdown once to send a close message,
01962        * we read until the other side has closed too.
01963        */
01964       do {
01965         r = SSL_read(tls->ssl, buf, 128);
01966       } while (r>0);
01967       err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
01968                               LOG_INFO, LD_NET);
01969       if (err == _TOR_TLS_ZERORETURN) {
01970         tls->state = TOR_TLS_ST_GOTCLOSE;
01971         /* fall through... */
01972       } else {
01973         return err;
01974       }
01975     }
01976 
01977     r = SSL_shutdown(tls->ssl);
01978     if (r == 1) {
01979       /* If shutdown returns 1, the connection is entirely closed. */
01980       tls->state = TOR_TLS_ST_CLOSED;
01981       return TOR_TLS_DONE;
01982     }
01983     err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
01984                             LOG_INFO, LD_NET);
01985     if (err == _TOR_TLS_SYSCALL) {
01986       /* The underlying TCP connection closed while we were shutting down. */
01987       tls->state = TOR_TLS_ST_CLOSED;
01988       return TOR_TLS_DONE;
01989     } else if (err == _TOR_TLS_ZERORETURN) {
01990       /* The TLS connection says that it sent a shutdown record, but
01991        * isn't done shutting down yet.  Make sure that this hasn't
01992        * happened before, then go back to the start of the function
01993        * and try to read.
01994        */
01995       if (tls->state == TOR_TLS_ST_GOTCLOSE ||
01996          tls->state == TOR_TLS_ST_SENTCLOSE) {
01997         log(LOG_WARN, LD_NET,
01998             "TLS returned \"half-closed\" value while already half-closed");
01999         return TOR_TLS_ERROR_MISC;
02000       }
02001       tls->state = TOR_TLS_ST_SENTCLOSE;
02002       /* fall through ... */
02003     } else {
02004       return err;
02005     }
02006   } /* end loop */
02007 }
02008 
02011 int
02012 tor_tls_peer_has_cert(tor_tls_t *tls)
02013 {
02014   X509 *cert;
02015   cert = SSL_get_peer_certificate(tls->ssl);
02016   tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
02017   if (!cert)
02018     return 0;
02019   X509_free(cert);
02020   return 1;
02021 }
02022 
02024 tor_cert_t *
02025 tor_tls_get_peer_cert(tor_tls_t *tls)
02026 {
02027   X509 *cert;
02028   cert = SSL_get_peer_certificate(tls->ssl);
02029   tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
02030   if (!cert)
02031     return NULL;
02032   return tor_cert_new(cert);
02033 }
02034 
02036 static void
02037 log_cert_lifetime(int severity, const X509 *cert, const char *problem)
02038 {
02039   BIO *bio = NULL;
02040   BUF_MEM *buf;
02041   char *s1=NULL, *s2=NULL;
02042   char mytime[33];
02043   time_t now = time(NULL);
02044   struct tm tm;
02045 
02046   if (problem)
02047     log(severity, LD_GENERAL,
02048         "Certificate %s. Either their clock is set wrong, or your clock "
02049         "is wrong.",
02050            problem);
02051 
02052   if (!(bio = BIO_new(BIO_s_mem()))) {
02053     log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
02054   }
02055   if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
02056     tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
02057     goto end;
02058   }
02059   BIO_get_mem_ptr(bio, &buf);
02060   s1 = tor_strndup(buf->data, buf->length);
02061 
02062   (void)BIO_reset(bio);
02063   if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
02064     tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
02065     goto end;
02066   }
02067   BIO_get_mem_ptr(bio, &buf);
02068   s2 = tor_strndup(buf->data, buf->length);
02069 
02070   strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
02071 
02072   log(severity, LD_GENERAL,
02073       "(certificate lifetime runs from %s through %s. Your time is %s.)",
02074       s1,s2,mytime);
02075 
02076  end:
02077   /* Not expected to get invoked */
02078   tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
02079   if (bio)
02080     BIO_free(bio);
02081   tor_free(s1);
02082   tor_free(s2);
02083 }
02084 
02092 static void
02093 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
02094                               X509 **cert_out, X509 **id_cert_out)
02095 {
02096   X509 *cert = NULL, *id_cert = NULL;
02097   STACK_OF(X509) *chain = NULL;
02098   int num_in_chain, i;
02099   *cert_out = *id_cert_out = NULL;
02100 
02101   if (!(cert = SSL_get_peer_certificate(tls->ssl)))
02102     return;
02103   *cert_out = cert;
02104   if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
02105     return;
02106   num_in_chain = sk_X509_num(chain);
02107   /* 1 means we're receiving (server-side), and it's just the id_cert.
02108    * 2 means we're connecting (client-side), and it's both the link
02109    * cert and the id_cert.
02110    */
02111   if (num_in_chain < 1) {
02112     log_fn(severity,LD_PROTOCOL,
02113            "Unexpected number of certificates in chain (%d)",
02114            num_in_chain);
02115     return;
02116   }
02117   for (i=0; i<num_in_chain; ++i) {
02118     id_cert = sk_X509_value(chain, i);
02119     if (X509_cmp(id_cert, cert) != 0)
02120       break;
02121   }
02122   *id_cert_out = id_cert;
02123 }
02124 
02130 int
02131 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
02132 {
02133   X509 *cert = NULL, *id_cert = NULL;
02134   EVP_PKEY *id_pkey = NULL;
02135   RSA *rsa;
02136   int r = -1;
02137 
02138   *identity_key = NULL;
02139 
02140   try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
02141   if (!cert)
02142     goto done;
02143   if (!id_cert) {
02144     log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
02145     goto done;
02146   }
02147   tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
02148 
02149   if (!(id_pkey = X509_get_pubkey(id_cert)) ||
02150       X509_verify(cert, id_pkey) <= 0) {
02151     log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
02152     tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
02153     goto done;
02154   }
02155 
02156   rsa = EVP_PKEY_get1_RSA(id_pkey);
02157   if (!rsa)
02158     goto done;
02159   *identity_key = _crypto_new_pk_from_rsa(rsa);
02160 
02161   r = 0;
02162 
02163  done:
02164   if (cert)
02165     X509_free(cert);
02166   if (id_pkey)
02167     EVP_PKEY_free(id_pkey);
02168 
02169   /* This should never get invoked, but let's make sure in case OpenSSL
02170    * acts unexpectedly. */
02171   tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
02172 
02173   return r;
02174 }
02175 
02182 int
02183 tor_tls_check_lifetime(int severity, tor_tls_t *tls,
02184                        int past_tolerance, int future_tolerance)
02185 {
02186   X509 *cert;
02187   int r = -1;
02188 
02189   if (!(cert = SSL_get_peer_certificate(tls->ssl)))
02190     goto done;
02191 
02192   if (check_cert_lifetime_internal(severity, cert,
02193                                    past_tolerance, future_tolerance) < 0)
02194     goto done;
02195 
02196   r = 0;
02197  done:
02198   if (cert)
02199     X509_free(cert);
02200   /* Not expected to get invoked */
02201   tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
02202 
02203   return r;
02204 }
02205 
02210 static int
02211 check_cert_lifetime_internal(int severity, const X509 *cert,
02212                              int past_tolerance, int future_tolerance)
02213 {
02214   time_t now, t;
02215 
02216   now = time(NULL);
02217 
02218   t = now + future_tolerance;
02219   if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
02220     log_cert_lifetime(severity, cert, "not yet valid");
02221     return -1;
02222   }
02223   t = now - past_tolerance;
02224   if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
02225     log_cert_lifetime(severity, cert, "already expired");
02226     return -1;
02227   }
02228 
02229   return 0;
02230 }
02231 
02234 int
02235 tor_tls_get_pending_bytes(tor_tls_t *tls)
02236 {
02237   tor_assert(tls);
02238   return SSL_pending(tls->ssl);
02239 }
02240 
02243 size_t
02244 tor_tls_get_forced_write_size(tor_tls_t *tls)
02245 {
02246   return tls->wantwrite_n;
02247 }
02248 
02252 void
02253 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
02254 {
02255   BIO *wbio, *tmpbio;
02256   unsigned long r, w;
02257   r = BIO_number_read(SSL_get_rbio(tls->ssl));
02258   /* We want the number of bytes actually for real written.  Unfortunately,
02259    * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
02260    * which makes the answer turn out wrong.  Let's cope with that.  Note
02261    * that this approach will fail if we ever replace tls->ssl's BIOs with
02262    * buffering bios for reasons of our own.  As an alternative, we could
02263    * save the original BIO for  tls->ssl in the tor_tls_t structure, but
02264    * that would be tempting fate. */
02265   wbio = SSL_get_wbio(tls->ssl);
02266   if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
02267     wbio = tmpbio;
02268   w = BIO_number_written(wbio);
02269 
02270   /* We are ok with letting these unsigned ints go "negative" here:
02271    * If we wrapped around, this should still give us the right answer, unless
02272    * we wrapped around by more than ULONG_MAX since the last time we called
02273    * this function.
02274    */
02275   *n_read = (size_t)(r - tls->last_read_count);
02276   *n_written = (size_t)(w - tls->last_write_count);
02277   if (*n_read > INT_MAX || *n_written > INT_MAX) {
02278     log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
02279              "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
02280              r, tls->last_read_count, w, tls->last_write_count);
02281   }
02282   tls->last_read_count = r;
02283   tls->last_write_count = w;
02284 }
02285 
02288 void
02289 _check_no_tls_errors(const char *fname, int line)
02290 {
02291   if (ERR_peek_error() == 0)
02292     return;
02293   log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
02294       tor_fix_source_file(fname), line);
02295   tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
02296 }
02297 
02300 int
02301 tor_tls_used_v1_handshake(tor_tls_t *tls)
02302 {
02303   if (tls->isServer) {
02304 #ifdef V2_HANDSHAKE_SERVER
02305     return ! tls->wasV2Handshake;
02306 #endif
02307   } else {
02308 #ifdef V2_HANDSHAKE_CLIENT
02309     return ! tls->wasV2Handshake;
02310 #endif
02311   }
02312   return 1;
02313 }
02314 
02317 static int
02318 dn_indicates_v3_cert(X509_NAME *name)
02319 {
02320 #ifdef DISABLE_V3_LINKPROTO_CLIENTSIDE
02321   (void)name;
02322   return 0;
02323 #else
02324   X509_NAME_ENTRY *entry;
02325   int n_entries;
02326   ASN1_OBJECT *obj;
02327   ASN1_STRING *str;
02328   unsigned char *s;
02329   int len, r;
02330 
02331   n_entries = X509_NAME_entry_count(name);
02332   if (n_entries != 1)
02333     return 1; /* More than one entry in the DN. */
02334   entry = X509_NAME_get_entry(name, 0);
02335 
02336   obj = X509_NAME_ENTRY_get_object(entry);
02337   if (OBJ_obj2nid(obj) != OBJ_txt2nid("commonName"))
02338     return 1; /* The entry isn't a commonName. */
02339 
02340   str = X509_NAME_ENTRY_get_data(entry);
02341   len = ASN1_STRING_to_UTF8(&s, str);
02342   if (len < 0)
02343     return 0;
02344   r = fast_memneq(s + len - 4, ".net", 4);
02345   OPENSSL_free(s);
02346   return r;
02347 #endif
02348 }
02349 
02358 int
02359 tor_tls_received_v3_certificate(tor_tls_t *tls)
02360 {
02361   X509 *cert = SSL_get_peer_certificate(tls->ssl);
02362   EVP_PKEY *key = NULL;
02363   X509_NAME *issuer_name, *subject_name;
02364   int is_v3 = 0;
02365 
02366   if (!cert) {
02367     log_warn(LD_BUG, "Called on a connection with no peer certificate");
02368     goto done;
02369   }
02370 
02371   subject_name = X509_get_subject_name(cert);
02372   issuer_name = X509_get_issuer_name(cert);
02373 
02374   if (X509_name_cmp(subject_name, issuer_name) == 0) {
02375     is_v3 = 1; /* purportedly self signed */
02376     goto done;
02377   }
02378 
02379   if (dn_indicates_v3_cert(subject_name) ||
02380       dn_indicates_v3_cert(issuer_name)) {
02381     is_v3 = 1; /* DN is fancy */
02382     goto done;
02383   }
02384 
02385   key = X509_get_pubkey(cert);
02386   if (EVP_PKEY_bits(key) != 1024 ||
02387       EVP_PKEY_type(key->type) != EVP_PKEY_RSA) {
02388     is_v3 = 1; /* Key is fancy */
02389     goto done;
02390   }
02391 
02392  done:
02393   if (key)
02394     EVP_PKEY_free(key);
02395   if (cert)
02396     X509_free(cert);
02397 
02398   return is_v3;
02399 }
02400 
02403 int
02404 tor_tls_get_num_server_handshakes(tor_tls_t *tls)
02405 {
02406   return tls->server_handshake_count;
02407 }
02408 
02411 int
02412 tor_tls_server_got_renegotiate(tor_tls_t *tls)
02413 {
02414   return tls->got_renegotiate;
02415 }
02416 
02421 int
02422 tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
02423 {
02424 #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
02425   char buf[128];
02426   size_t len;
02427   tor_assert(tls);
02428   tor_assert(tls->ssl);
02429   tor_assert(tls->ssl->s3);
02430   tor_assert(tls->ssl->session);
02431   /*
02432     The value is an HMAC, using the TLS master key as the HMAC key, of
02433     client_random | server_random | TLSSECRET_MAGIC
02434   */
02435   memcpy(buf +  0, tls->ssl->s3->client_random, 32);
02436   memcpy(buf + 32, tls->ssl->s3->server_random, 32);
02437   memcpy(buf + 64, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
02438   len = 64 + strlen(TLSSECRET_MAGIC) + 1;
02439   crypto_hmac_sha256((char*)secrets_out,
02440                      (char*)tls->ssl->session->master_key,
02441                      tls->ssl->session->master_key_length,
02442                      buf, len);
02443   memset(buf, 0, sizeof(buf));
02444   return 0;
02445 }
02446 
02452 void
02453 tor_tls_get_buffer_sizes(tor_tls_t *tls,
02454                          size_t *rbuf_capacity, size_t *rbuf_bytes,
02455                          size_t *wbuf_capacity, size_t *wbuf_bytes)
02456 {
02457   if (tls->ssl->s3->rbuf.buf)
02458     *rbuf_capacity = tls->ssl->s3->rbuf.len;
02459   else
02460     *rbuf_capacity = 0;
02461   if (tls->ssl->s3->wbuf.buf)
02462     *wbuf_capacity = tls->ssl->s3->wbuf.len;
02463   else
02464     *wbuf_capacity = 0;
02465   *rbuf_bytes = tls->ssl->s3->rbuf.left;
02466   *wbuf_bytes = tls->ssl->s3->wbuf.left;
02467 }
02468 
02469 #ifdef USE_BUFFEREVENTS
02470 
02484 struct bufferevent *
02485 tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
02486                          evutil_socket_t socket, int receiving,
02487                          int filter)
02488 {
02489   struct bufferevent *out;
02490   const enum bufferevent_ssl_state state = receiving ?
02491     BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
02492 
02493   if (filter || tor_libevent_using_iocp_bufferevents()) {
02494     /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
02495        means that the SSL will get freed too.
02496 
02497        This increment makes our SSL usage not-threadsafe, BTW.  We should
02498        see if we're allowed to use CRYPTO_add from outside openssl. */
02499     tls->ssl->references += 1;
02500     out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
02501                                          bufev_in,
02502                                          tls->ssl,
02503                                          state,
02504                                          BEV_OPT_DEFER_CALLBACKS|
02505                                          BEV_OPT_CLOSE_ON_FREE);
02506     /* Tell the underlying bufferevent when to accept more data from the SSL
02507        filter (only when it's got less than 32K to write), and when to notify
02508        the SSL filter that it could write more (when it drops under 24K). */
02509     bufferevent_setwatermark(bufev_in, EV_WRITE, 24*1024, 32*1024);
02510   } else {
02511     if (bufev_in) {
02512       evutil_socket_t s = bufferevent_getfd(bufev_in);
02513       tor_assert(s == -1 || s == socket);
02514       tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
02515       tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
02516       tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
02517       tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
02518       bufferevent_free(bufev_in);
02519     }
02520 
02521     /* Current versions (as of 2.0.x) of Libevent need to defer
02522      * bufferevent_openssl callbacks, or else our callback functions will
02523      * get called reentrantly, which is bad for us.
02524      */
02525     out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
02526                                          socket,
02527                                          tls->ssl,
02528                                          state,
02529                                          BEV_OPT_DEFER_CALLBACKS);
02530   }
02531   tls->state = TOR_TLS_ST_BUFFEREVENT;
02532 
02533   /* Unblock _after_ creating the bufferevent, since accept/connect tend to
02534    * clear flags. */
02535   tor_tls_unblock_renegotiation(tls);
02536 
02537   return out;
02538 }
02539 #endif
02540