Revise OpenSSL fix to work with OpenSSL 1.0.0beta*
[tor/rransom.git] / src / common / tortls.c
blobf552f2162dc65fe15a0e057d2ae97d3f9e159194
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file tortls.c
8 * \brief Wrapper functions to present a consistent interface to
9 * TLS, SSL, and X.509 functions from OpenSSL.
10 **/
12 /* (Unlike other tor functions, these
13 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
14 * functions and variables.)
17 #include "orconfig.h"
19 #include <assert.h>
20 #include <openssl/ssl.h>
21 #include <openssl/ssl3.h>
22 #include <openssl/err.h>
23 #include <openssl/tls1.h>
24 #include <openssl/asn1.h>
25 #include <openssl/bio.h>
26 #include <openssl/opensslv.h>
28 #if OPENSSL_VERSION_NUMBER < 0x00907000l
29 #error "We require OpenSSL >= 0.9.7"
30 #endif
32 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
34 #include "crypto.h"
35 #include "tortls.h"
36 #include "util.h"
37 #include "log.h"
38 #include "container.h"
39 #include "ht.h"
40 #include <string.h>
42 /* Enable the "v2" TLS handshake.
44 #define V2_HANDSHAKE_SERVER
45 #define V2_HANDSHAKE_CLIENT
47 /* Copied from or.h */
48 #define LEGAL_NICKNAME_CHARACTERS \
49 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
51 /** How long do identity certificates live? (sec) */
52 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
54 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
56 /* We redefine these so that we can run correctly even if the vendor gives us
57 * a version of OpenSSL that does not match its header files. (Apple: I am
58 * looking at you.)
60 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
61 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
62 #endif
63 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
64 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
65 #endif
67 /** Does the run-time openssl version look like we need
68 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
69 static int use_unsafe_renegotiation_op = 0;
70 /** Does the run-time openssl version look like we need
71 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
72 static int use_unsafe_renegotiation_flag = 0;
74 /** Structure holding the TLS state for a single connection. */
75 typedef struct tor_tls_context_t {
76 int refcnt;
77 SSL_CTX *ctx;
78 X509 *my_cert;
79 X509 *my_id_cert;
80 crypto_pk_env_t *key;
81 } tor_tls_context_t;
83 /** Holds a SSL object and its associated data. Members are only
84 * accessed from within tortls.c.
86 struct tor_tls_t {
87 HT_ENTRY(tor_tls_t) node;
88 tor_tls_context_t *context; /** A link to the context object for this tls. */
89 SSL *ssl; /**< An OpenSSL SSL object. */
90 int socket; /**< The underlying file descriptor for this TLS connection. */
91 char *address; /**< An address to log when describing this connection. */
92 enum {
93 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
94 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
95 } state : 3; /**< The current SSL state, depending on which operations have
96 * completed successfully. */
97 unsigned int isServer:1; /**< True iff this is a server-side connection */
98 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
99 * this connection used the updated version
100 * of the connection protocol (client sends
101 * different cipher list, server sends only
102 * one certificate). */
103 /** True iff we should call negotiated_callback when we're done reading. */
104 unsigned int got_renegotiate:1;
105 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
106 * time. */
107 /** Last values retrieved from BIO_number_read()/write(); see
108 * tor_tls_get_n_raw_bytes() for usage.
110 unsigned long last_write_count;
111 unsigned long last_read_count;
112 /** If set, a callback to invoke whenever the client tries to renegotiate
113 * the handshake. */
114 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
115 /** Argument to pass to negotiated_callback. */
116 void *callback_arg;
119 #ifdef V2_HANDSHAKE_CLIENT
120 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
121 * in client mode into advertising the ciphers we want. See
122 * rectify_client_ciphers() for details. */
123 static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
124 /** A stack of SSL_CIPHER objects, some real, some fake.
125 * See rectify_client_ciphers() for details. */
126 static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
127 #endif
129 /** Helper: compare tor_tls_t objects by its SSL. */
130 static INLINE int
131 tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
133 return a->ssl == b->ssl;
136 /** Helper: return a hash value for a tor_tls_t by its SSL. */
137 static INLINE unsigned int
138 tor_tls_entry_hash(const tor_tls_t *a)
140 #if SIZEOF_INT == SIZEOF_VOID_P
141 return ((unsigned int)(uintptr_t)a->ssl);
142 #else
143 return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
144 #endif
147 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
149 static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
151 HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
152 tor_tls_entries_eq)
153 HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
154 tor_tls_entries_eq, 0.6, malloc, realloc, free)
156 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
157 * pointer. */
158 static INLINE tor_tls_t *
159 tor_tls_get_by_ssl(const SSL *ssl)
161 tor_tls_t search, *result;
162 memset(&search, 0, sizeof(search));
163 search.ssl = (SSL*)ssl;
164 result = HT_FIND(tlsmap, &tlsmap_root, &search);
165 return result;
168 static void tor_tls_context_decref(tor_tls_context_t *ctx);
169 static void tor_tls_context_incref(tor_tls_context_t *ctx);
170 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
171 crypto_pk_env_t *rsa_sign,
172 const char *cname,
173 const char *cname_sign,
174 unsigned int lifetime);
175 static void tor_tls_unblock_renegotiation(tor_tls_t *tls);
177 /** Global tls context. We keep it here because nobody else needs to
178 * touch it. */
179 static tor_tls_context_t *global_tls_context = NULL;
180 /** True iff tor_tls_init() has been called. */
181 static int tls_library_is_initialized = 0;
183 /* Module-internal error codes. */
184 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
185 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
187 /** Log all pending tls errors at level <b>severity</b>. Use
188 * <b>doing</b> to describe our current activities.
190 static void
191 tls_log_errors(tor_tls_t *tls, int severity, const char *doing)
193 unsigned long err;
194 const char *msg, *lib, *func, *addr;
195 addr = tls ? tls->address : NULL;
196 while ((err = ERR_get_error()) != 0) {
197 msg = (const char*)ERR_reason_error_string(err);
198 lib = (const char*)ERR_lib_error_string(err);
199 func = (const char*)ERR_func_error_string(err);
200 if (!msg) msg = "(null)";
201 if (!lib) lib = "(null)";
202 if (!func) func = "(null)";
203 if (doing) {
204 log(severity, LD_NET, "TLS error while %s%s%s: %s (in %s:%s)",
205 doing, addr?" with ":"", addr?addr:"",
206 msg, lib, func);
207 } else {
208 log(severity, LD_NET, "TLS error%s%s: %s (in %s:%s)",
209 addr?" with ":"", addr?addr:"",
210 msg, lib, func);
215 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
216 * code. */
217 static int
218 tor_errno_to_tls_error(int e)
220 #if defined(MS_WINDOWS)
221 switch (e) {
222 case WSAECONNRESET: // most common
223 return TOR_TLS_ERROR_CONNRESET;
224 case WSAETIMEDOUT:
225 return TOR_TLS_ERROR_TIMEOUT;
226 case WSAENETUNREACH:
227 case WSAEHOSTUNREACH:
228 return TOR_TLS_ERROR_NO_ROUTE;
229 case WSAECONNREFUSED:
230 return TOR_TLS_ERROR_CONNREFUSED; // least common
231 default:
232 return TOR_TLS_ERROR_MISC;
234 #else
235 switch (e) {
236 case ECONNRESET: // most common
237 return TOR_TLS_ERROR_CONNRESET;
238 case ETIMEDOUT:
239 return TOR_TLS_ERROR_TIMEOUT;
240 case EHOSTUNREACH:
241 case ENETUNREACH:
242 return TOR_TLS_ERROR_NO_ROUTE;
243 case ECONNREFUSED:
244 return TOR_TLS_ERROR_CONNREFUSED; // least common
245 default:
246 return TOR_TLS_ERROR_MISC;
248 #endif
251 /** Given a TOR_TLS_* error code, return a string equivalent. */
252 const char *
253 tor_tls_err_to_string(int err)
255 if (err >= 0)
256 return "[Not an error.]";
257 switch (err) {
258 case TOR_TLS_ERROR_MISC: return "misc error";
259 case TOR_TLS_ERROR_IO: return "unexpected close";
260 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
261 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
262 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
263 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
264 case TOR_TLS_CLOSE: return "closed";
265 case TOR_TLS_WANTREAD: return "want to read";
266 case TOR_TLS_WANTWRITE: return "want to write";
267 default: return "(unknown error code)";
271 #define CATCH_SYSCALL 1
272 #define CATCH_ZERO 2
274 /** Given a TLS object and the result of an SSL_* call, use
275 * SSL_get_error to determine whether an error has occurred, and if so
276 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
277 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
278 * reporting syscall errors. If extra&CATCH_ZERO is true, return
279 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
281 * If an error has occurred, log it at level <b>severity</b> and describe the
282 * current action as <b>doing</b>.
284 static int
285 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
286 const char *doing, int severity)
288 int err = SSL_get_error(tls->ssl, r);
289 int tor_error = TOR_TLS_ERROR_MISC;
290 switch (err) {
291 case SSL_ERROR_NONE:
292 return TOR_TLS_DONE;
293 case SSL_ERROR_WANT_READ:
294 return TOR_TLS_WANTREAD;
295 case SSL_ERROR_WANT_WRITE:
296 return TOR_TLS_WANTWRITE;
297 case SSL_ERROR_SYSCALL:
298 if (extra&CATCH_SYSCALL)
299 return _TOR_TLS_SYSCALL;
300 if (r == 0) {
301 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
302 tor_error = TOR_TLS_ERROR_IO;
303 } else {
304 int e = tor_socket_errno(tls->socket);
305 log(severity, LD_NET,
306 "TLS error: <syscall error while %s> (errno=%d: %s)",
307 doing, e, tor_socket_strerror(e));
308 tor_error = tor_errno_to_tls_error(e);
310 tls_log_errors(tls, severity, doing);
311 return tor_error;
312 case SSL_ERROR_ZERO_RETURN:
313 if (extra&CATCH_ZERO)
314 return _TOR_TLS_ZERORETURN;
315 log(severity, LD_NET, "TLS connection closed while %s", doing);
316 tls_log_errors(tls, severity, doing);
317 return TOR_TLS_CLOSE;
318 default:
319 tls_log_errors(tls, severity, doing);
320 return TOR_TLS_ERROR_MISC;
324 /** Initialize OpenSSL, unless it has already been initialized.
326 static void
327 tor_tls_init(void)
329 if (!tls_library_is_initialized) {
330 long version;
331 SSL_library_init();
332 SSL_load_error_strings();
333 crypto_global_init(-1);
335 version = SSLeay();
337 /* OpenSSL 0.9.8l introdeced SSL3_FLAGS_ALLOW_UNSAGE_LEGACY_RENEGOTIATION
338 * here, but without thinking too hard about it: it turns out that the
339 * flag in question needed to be set at the last minute, and that it
340 * conflicted with an existing flag number that had already been added
341 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
342 * the flag with an option and (it seems) broke anything that used
343 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
344 * and we mustn't use the SSL3_FLAGS option with anything besides
345 * OpenSSL 0.9.8l.
347 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
348 * OpenSSL 1.0.0beta, since i. No, we can't just set option
349 * 0x00040000L everywhere: before 0.9.8m, it meant something else.
351 * No, we can't simply detect whether the flag or the option is present
352 * in the headers at build-time: some vendors (notably Apple) like to
353 * leave their headers out of sync with their libraries.
355 * Yes, it _is_ almost as if the OpenSSL developers decided that no
356 * program should be allowed to use renegotiation its first passed an
357 * test of intelligence and determination.
359 if (version >= 0x009080c0L && version < 0x009080d0L) {
360 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
361 "I will try SSL3_FLAGS to enable renegotation.",
362 SSLeay_version(SSLEAY_VERSION));
363 use_unsafe_renegotiation_flag = 1;
364 use_unsafe_renegotiation_op = 1;
365 } else if (version >= 0x009080d0L) {
366 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
367 "I will try SSL_OP to enable renegotiation",
368 SSLeay_version(SSLEAY_VERSION));
369 use_unsafe_renegotiation_op = 1;
370 } else {
371 log_info(LD_GENERAL, "OpenSSL %s has version %lx",
372 SSLeay_version(SSLEAY_VERSION), version);
375 tls_library_is_initialized = 1;
379 /** Free all global TLS structures. */
380 void
381 tor_tls_free_all(void)
383 if (global_tls_context) {
384 tor_tls_context_decref(global_tls_context);
385 global_tls_context = NULL;
387 if (!HT_EMPTY(&tlsmap_root)) {
388 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
390 HT_CLEAR(tlsmap, &tlsmap_root);
391 #ifdef V2_HANDSHAKE_CLIENT
392 if (CLIENT_CIPHER_DUMMIES)
393 tor_free(CLIENT_CIPHER_DUMMIES);
394 if (CLIENT_CIPHER_STACK)
395 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
396 #endif
399 /** We need to give OpenSSL a callback to verify certificates. This is
400 * it: We always accept peer certs and complete the handshake. We
401 * don't validate them until later.
403 static int
404 always_accept_verify_cb(int preverify_ok,
405 X509_STORE_CTX *x509_ctx)
407 (void) preverify_ok;
408 (void) x509_ctx;
409 return 1;
412 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
413 static X509_NAME *
414 tor_x509_name_new(const char *cname)
416 int nid;
417 X509_NAME *name;
418 if (!(name = X509_NAME_new()))
419 return NULL;
420 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
421 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
422 (unsigned char*)cname, -1, -1, 0)))
423 goto error;
424 return name;
425 error:
426 X509_NAME_free(name);
427 return NULL;
430 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
431 * signed by the private key <b>rsa_sign</b>. The commonName of the
432 * certificate will be <b>cname</b>; the commonName of the issuer will be
433 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
434 * starting from now. Return a certificate on success, NULL on
435 * failure.
437 static X509 *
438 tor_tls_create_certificate(crypto_pk_env_t *rsa,
439 crypto_pk_env_t *rsa_sign,
440 const char *cname,
441 const char *cname_sign,
442 unsigned int cert_lifetime)
444 time_t start_time, end_time;
445 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
446 X509 *x509 = NULL;
447 X509_NAME *name = NULL, *name_issuer=NULL;
449 tor_tls_init();
451 start_time = time(NULL);
453 tor_assert(rsa);
454 tor_assert(cname);
455 tor_assert(rsa_sign);
456 tor_assert(cname_sign);
457 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
458 goto error;
459 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
460 goto error;
461 if (!(x509 = X509_new()))
462 goto error;
463 if (!(X509_set_version(x509, 2)))
464 goto error;
465 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
466 goto error;
468 if (!(name = tor_x509_name_new(cname)))
469 goto error;
470 if (!(X509_set_subject_name(x509, name)))
471 goto error;
472 if (!(name_issuer = tor_x509_name_new(cname_sign)))
473 goto error;
474 if (!(X509_set_issuer_name(x509, name_issuer)))
475 goto error;
477 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
478 goto error;
479 end_time = start_time + cert_lifetime;
480 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
481 goto error;
482 if (!X509_set_pubkey(x509, pkey))
483 goto error;
484 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
485 goto error;
487 goto done;
488 error:
489 if (x509) {
490 X509_free(x509);
491 x509 = NULL;
493 done:
494 tls_log_errors(NULL, LOG_WARN, "generating certificate");
495 if (sign_pkey)
496 EVP_PKEY_free(sign_pkey);
497 if (pkey)
498 EVP_PKEY_free(pkey);
499 if (name)
500 X509_NAME_free(name);
501 if (name_issuer)
502 X509_NAME_free(name_issuer);
503 return x509;
506 /** List of ciphers that servers should select from.*/
507 #define SERVER_CIPHER_LIST \
508 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
509 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
510 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
511 /* Note: for setting up your own private testing network with link crypto
512 * disabled, set the cipher lists to your cipher list to
513 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
514 * with any of the "real" Tors, though. */
516 #ifdef V2_HANDSHAKE_CLIENT
517 #define CIPHER(id, name) name ":"
518 #define XCIPHER(id, name)
519 /** List of ciphers that clients should advertise, omitting items that
520 * our OpenSSL doesn't know about. */
521 static const char CLIENT_CIPHER_LIST[] =
522 #include "./ciphers.inc"
524 #undef CIPHER
525 #undef XCIPHER
527 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
528 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
529 /** A list of all the ciphers that clients should advertise, including items
530 * that OpenSSL might not know about. */
531 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
532 #define CIPHER(id, name) { id, name },
533 #define XCIPHER(id, name) { id, #name },
534 #include "./ciphers.inc"
535 #undef CIPHER
536 #undef XCIPHER
539 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
540 static const int N_CLIENT_CIPHERS =
541 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
542 #endif
544 #ifndef V2_HANDSHAKE_CLIENT
545 #undef CLIENT_CIPHER_LIST
546 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
547 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
548 #endif
550 /** Remove a reference to <b>ctx</b>, and free it if it has no more
551 * references. */
552 static void
553 tor_tls_context_decref(tor_tls_context_t *ctx)
555 tor_assert(ctx);
556 if (--ctx->refcnt == 0) {
557 SSL_CTX_free(ctx->ctx);
558 X509_free(ctx->my_cert);
559 X509_free(ctx->my_id_cert);
560 crypto_free_pk_env(ctx->key);
561 tor_free(ctx);
565 /** Increase the reference count of <b>ctx</b>. */
566 static void
567 tor_tls_context_incref(tor_tls_context_t *ctx)
569 ++ctx->refcnt;
572 /** Create a new TLS context for use with Tor TLS handshakes.
573 * <b>identity</b> should be set to the identity key used to sign the
574 * certificate, and <b>nickname</b> set to the nickname to use.
576 * You can call this function multiple times. Each time you call it,
577 * it generates new certificates; all new connections will use
578 * the new SSL context.
581 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
583 crypto_pk_env_t *rsa = NULL;
584 EVP_PKEY *pkey = NULL;
585 tor_tls_context_t *result = NULL;
586 X509 *cert = NULL, *idcert = NULL;
587 char *nickname = NULL, *nn2 = NULL;
589 tor_tls_init();
590 nickname = crypto_random_hostname(8, 20, "www.", ".net");
591 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
593 /* Generate short-term RSA key. */
594 if (!(rsa = crypto_new_pk_env()))
595 goto error;
596 if (crypto_pk_generate_key(rsa)<0)
597 goto error;
598 /* Create certificate signed by identity key. */
599 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
600 key_lifetime);
601 /* Create self-signed certificate for identity key. */
602 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
603 IDENTITY_CERT_LIFETIME);
604 if (!cert || !idcert) {
605 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
606 goto error;
609 result = tor_malloc_zero(sizeof(tor_tls_context_t));
610 result->refcnt = 1;
611 result->my_cert = X509_dup(cert);
612 result->my_id_cert = X509_dup(idcert);
613 result->key = crypto_pk_dup_key(rsa);
615 #ifdef EVERYONE_HAS_AES
616 /* Tell OpenSSL to only use TLS1 */
617 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
618 goto error;
619 #else
620 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
621 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
622 goto error;
623 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
624 #endif
625 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
627 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
628 SSL_CTX_set_options(result->ctx,
629 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
630 #endif
631 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
632 * as authenticating any earlier-received data.
634 if (use_unsafe_renegotiation_op) {
635 SSL_CTX_set_options(result->ctx,
636 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
638 /* Don't actually allow compression; it uses ram and time, but the data
639 * we transmit is all encrypted anyway. */
640 if (result->ctx->comp_methods)
641 result->ctx->comp_methods = NULL;
642 #ifdef SSL_MODE_RELEASE_BUFFERS
643 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
644 #endif
645 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
646 goto error;
647 X509_free(cert); /* We just added a reference to cert. */
648 cert=NULL;
649 if (idcert) {
650 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
651 tor_assert(s);
652 X509_STORE_add_cert(s, idcert);
653 X509_free(idcert); /* The context now owns the reference to idcert */
654 idcert = NULL;
656 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
657 tor_assert(rsa);
658 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
659 goto error;
660 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
661 goto error;
662 EVP_PKEY_free(pkey);
663 pkey = NULL;
664 if (!SSL_CTX_check_private_key(result->ctx))
665 goto error;
667 crypto_dh_env_t *dh = crypto_dh_new();
668 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
669 crypto_dh_free(dh);
671 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
672 always_accept_verify_cb);
673 /* let us realloc bufs that we're writing from */
674 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
675 /* Free the old context if one exists. */
676 if (global_tls_context) {
677 /* This is safe even if there are open connections: OpenSSL does
678 * reference counting with SSL and SSL_CTX objects. */
679 tor_tls_context_decref(global_tls_context);
681 global_tls_context = result;
682 if (rsa)
683 crypto_free_pk_env(rsa);
684 tor_free(nickname);
685 tor_free(nn2);
686 return 0;
688 error:
689 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
690 tor_free(nickname);
691 tor_free(nn2);
692 if (pkey)
693 EVP_PKEY_free(pkey);
694 if (rsa)
695 crypto_free_pk_env(rsa);
696 if (result)
697 tor_tls_context_decref(result);
698 if (cert)
699 X509_free(cert);
700 if (idcert)
701 X509_free(idcert);
702 return -1;
705 #ifdef V2_HANDSHAKE_SERVER
706 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
707 * a list that indicates that the client knows how to do the v2 TLS connection
708 * handshake. */
709 static int
710 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
712 int i;
713 SSL_SESSION *session;
714 /* If we reached this point, we just got a client hello. See if there is
715 * a cipher list. */
716 if (!(session = SSL_get_session((SSL *)ssl))) {
717 log_warn(LD_NET, "No session on TLS?");
718 return 0;
720 if (!session->ciphers) {
721 log_warn(LD_NET, "No ciphers on session");
722 return 0;
724 /* Now we need to see if there are any ciphers whose presence means we're
725 * dealing with an updated Tor. */
726 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
727 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
728 const char *ciphername = SSL_CIPHER_get_name(cipher);
729 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
730 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
731 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
732 strcmp(ciphername, "(NONE)")) {
733 /* XXXX should be ld_debug */
734 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
735 // return 1;
736 goto dump_list;
739 return 0;
740 dump_list:
742 smartlist_t *elts = smartlist_create();
743 char *s;
744 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
745 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
746 const char *ciphername = SSL_CIPHER_get_name(cipher);
747 smartlist_add(elts, (char*)ciphername);
749 s = smartlist_join_strings(elts, ":", 0, NULL);
750 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
751 address, s);
752 tor_free(s);
753 smartlist_free(elts);
755 return 1;
758 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
759 * changes state. We use this:
760 * <ul><li>To alter the state of the handshake partway through, so we
761 * do not send or request extra certificates in v2 handshakes.</li>
762 * <li>To detect renegotiation</li></ul>
764 static void
765 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
767 tor_tls_t *tls;
768 (void) val;
769 if (type != SSL_CB_ACCEPT_LOOP)
770 return;
771 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
772 return;
774 tls = tor_tls_get_by_ssl(ssl);
775 if (tls) {
776 /* Check whether we're watching for renegotiates. If so, this is one! */
777 if (tls->negotiated_callback)
778 tls->got_renegotiate = 1;
779 } else {
780 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
783 /* Now check the cipher list. */
784 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
785 /*XXXX_TLS keep this from happening more than once! */
787 /* Yes, we're casting away the const from ssl. This is very naughty of us.
788 * Let's hope openssl doesn't notice! */
790 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
791 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
792 /* Don't send a hello request. */
793 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
795 if (tls) {
796 tls->wasV2Handshake = 1;
797 } else {
798 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
802 #endif
804 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
805 * a list designed to mimic a common web browser. Some of the ciphers in the
806 * list won't actually be implemented by OpenSSL: that's okay so long as the
807 * server doesn't select them, and the server won't select anything besides
808 * what's in SERVER_CIPHER_LIST.
810 * [If the server <b>does</b> select a bogus cipher, we won't crash or
811 * anything; we'll just fail later when we try to look up the cipher in
812 * ssl->cipher_list_by_id.]
814 static void
815 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
817 #ifdef V2_HANDSHAKE_CLIENT
818 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
819 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
820 * we want.*/
821 int i = 0, j = 0;
823 /* First, create a dummy SSL_CIPHER for every cipher. */
824 CLIENT_CIPHER_DUMMIES =
825 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
826 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
827 CLIENT_CIPHER_DUMMIES[i].valid = 1;
828 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
829 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
832 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
833 tor_assert(CLIENT_CIPHER_STACK);
835 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
836 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
837 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
838 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
841 /* Then copy as many ciphers as we can from the good list, inserting
842 * dummies as needed. */
843 j=0;
844 for (i = 0; i < N_CLIENT_CIPHERS; ) {
845 SSL_CIPHER *cipher = NULL;
846 if (j < sk_SSL_CIPHER_num(*ciphers))
847 cipher = sk_SSL_CIPHER_value(*ciphers, j);
848 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
849 log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
850 ++j;
851 } else if (cipher &&
852 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
853 log_debug(LD_NET, "Found cipher %s", cipher->name);
854 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
855 ++j;
856 ++i;
857 } else {
858 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
859 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
860 ++i;
865 sk_SSL_CIPHER_free(*ciphers);
866 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
867 tor_assert(*ciphers);
869 #else
870 (void)ciphers;
871 #endif
874 /** Create a new TLS object from a file descriptor, and a flag to
875 * determine whether it is functioning as a server.
877 tor_tls_t *
878 tor_tls_new(int sock, int isServer)
880 BIO *bio = NULL;
881 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
883 tor_assert(global_tls_context); /* make sure somebody made it first */
884 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
885 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
886 tor_free(result);
887 return NULL;
890 #ifdef SSL_set_tlsext_host_name
891 /* Browsers use the TLS hostname extension, so we should too. */
893 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
894 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
895 tor_free(fake_hostname);
897 #endif
899 if (!SSL_set_cipher_list(result->ssl,
900 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
901 tls_log_errors(NULL, LOG_WARN, "setting ciphers");
902 #ifdef SSL_set_tlsext_host_name
903 SSL_set_tlsext_host_name(result->ssl, NULL);
904 #endif
905 SSL_free(result->ssl);
906 tor_free(result);
907 return NULL;
909 if (!isServer)
910 rectify_client_ciphers(&result->ssl->cipher_list);
911 result->socket = sock;
912 bio = BIO_new_socket(sock, BIO_NOCLOSE);
913 if (! bio) {
914 tls_log_errors(NULL, LOG_WARN, "opening BIO");
915 #ifdef SSL_set_tlsext_host_name
916 SSL_set_tlsext_host_name(result->ssl, NULL);
917 #endif
918 SSL_free(result->ssl);
919 tor_free(result);
920 return NULL;
922 HT_INSERT(tlsmap, &tlsmap_root, result);
923 SSL_set_bio(result->ssl, bio, bio);
924 tor_tls_context_incref(global_tls_context);
925 result->context = global_tls_context;
926 result->state = TOR_TLS_ST_HANDSHAKE;
927 result->isServer = isServer;
928 result->wantwrite_n = 0;
929 result->last_write_count = BIO_number_written(bio);
930 result->last_read_count = BIO_number_read(bio);
931 if (result->last_write_count || result->last_read_count) {
932 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
933 result->last_read_count, result->last_write_count);
935 #ifdef V2_HANDSHAKE_SERVER
936 if (isServer) {
937 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
939 #endif
941 /* Not expected to get called. */
942 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
943 return result;
946 /** Make future log messages about <b>tls</b> display the address
947 * <b>address</b>.
949 void
950 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
952 tor_assert(tls);
953 tor_free(tls->address);
954 tls->address = tor_strdup(address);
957 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
958 * next gets a client-side renegotiate in the middle of a read. Do not
959 * invoke this function until <em>after</em> initial handshaking is done!
961 void
962 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
963 void (*cb)(tor_tls_t *, void *arg),
964 void *arg)
966 tls->negotiated_callback = cb;
967 tls->callback_arg = arg;
968 tls->got_renegotiate = 0;
969 #ifdef V2_HANDSHAKE_SERVER
970 if (cb) {
971 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
972 } else {
973 SSL_set_info_callback(tls->ssl, NULL);
975 #endif
978 /** If this version of openssl requires it, turn on renegotiation on
979 * <b>tls</b>.
981 static void
982 tor_tls_unblock_renegotiation(tor_tls_t *tls)
984 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
985 * as authenticating any earlier-received data. */
986 if (use_unsafe_renegotiation_flag) {
987 tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
989 if (use_unsafe_renegotiation_op) {
990 SSL_set_options(tls->ssl,
991 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
995 /** If this version of openssl supports it, turn off renegotiation on
996 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
997 * to use belt-and-suspenders here.)
999 void
1000 tor_tls_block_renegotiation(tor_tls_t *tls)
1002 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1005 /** Return whether this tls initiated the connect (client) or
1006 * received it (server). */
1008 tor_tls_is_server(tor_tls_t *tls)
1010 tor_assert(tls);
1011 return tls->isServer;
1014 /** Release resources associated with a TLS object. Does not close the
1015 * underlying file descriptor.
1017 void
1018 tor_tls_free(tor_tls_t *tls)
1020 tor_tls_t *removed;
1021 tor_assert(tls && tls->ssl);
1022 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
1023 if (!removed) {
1024 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
1026 #ifdef SSL_set_tlsext_host_name
1027 SSL_set_tlsext_host_name(tls->ssl, NULL);
1028 #endif
1029 SSL_free(tls->ssl);
1030 tls->ssl = NULL;
1031 tls->negotiated_callback = NULL;
1032 if (tls->context)
1033 tor_tls_context_decref(tls->context);
1034 tor_free(tls->address);
1035 tor_free(tls);
1038 /** Underlying function for TLS reading. Reads up to <b>len</b>
1039 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1040 * number of characters read. On failure, returns TOR_TLS_ERROR,
1041 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1044 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
1046 int r, err;
1047 tor_assert(tls);
1048 tor_assert(tls->ssl);
1049 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1050 tor_assert(len<INT_MAX);
1051 r = SSL_read(tls->ssl, cp, (int)len);
1052 if (r > 0) {
1053 #ifdef V2_HANDSHAKE_SERVER
1054 if (tls->got_renegotiate) {
1055 /* Renegotiation happened! */
1056 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1057 if (tls->negotiated_callback)
1058 tls->negotiated_callback(tls, tls->callback_arg);
1059 tls->got_renegotiate = 0;
1061 #endif
1062 return r;
1064 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
1065 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
1066 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1067 tls->state = TOR_TLS_ST_CLOSED;
1068 return TOR_TLS_CLOSE;
1069 } else {
1070 tor_assert(err != TOR_TLS_DONE);
1071 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1072 return err;
1076 /** Underlying function for TLS writing. Write up to <b>n</b>
1077 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1078 * number of characters written. On failure, returns TOR_TLS_ERROR,
1079 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1082 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1084 int r, err;
1085 tor_assert(tls);
1086 tor_assert(tls->ssl);
1087 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1088 tor_assert(n < INT_MAX);
1089 if (n == 0)
1090 return 0;
1091 if (tls->wantwrite_n) {
1092 /* if WANTWRITE last time, we must use the _same_ n as before */
1093 tor_assert(n >= tls->wantwrite_n);
1094 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1095 (int)n, (int)tls->wantwrite_n);
1096 n = tls->wantwrite_n;
1097 tls->wantwrite_n = 0;
1099 r = SSL_write(tls->ssl, cp, (int)n);
1100 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
1101 if (err == TOR_TLS_DONE) {
1102 return r;
1104 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1105 tls->wantwrite_n = n;
1107 return err;
1110 /** Perform initial handshake on <b>tls</b>. When finished, returns
1111 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1112 * or TOR_TLS_WANTWRITE.
1115 tor_tls_handshake(tor_tls_t *tls)
1117 int r;
1118 tor_assert(tls);
1119 tor_assert(tls->ssl);
1120 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1121 check_no_tls_errors();
1122 if (tls->isServer) {
1123 r = SSL_accept(tls->ssl);
1124 } else {
1125 r = SSL_connect(tls->ssl);
1127 /* We need to call this here and not earlier, since OpenSSL has a penchant
1128 * for clearing its flags when you say accept or connect. */
1129 tor_tls_unblock_renegotiation(tls);
1130 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
1131 if (ERR_peek_error() != 0) {
1132 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
1133 "handshaking");
1134 return TOR_TLS_ERROR_MISC;
1136 if (r == TOR_TLS_DONE) {
1137 tls->state = TOR_TLS_ST_OPEN;
1138 if (tls->isServer) {
1139 SSL_set_info_callback(tls->ssl, NULL);
1140 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1141 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1142 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
1143 #ifdef V2_HANDSHAKE_SERVER
1144 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
1145 /* This check is redundant, but back when we did it in the callback,
1146 * we might have not been able to look up the tor_tls_t if the code
1147 * was buggy. Fixing that. */
1148 if (!tls->wasV2Handshake) {
1149 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1150 " get set. Fixing that.");
1152 tls->wasV2Handshake = 1;
1153 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
1154 "for renegotiation.");
1155 } else {
1156 tls->wasV2Handshake = 0;
1158 #endif
1159 } else {
1160 #ifdef V2_HANDSHAKE_CLIENT
1161 /* If we got no ID cert, we're a v2 handshake. */
1162 X509 *cert = SSL_get_peer_certificate(tls->ssl);
1163 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
1164 int n_certs = sk_X509_num(chain);
1165 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
1166 tls->wasV2Handshake = 0;
1167 else {
1168 log_debug(LD_NET, "Server sent back a single certificate; looks like "
1169 "a v2 handshake on %p.", tls);
1170 tls->wasV2Handshake = 1;
1172 if (cert)
1173 X509_free(cert);
1174 #endif
1175 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1176 tls_log_errors(NULL, LOG_WARN, "re-setting ciphers");
1177 r = TOR_TLS_ERROR_MISC;
1181 return r;
1184 /** Client only: Renegotiate a TLS session. When finished, returns
1185 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1186 * TOR_TLS_WANTWRITE.
1189 tor_tls_renegotiate(tor_tls_t *tls)
1191 int r;
1192 tor_assert(tls);
1193 /* We could do server-initiated renegotiation too, but that would be tricky.
1194 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1195 tor_assert(!tls->isServer);
1196 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1197 int r = SSL_renegotiate(tls->ssl);
1198 if (r <= 0) {
1199 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1201 tls->state = TOR_TLS_ST_RENEGOTIATE;
1203 r = SSL_do_handshake(tls->ssl);
1204 if (r == 1) {
1205 tls->state = TOR_TLS_ST_OPEN;
1206 return TOR_TLS_DONE;
1207 } else
1208 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1211 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1212 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1213 * or TOR_TLS_WANTWRITE.
1216 tor_tls_shutdown(tor_tls_t *tls)
1218 int r, err;
1219 char buf[128];
1220 tor_assert(tls);
1221 tor_assert(tls->ssl);
1223 while (1) {
1224 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1225 /* If we've already called shutdown once to send a close message,
1226 * we read until the other side has closed too.
1228 do {
1229 r = SSL_read(tls->ssl, buf, 128);
1230 } while (r>0);
1231 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1232 LOG_INFO);
1233 if (err == _TOR_TLS_ZERORETURN) {
1234 tls->state = TOR_TLS_ST_GOTCLOSE;
1235 /* fall through... */
1236 } else {
1237 return err;
1241 r = SSL_shutdown(tls->ssl);
1242 if (r == 1) {
1243 /* If shutdown returns 1, the connection is entirely closed. */
1244 tls->state = TOR_TLS_ST_CLOSED;
1245 return TOR_TLS_DONE;
1247 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1248 LOG_INFO);
1249 if (err == _TOR_TLS_SYSCALL) {
1250 /* The underlying TCP connection closed while we were shutting down. */
1251 tls->state = TOR_TLS_ST_CLOSED;
1252 return TOR_TLS_DONE;
1253 } else if (err == _TOR_TLS_ZERORETURN) {
1254 /* The TLS connection says that it sent a shutdown record, but
1255 * isn't done shutting down yet. Make sure that this hasn't
1256 * happened before, then go back to the start of the function
1257 * and try to read.
1259 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1260 tls->state == TOR_TLS_ST_SENTCLOSE) {
1261 log(LOG_WARN, LD_NET,
1262 "TLS returned \"half-closed\" value while already half-closed");
1263 return TOR_TLS_ERROR_MISC;
1265 tls->state = TOR_TLS_ST_SENTCLOSE;
1266 /* fall through ... */
1267 } else {
1268 return err;
1270 } /* end loop */
1273 /** Return true iff this TLS connection is authenticated.
1276 tor_tls_peer_has_cert(tor_tls_t *tls)
1278 X509 *cert;
1279 cert = SSL_get_peer_certificate(tls->ssl);
1280 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1281 if (!cert)
1282 return 0;
1283 X509_free(cert);
1284 return 1;
1287 /** Warn that a certificate lifetime extends through a certain range. */
1288 static void
1289 log_cert_lifetime(X509 *cert, const char *problem)
1291 BIO *bio = NULL;
1292 BUF_MEM *buf;
1293 char *s1=NULL, *s2=NULL;
1294 char mytime[33];
1295 time_t now = time(NULL);
1296 struct tm tm;
1298 if (problem)
1299 log_warn(LD_GENERAL,
1300 "Certificate %s: is your system clock set incorrectly?",
1301 problem);
1303 if (!(bio = BIO_new(BIO_s_mem()))) {
1304 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1306 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1307 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1308 goto end;
1310 BIO_get_mem_ptr(bio, &buf);
1311 s1 = tor_strndup(buf->data, buf->length);
1313 (void)BIO_reset(bio);
1314 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1315 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1316 goto end;
1318 BIO_get_mem_ptr(bio, &buf);
1319 s2 = tor_strndup(buf->data, buf->length);
1321 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1323 log_warn(LD_GENERAL,
1324 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1325 s1,s2,mytime);
1327 end:
1328 /* Not expected to get invoked */
1329 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1330 if (bio)
1331 BIO_free(bio);
1332 if (s1)
1333 tor_free(s1);
1334 if (s2)
1335 tor_free(s2);
1338 /** Helper function: try to extract a link certificate and an identity
1339 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1340 * *<b>id_cert_out</b> respectively. Log all messages at level
1341 * <b>severity</b>.
1343 * Note that a reference is added to cert_out, so it needs to be
1344 * freed. id_cert_out doesn't. */
1345 static void
1346 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1347 X509 **cert_out, X509 **id_cert_out)
1349 X509 *cert = NULL, *id_cert = NULL;
1350 STACK_OF(X509) *chain = NULL;
1351 int num_in_chain, i;
1352 *cert_out = *id_cert_out = NULL;
1354 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1355 return;
1356 *cert_out = cert;
1357 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1358 return;
1359 num_in_chain = sk_X509_num(chain);
1360 /* 1 means we're receiving (server-side), and it's just the id_cert.
1361 * 2 means we're connecting (client-side), and it's both the link
1362 * cert and the id_cert.
1364 if (num_in_chain < 1) {
1365 log_fn(severity,LD_PROTOCOL,
1366 "Unexpected number of certificates in chain (%d)",
1367 num_in_chain);
1368 return;
1370 for (i=0; i<num_in_chain; ++i) {
1371 id_cert = sk_X509_value(chain, i);
1372 if (X509_cmp(id_cert, cert) != 0)
1373 break;
1375 *id_cert_out = id_cert;
1378 /** If the provided tls connection is authenticated and has a
1379 * certificate chain that is currently valid and signed, then set
1380 * *<b>identity_key</b> to the identity certificate's key and return
1381 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1384 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1386 X509 *cert = NULL, *id_cert = NULL;
1387 EVP_PKEY *id_pkey = NULL;
1388 RSA *rsa;
1389 int r = -1;
1391 *identity_key = NULL;
1393 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1394 if (!cert)
1395 goto done;
1396 if (!id_cert) {
1397 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1398 goto done;
1400 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1401 X509_verify(cert, id_pkey) <= 0) {
1402 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1403 tls_log_errors(tls, severity,"verifying certificate");
1404 goto done;
1407 rsa = EVP_PKEY_get1_RSA(id_pkey);
1408 if (!rsa)
1409 goto done;
1410 *identity_key = _crypto_new_pk_env_rsa(rsa);
1412 r = 0;
1414 done:
1415 if (cert)
1416 X509_free(cert);
1417 if (id_pkey)
1418 EVP_PKEY_free(id_pkey);
1420 /* This should never get invoked, but let's make sure in case OpenSSL
1421 * acts unexpectedly. */
1422 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1424 return r;
1427 /** Check whether the certificate set on the connection <b>tls</b> is
1428 * expired or not-yet-valid, give or take <b>tolerance</b>
1429 * seconds. Return 0 for valid, -1 for failure.
1431 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1434 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1436 time_t now, t;
1437 X509 *cert;
1438 int r = -1;
1440 now = time(NULL);
1442 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1443 goto done;
1445 t = now + tolerance;
1446 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1447 log_cert_lifetime(cert, "not yet valid");
1448 goto done;
1450 t = now - tolerance;
1451 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1452 log_cert_lifetime(cert, "already expired");
1453 goto done;
1456 r = 0;
1457 done:
1458 if (cert)
1459 X509_free(cert);
1460 /* Not expected to get invoked */
1461 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1463 return r;
1466 /** Return the number of bytes available for reading from <b>tls</b>.
1469 tor_tls_get_pending_bytes(tor_tls_t *tls)
1471 tor_assert(tls);
1472 return SSL_pending(tls->ssl);
1475 /** If <b>tls</b> requires that the next write be of a particular size,
1476 * return that size. Otherwise, return 0. */
1477 size_t
1478 tor_tls_get_forced_write_size(tor_tls_t *tls)
1480 return tls->wantwrite_n;
1483 /** Sets n_read and n_written to the number of bytes read and written,
1484 * respectively, on the raw socket used by <b>tls</b> since the last time this
1485 * function was called on <b>tls</b>. */
1486 void
1487 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1489 BIO *wbio, *tmpbio;
1490 unsigned long r, w;
1491 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1492 /* We want the number of bytes actually for real written. Unfortunately,
1493 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1494 * which makes the answer turn out wrong. Let's cope with that. Note
1495 * that this approach will fail if we ever replace tls->ssl's BIOs with
1496 * buffering bios for reasons of our own. As an alternative, we could
1497 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1498 * that would be tempting fate. */
1499 wbio = SSL_get_wbio(tls->ssl);
1500 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1501 wbio = tmpbio;
1502 w = BIO_number_written(wbio);
1504 /* We are ok with letting these unsigned ints go "negative" here:
1505 * If we wrapped around, this should still give us the right answer, unless
1506 * we wrapped around by more than ULONG_MAX since the last time we called
1507 * this function.
1509 *n_read = (size_t)(r - tls->last_read_count);
1510 *n_written = (size_t)(w - tls->last_write_count);
1511 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1512 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1513 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1514 r, tls->last_read_count, w, tls->last_write_count);
1516 tls->last_read_count = r;
1517 tls->last_write_count = w;
1520 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1521 * errors, log an error message. */
1522 void
1523 _check_no_tls_errors(const char *fname, int line)
1525 if (ERR_peek_error() == 0)
1526 return;
1527 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1528 tor_fix_source_file(fname), line);
1529 tls_log_errors(NULL, LOG_WARN, NULL);
1532 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1533 * TLS handshake. Output is undefined if the handshake isn't finished. */
1535 tor_tls_used_v1_handshake(tor_tls_t *tls)
1537 if (tls->isServer) {
1538 #ifdef V2_HANDSHAKE_SERVER
1539 return ! tls->wasV2Handshake;
1540 #endif
1541 } else {
1542 #ifdef V2_HANDSHAKE_CLIENT
1543 return ! tls->wasV2Handshake;
1544 #endif
1546 return 1;
1549 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1550 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1551 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1552 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1553 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1554 void
1555 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1556 size_t *rbuf_capacity, size_t *rbuf_bytes,
1557 size_t *wbuf_capacity, size_t *wbuf_bytes)
1559 if (tls->ssl->s3->rbuf.buf)
1560 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1561 else
1562 *rbuf_capacity = 0;
1563 if (tls->ssl->s3->wbuf.buf)
1564 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1565 else
1566 *wbuf_capacity = 0;
1567 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1568 *wbuf_bytes = tls->ssl->s3->wbuf.left;