doxygen and other cleanups
[tor.git] / src / common / tortls.c
blob51ce4a6c3a2c333f361bd2b931c693dcf35000fd
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char tortls_c_id[] =
7 "$Id$";
9 /**
10 * \file tortls.c
11 * \brief Wrapper functions to present a consistent interface to
12 * TLS, SSL, and X.509 functions from OpenSSL.
13 **/
15 /* (Unlike other tor functions, these
16 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
17 * functions and variables.)
20 #include "orconfig.h"
22 #include <assert.h>
23 #include <openssl/ssl.h>
24 #include <openssl/ssl3.h>
25 #include <openssl/err.h>
26 #include <openssl/tls1.h>
27 #include <openssl/asn1.h>
28 #include <openssl/bio.h>
29 #include <openssl/opensslv.h>
31 #if OPENSSL_VERSION_NUMBER < 0x00907000l
32 #error "We require openssl >= 0.9.7"
33 #endif
35 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
37 #include "crypto.h"
38 #include "tortls.h"
39 #include "util.h"
40 #include "log.h"
41 #include "container.h"
42 #include "ht.h"
43 #include <string.h>
45 // #define V2_HANDSHAKE_SERVER
46 // #define V2_HANDSHAKE_CLIENT
48 /* Copied from or.h */
49 #define LEGAL_NICKNAME_CHARACTERS \
50 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
52 /** How long do identity certificates live? (sec) */
53 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
55 /** Structure holding the TLS state for a single connection. */
56 typedef struct tor_tls_context_t {
57 int refcnt;
58 SSL_CTX *ctx;
59 X509 *my_cert;
60 X509 *my_id_cert;
61 crypto_pk_env_t *key;
62 } tor_tls_context_t;
64 /** Holds a SSL object and its associated data. Members are only
65 * accessed from within tortls.c.
67 struct tor_tls_t {
68 HT_ENTRY(tor_tls_t) node;
69 tor_tls_context_t *context; /** A link to the context object for this tls */
70 SSL *ssl; /**< An OpenSSL SSL object. */
71 int socket; /**< The underlying file descriptor for this TLS connection. */
72 enum {
73 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
74 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
75 } state : 3; /**< The current SSL state, depending on which operations have
76 * completed successfully. */
77 unsigned int isServer:1; /**< True iff this is a server-side connection */
78 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
79 * this connection used the updated version
80 * of the connection protocol (client sends
81 * different cipher list, server sends only
82 * one certificate). */
83 int got_renegotiate:1; /**< True iff we should call negotiated_callback
84 * when we're done reading. */
85 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
86 * time. */
87 /** Last values retrieved from BIO_number_read()/write(); see
88 * tor_tls_get_n_raw_bytes() for usage.
90 unsigned long last_write_count;
91 unsigned long last_read_count;
92 /** If set, a callback to invoke whenever the client tries to renegotiate
93 * the handshake. */
94 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
95 /** Argument to pass to negotiated_callback. */
96 void *callback_arg;
99 /** Helper: compare tor_tls_t objects by its SSL. */
100 static INLINE int
101 tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
103 return a->ssl == b->ssl;
106 /** Helper: return a hash value for a tor_tls_t by its SSL. */
107 static INLINE unsigned int
108 tor_tls_entry_hash(const tor_tls_t *a)
110 #if SIZEOF_INT == SIZEOF_VOID_P
111 return ((unsigned int)a->ssl);
112 #else
113 return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
114 #endif
117 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
119 static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
121 HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
122 tor_tls_entries_eq)
123 HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
124 tor_tls_entries_eq, 0.6, malloc, realloc, free)
126 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
127 * pointer. */
128 static INLINE tor_tls_t *
129 tor_tls_get_by_ssl(const SSL *ssl)
131 tor_tls_t search, *result;
132 memset(&search, 0, sizeof(search));
133 search.ssl = (SSL*)ssl;
134 result = HT_FIND(tlsmap, &tlsmap_root, &search);
135 return result;
138 static void tor_tls_context_decref(tor_tls_context_t *ctx);
139 static void tor_tls_context_incref(tor_tls_context_t *ctx);
140 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
141 crypto_pk_env_t *rsa_sign,
142 const char *cname,
143 const char *cname_sign,
144 unsigned int lifetime);
146 /** Global tls context. We keep it here because nobody else needs to
147 * touch it. */
148 static tor_tls_context_t *global_tls_context = NULL;
149 /** True iff tor_tls_init() has been called. */
150 static int tls_library_is_initialized = 0;
152 /* Module-internal error codes. */
153 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
154 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
156 /** Log all pending tls errors at level <b>severity</b>. Use
157 * <b>doing</b> to describe our current activities.
159 static void
160 tls_log_errors(int severity, const char *doing)
162 int err;
163 const char *msg, *lib, *func;
164 while ((err = ERR_get_error()) != 0) {
165 msg = (const char*)ERR_reason_error_string(err);
166 lib = (const char*)ERR_lib_error_string(err);
167 func = (const char*)ERR_func_error_string(err);
168 if (!msg) msg = "(null)";
169 if (doing) {
170 log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)",
171 doing, msg, lib,func);
172 } else {
173 log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
178 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
179 * code. */
180 static int
181 tor_errno_to_tls_error(int e)
183 #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
184 switch (e) {
185 case WSAECONNRESET: // most common
186 return TOR_TLS_ERROR_CONNRESET;
187 case WSAETIMEDOUT:
188 return TOR_TLS_ERROR_TIMEOUT;
189 case WSAENETUNREACH:
190 case WSAEHOSTUNREACH:
191 return TOR_TLS_ERROR_NO_ROUTE;
192 case WSAECONNREFUSED:
193 return TOR_TLS_ERROR_CONNREFUSED; // least common
194 default:
195 return TOR_TLS_ERROR_MISC;
197 #else
198 switch (e) {
199 case ECONNRESET: // most common
200 return TOR_TLS_ERROR_CONNRESET;
201 case ETIMEDOUT:
202 return TOR_TLS_ERROR_TIMEOUT;
203 case EHOSTUNREACH:
204 case ENETUNREACH:
205 return TOR_TLS_ERROR_NO_ROUTE;
206 case ECONNREFUSED:
207 return TOR_TLS_ERROR_CONNREFUSED; // least common
208 default:
209 return TOR_TLS_ERROR_MISC;
211 #endif
214 /** Given a TOR_TLS_* error code, return a string equivalent. */
215 const char *
216 tor_tls_err_to_string(int err)
218 if (err >= 0)
219 return "[Not an error.]";
220 switch (err) {
221 case TOR_TLS_ERROR_MISC: return "misc error";
222 case TOR_TLS_ERROR_IO: return "unexpected close";
223 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
224 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
225 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
226 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
227 case TOR_TLS_CLOSE: return "closed";
228 case TOR_TLS_WANTREAD: return "want to read";
229 case TOR_TLS_WANTWRITE: return "want to write";
230 default: return "(unknown error code)";
234 #define CATCH_SYSCALL 1
235 #define CATCH_ZERO 2
237 /** Given a TLS object and the result of an SSL_* call, use
238 * SSL_get_error to determine whether an error has occurred, and if so
239 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
240 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
241 * reporting syscall errors. If extra&CATCH_ZERO is true, return
242 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
244 * If an error has occurred, log it at level <b>severity</b> and describe the
245 * current action as <b>doing</b>.
247 static int
248 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
249 const char *doing, int severity)
251 int err = SSL_get_error(tls->ssl, r);
252 int tor_error = TOR_TLS_ERROR_MISC;
253 switch (err) {
254 case SSL_ERROR_NONE:
255 return TOR_TLS_DONE;
256 case SSL_ERROR_WANT_READ:
257 return TOR_TLS_WANTREAD;
258 case SSL_ERROR_WANT_WRITE:
259 return TOR_TLS_WANTWRITE;
260 case SSL_ERROR_SYSCALL:
261 if (extra&CATCH_SYSCALL)
262 return _TOR_TLS_SYSCALL;
263 if (r == 0) {
264 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
265 tor_error = TOR_TLS_ERROR_IO;
266 } else {
267 int e = tor_socket_errno(tls->socket);
268 log(severity, LD_NET,
269 "TLS error: <syscall error while %s> (errno=%d: %s)",
270 doing, e, tor_socket_strerror(e));
271 tor_error = tor_errno_to_tls_error(e);
273 tls_log_errors(severity, doing);
274 return tor_error;
275 case SSL_ERROR_ZERO_RETURN:
276 if (extra&CATCH_ZERO)
277 return _TOR_TLS_ZERORETURN;
278 log(severity, LD_NET, "TLS error: Zero return");
279 tls_log_errors(severity, doing);
280 /* XXXX020 Actually, a 'zero return' error has a pretty specific meaning:
281 * the connection has been closed cleanly. */
282 return TOR_TLS_ERROR_MISC;
283 default:
284 tls_log_errors(severity, doing);
285 return TOR_TLS_ERROR_MISC;
289 /** Initialize OpenSSL, unless it has already been initialized.
291 static void
292 tor_tls_init(void)
294 if (!tls_library_is_initialized) {
295 SSL_library_init();
296 SSL_load_error_strings();
297 crypto_global_init(-1);
298 tls_library_is_initialized = 1;
302 /** Free all global TLS structures. */
303 void
304 tor_tls_free_all(void)
306 if (global_tls_context) {
307 tor_tls_context_decref(global_tls_context);
308 global_tls_context = NULL;
312 /** We need to give OpenSSL a callback to verify certificates. This is
313 * it: We always accept peer certs and complete the handshake. We
314 * don't validate them until later.
316 static int
317 always_accept_verify_cb(int preverify_ok,
318 X509_STORE_CTX *x509_ctx)
320 (void) preverify_ok;
321 (void) x509_ctx;
322 return 1;
325 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
326 static X509_NAME *
327 tor_x509_name_new(const char *cname)
329 int nid;
330 X509_NAME *name;
331 if (!(name = X509_NAME_new()))
332 return NULL;
333 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
334 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
335 (unsigned char*)cname, -1, -1, 0)))
336 goto error;
337 return name;
338 error:
339 X509_NAME_free(name);
340 return NULL;
343 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
344 * signed by the private key <b>rsa_sign</b>. The commonName of the
345 * certificate will be <b>cname</b>; the commonName of the issuer will be
346 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
347 * starting from now. Return a certificate on success, NULL on
348 * failure.
350 static X509 *
351 tor_tls_create_certificate(crypto_pk_env_t *rsa,
352 crypto_pk_env_t *rsa_sign,
353 const char *cname,
354 const char *cname_sign,
355 unsigned int cert_lifetime)
357 time_t start_time, end_time;
358 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
359 X509 *x509 = NULL;
360 X509_NAME *name = NULL, *name_issuer=NULL;
362 tor_tls_init();
364 start_time = time(NULL);
366 tor_assert(rsa);
367 tor_assert(cname);
368 tor_assert(rsa_sign);
369 tor_assert(cname_sign);
370 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
371 goto error;
372 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
373 goto error;
374 if (!(x509 = X509_new()))
375 goto error;
376 if (!(X509_set_version(x509, 2)))
377 goto error;
378 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
379 goto error;
381 if (!(name = tor_x509_name_new(cname)))
382 goto error;
383 if (!(X509_set_subject_name(x509, name)))
384 goto error;
385 if (!(name_issuer = tor_x509_name_new(cname_sign)))
386 goto error;
387 if (!(X509_set_issuer_name(x509, name_issuer)))
388 goto error;
390 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
391 goto error;
392 end_time = start_time + cert_lifetime;
393 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
394 goto error;
395 if (!X509_set_pubkey(x509, pkey))
396 goto error;
397 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
398 goto error;
400 goto done;
401 error:
402 if (x509) {
403 X509_free(x509);
404 x509 = NULL;
406 done:
407 tls_log_errors(LOG_WARN, "generating certificate");
408 if (sign_pkey)
409 EVP_PKEY_free(sign_pkey);
410 if (pkey)
411 EVP_PKEY_free(pkey);
412 if (name)
413 X509_NAME_free(name);
414 if (name_issuer)
415 X509_NAME_free(name_issuer);
416 return x509;
419 #define SERVER_CIPHER_LIST \
420 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
421 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
422 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
423 /* Note: for setting up your own private testing network with link crypto
424 * disabled, set the cipher lists to your cipher list to
425 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
426 * with any of the "real" Tors, though. */
428 #if OPENSSL_VERSION_NUMBER >= 0x00908000l
429 #define CLIENT_CIPHER_LIST \
430 (TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ":" \
431 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":" \
432 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
433 TLS1_TXT_DHE_DSS_WITH_AES_256_SHA ":" \
434 TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA ":" \
435 TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA ":" \
436 TLS1_TXT_RSA_WITH_AES_256_SHA ":" \
437 TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA ":" \
438 TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ":" \
439 TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA ":" \
440 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":" \
441 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
442 TLS1_TXT_DHE_DSS_WITH_AES_128_SHA ":" \
443 TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA":" \
444 TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA":" \
445 TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA ":" \
446 TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA ":" \
447 SSL3_TXT_RSA_RC4_128_MD5 ":" \
448 SSL3_TXT_RSA_RC4_128_SHA ":" \
449 TLS1_TXT_RSA_WITH_AES_128_SHA ":" \
450 TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA ":" \
451 TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":" \
452 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
453 SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA ":" \
454 TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA ":" \
455 TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA ":" \
456 /*SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA ":"*/ \
457 SSL3_TXT_RSA_DES_192_CBC3_SHA)
458 /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA is commented out because it doesn't
459 * really exist; if I understand correctly, it's a bit of silliness that
460 * netscape did on its own before any standard for what they wanted was
461 * formally approved. Nonetheless, Firefox still uses it, so we need to
462 * fake it at some point soon. XXXX020 -NM */
463 #else
464 /* Ug. We don't have as many ciphers with openssl 0.9.7 as we'd like. Fix
465 * this list into something that sucks less. */
466 #define CLIENT_CIPHER_LIST \
467 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
468 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
469 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
470 SSL3_TXT_RSA_RC4_128_SHA)
471 #endif
473 #ifndef V2_HANDSHAKE_CLIENT
474 #undef CLIENT_CIPHER_LIST
475 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
476 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
477 #endif
479 /** Remove a reference to <b>ctx</b>, and free it if it has no more
480 * references. */
481 static void
482 tor_tls_context_decref(tor_tls_context_t *ctx)
484 tor_assert(ctx);
485 if (--ctx->refcnt == 0) {
486 SSL_CTX_free(ctx->ctx);
487 X509_free(ctx->my_cert);
488 X509_free(ctx->my_id_cert);
489 crypto_free_pk_env(ctx->key);
490 tor_free(ctx);
494 /** Increase the reference count of <b>ctx</b>. */
495 static void
496 tor_tls_context_incref(tor_tls_context_t *ctx)
498 ++ctx->refcnt;
501 /** Create a new TLS context for use with Tor TLS handshakes.
502 * <b>identity</b> should be set to the identity key used to sign the
503 * certificate, and <b>nickname</b> set to the nickname to use.
505 * You can call this function multiple times. Each time you call it,
506 * it generates new certificates; all new connections will use
507 * the new SSL context.
510 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
512 crypto_pk_env_t *rsa = NULL;
513 crypto_dh_env_t *dh = NULL;
514 EVP_PKEY *pkey = NULL;
515 tor_tls_context_t *result = NULL;
516 X509 *cert = NULL, *idcert = NULL;
517 char *nickname = NULL, *nn2 = NULL;
519 tor_tls_init();
520 nickname = crypto_random_hostname(8, 20, "www.", ".net");
521 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
523 /* Generate short-term RSA key. */
524 if (!(rsa = crypto_new_pk_env()))
525 goto error;
526 if (crypto_pk_generate_key(rsa)<0)
527 goto error;
528 /* Create certificate signed by identity key. */
529 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
530 key_lifetime);
531 /* Create self-signed certificate for identity key. */
532 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
533 IDENTITY_CERT_LIFETIME);
534 if (!cert || !idcert) {
535 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
536 goto error;
539 result = tor_malloc_zero(sizeof(tor_tls_context_t));
540 result->refcnt = 1;
541 result->my_cert = X509_dup(cert);
542 result->my_id_cert = X509_dup(idcert);
543 result->key = crypto_pk_dup_key(rsa);
545 #ifdef EVERYONE_HAS_AES
546 /* Tell OpenSSL to only use TLS1 */
547 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
548 goto error;
549 #else
550 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
551 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
552 goto error;
553 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
554 #endif
555 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
556 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
557 goto error;
558 X509_free(cert); /* We just added a reference to cert. */
559 cert=NULL;
560 if (idcert) {
561 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
562 tor_assert(s);
563 X509_STORE_add_cert(s, idcert);
564 X509_free(idcert); /* The context now owns the reference to idcert */
565 idcert = NULL;
567 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
568 tor_assert(rsa);
569 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
570 goto error;
571 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
572 goto error;
573 EVP_PKEY_free(pkey);
574 pkey = NULL;
575 if (!SSL_CTX_check_private_key(result->ctx))
576 goto error;
577 dh = crypto_dh_new();
578 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
579 crypto_dh_free(dh);
580 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
581 always_accept_verify_cb);
582 /* let us realloc bufs that we're writing from */
583 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
584 /* Free the old context if one exists. */
585 if (global_tls_context) {
586 /* This is safe even if there are open connections: OpenSSL does
587 * reference counting with SSL and SSL_CTX objects. */
588 tor_tls_context_decref(global_tls_context);
590 global_tls_context = result;
591 if (rsa)
592 crypto_free_pk_env(rsa);
593 tor_free(nickname);
594 tor_free(nn2);
595 return 0;
597 error:
598 tls_log_errors(LOG_WARN, "creating TLS context");
599 tor_free(nickname);
600 tor_free(nn2);
601 if (pkey)
602 EVP_PKEY_free(pkey);
603 if (rsa)
604 crypto_free_pk_env(rsa);
605 if (dh)
606 crypto_dh_free(dh);
607 if (result)
608 tor_tls_context_decref(result);
609 if (cert)
610 X509_free(cert);
611 if (idcert)
612 X509_free(idcert);
613 return -1;
616 #ifdef V2_HANDSHAKE_SERVER
617 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
618 * a list that indicates that the client know how to do the v2 TLS connection
619 * handshake. */
620 static int
621 tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
623 int i;
624 SSL_SESSION *session;
625 /* If we reached this point, we just got a client hello. See if there is
626 * a cipher list. */
627 if (!(session = SSL_get_session(ssl))) {
628 log_warn(LD_NET, "No session on TLS?");
629 return 0;
631 if (!session->ciphers) {
632 log_warn(LD_NET, "No ciphers on session");
633 return 0;
635 /* Now we need to see if there are any ciphers whose presence means we're
636 * dealing with an updated Tor. */
637 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
638 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
639 const char *ciphername = SSL_CIPHER_get_name(cipher);
640 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
641 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
642 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
643 strcmp(ciphername, "(NONE)")) {
644 /* XXXX should be ld_debug */
645 log_info(LD_NET, "Got a non-version-1 cipher called '%s'",ciphername);
646 // return 1;
647 goto dump_list;
650 return 0;
651 dump_list:
653 smartlist_t *elts = smartlist_create();
654 char *s;
655 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
656 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
657 const char *ciphername = SSL_CIPHER_get_name(cipher);
658 smartlist_add(elts, (char*)ciphername);
660 s = smartlist_join_strings(elts, ":", 0, NULL);
661 log_info(LD_NET, "Got a non-version-1 cipher list. It is: '%s'", s);
662 tor_free(s);
663 smartlist_free(elts);
665 return 1;
668 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
669 * changes state. We use this:
670 * <ul><li>To alter the state of the handshake partway through, so we
671 * do not send or request extra certificates in v2 handshakes.</li>
672 * <li>To detect renegotiation</li></ul>
674 static void
675 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
677 tor_tls_t *tls;
678 (void) val;
679 if (type != SSL_CB_ACCEPT_LOOP)
680 return;
681 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
682 return;
684 tls = tor_tls_get_by_ssl(ssl);
685 if (tls) {
686 /* Check whether we're watching for renegotiates. If so, this is one! */
687 if (tls->negotiated_callback)
688 tls->got_renegotiate = 1;
689 } else {
690 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
693 /* Now check the cipher list. */
694 if (tor_tls_client_is_using_v2_ciphers(ssl)) {
695 /*XXXX_TLS keep this from happening more than once! */
697 /* Yes, we're casting away the const from ssl. This is very naughty of us.
698 * Let's hope openssl doesn't notice! */
700 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
701 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
702 /* Don't send a hello request. */
703 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
705 if (tls) {
706 tls->wasV2Handshake = 1;
707 } else {
708 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
712 #endif
714 /** Create a new TLS object from a file descriptor, and a flag to
715 * determine whether it is functioning as a server.
717 tor_tls_t *
718 tor_tls_new(int sock, int isServer)
720 BIO *bio = NULL;
721 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
723 tor_assert(global_tls_context); /* make sure somebody made it first */
724 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
725 tls_log_errors(LOG_WARN, "generating TLS context");
726 tor_free(result);
727 return NULL;
729 if (!SSL_set_cipher_list(result->ssl,
730 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
731 SSL_free(result->ssl);
732 tor_free(result);
733 return NULL;
735 result->socket = sock;
736 #ifdef USE_BSOCKETS
737 bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
738 #else
739 bio = BIO_new_socket(sock, BIO_NOCLOSE);
740 #endif
741 if (! bio) {
742 tls_log_errors(LOG_WARN, "opening BIO");
743 SSL_free(result->ssl);
744 tor_free(result);
745 return NULL;
747 HT_INSERT(tlsmap, &tlsmap_root, result);
748 SSL_set_bio(result->ssl, bio, bio);
749 tor_tls_context_incref(global_tls_context);
750 result->context = global_tls_context;
751 result->state = TOR_TLS_ST_HANDSHAKE;
752 result->isServer = isServer;
753 result->wantwrite_n = 0;
754 #ifdef V2_HANDSHAKE_SERVER
755 if (isServer) {
756 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
758 #endif
759 /* Not expected to get called. */
760 tls_log_errors(LOG_WARN, "generating TLS context");
761 return result;
764 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
765 * next gets a client-side renegotiate in the middle of a read. Do not
766 * invoke this function untile <em>after</em> initial handshaking is done!
768 void
769 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
770 void (*cb)(tor_tls_t *, void *arg),
771 void *arg)
773 tls->negotiated_callback = cb;
774 tls->callback_arg = arg;
775 tls->got_renegotiate = 0;
776 #ifdef V2_HANDSHAKE_SERVER
777 if (cb) {
778 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
779 } else {
780 SSL_set_info_callback(tls->ssl, NULL);
782 #endif
785 /** Return whether this tls initiated the connect (client) or
786 * received it (server). */
788 tor_tls_is_server(tor_tls_t *tls)
790 tor_assert(tls);
791 return tls->isServer;
794 /** Release resources associated with a TLS object. Does not close the
795 * underlying file descriptor.
797 void
798 tor_tls_free(tor_tls_t *tls)
800 tor_tls_t *removed;
801 tor_assert(tls && tls->ssl);
802 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
803 if (!removed) {
804 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
806 SSL_free(tls->ssl);
807 tls->ssl = NULL;
808 tls->negotiated_callback = NULL;
809 if (tls->context)
810 tor_tls_context_decref(tls->context);
811 tor_free(tls);
814 /** Underlying function for TLS reading. Reads up to <b>len</b>
815 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
816 * number of characters read. On failure, returns TOR_TLS_ERROR,
817 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
820 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
822 int r, err;
823 tor_assert(tls);
824 tor_assert(tls->ssl);
825 tor_assert(tls->state == TOR_TLS_ST_OPEN);
826 r = SSL_read(tls->ssl, cp, len);
827 if (r > 0) {
828 #ifdef V2_HANDSHAKE_SERVER
829 if (tls->got_renegotiate) {
830 /* Renegotiation happened! */
831 log_notice(LD_NET, "Got a TLS renegotiation from %p", tls);
832 if (tls->negotiated_callback)
833 tls->negotiated_callback(tls, tls->callback_arg);
834 tls->got_renegotiate = 0;
836 #endif
837 return r;
839 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
840 if (err == _TOR_TLS_ZERORETURN) {
841 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
842 tls->state = TOR_TLS_ST_CLOSED;
843 return TOR_TLS_CLOSE;
844 } else {
845 tor_assert(err != TOR_TLS_DONE);
846 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
847 return err;
851 /** Underlying function for TLS writing. Write up to <b>n</b>
852 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
853 * number of characters written. On failure, returns TOR_TLS_ERROR,
854 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
857 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
859 int r, err;
860 tor_assert(tls);
861 tor_assert(tls->ssl);
862 tor_assert(tls->state == TOR_TLS_ST_OPEN);
863 if (n == 0)
864 return 0;
865 if (tls->wantwrite_n) {
866 /* if WANTWRITE last time, we must use the _same_ n as before */
867 tor_assert(n >= tls->wantwrite_n);
868 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
869 (int)n, (int)tls->wantwrite_n);
870 n = tls->wantwrite_n;
871 tls->wantwrite_n = 0;
873 r = SSL_write(tls->ssl, cp, n);
874 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
875 if (err == TOR_TLS_DONE) {
876 return r;
878 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
879 tls->wantwrite_n = n;
881 return err;
884 /** Perform initial handshake on <b>tls</b>. When finished, returns
885 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
886 * or TOR_TLS_WANTWRITE.
889 tor_tls_handshake(tor_tls_t *tls)
891 int r;
892 tor_assert(tls);
893 tor_assert(tls->ssl);
894 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
895 check_no_tls_errors();
896 if (tls->isServer) {
897 r = SSL_accept(tls->ssl);
898 } else {
899 r = SSL_connect(tls->ssl);
901 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
902 if (ERR_peek_error() != 0) {
903 tls_log_errors(tls->isServer ? LOG_INFO : LOG_WARN,
904 "handshaking");
905 return TOR_TLS_ERROR_MISC;
907 if (r == TOR_TLS_DONE) {
908 tls->state = TOR_TLS_ST_OPEN;
909 if (tls->isServer) {
910 SSL_set_info_callback(tls->ssl, NULL);
911 SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, always_accept_verify_cb);
912 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
913 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
914 #ifdef V2_HANDSHAKE_SERVER
915 if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
916 /* This check is redundant, but back when we did it in the callback,
917 * we might have not been able to look up the tor_tls_t if the code
918 * was buggy. Fixing that. */
919 if (!tls->wasV2Handshake) {
920 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
921 " get set. Fixing that.");
923 tls->wasV2Handshake = 1;
924 } else {
925 tls->wasV2Handshake = 0;
927 #endif
928 } else {
929 #ifdef V2_HANDSHAKE_CLIENT
930 /* If we got no ID cert, we're a v2 handshake. */
931 X509 *cert = SSL_get_peer_certificate(tls->ssl);
932 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
933 int n_certs = sk_X509_num(chain);
934 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
935 tls->wasV2Handshake = 0;
936 else {
937 log_notice(LD_NET, "I think I got a v2 handshake on %p!", tls);
938 tls->wasV2Handshake = 1;
940 if (cert)
941 X509_free(cert);
942 #endif
943 SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
946 return r;
949 /** Client only: Renegotiate a TLS session. When finished, returns
950 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
951 * TOR_TLS_WANTWRITE.
954 tor_tls_renegotiate(tor_tls_t *tls)
956 int r;
957 tor_assert(tls);
958 /* We could do server-initiated renegotiation too, but that would be tricky.
959 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
960 tor_assert(!tls->isServer);
961 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
962 int r = SSL_renegotiate(tls->ssl);
963 if (r <= 0) {
964 return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
965 "renegotiating", LOG_WARN);
967 tls->state = TOR_TLS_ST_RENEGOTIATE;
969 r = SSL_do_handshake(tls->ssl);
970 if (r == 1) {
971 tls->state = TOR_TLS_ST_OPEN;
972 return TOR_TLS_DONE;
973 } else
974 return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
975 "renegotiating handshake", LOG_WARN);
978 /** Shut down an open tls connection <b>tls</b>. When finished, returns
979 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
980 * or TOR_TLS_WANTWRITE.
983 tor_tls_shutdown(tor_tls_t *tls)
985 int r, err;
986 char buf[128];
987 tor_assert(tls);
988 tor_assert(tls->ssl);
990 while (1) {
991 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
992 /* If we've already called shutdown once to send a close message,
993 * we read until the other side has closed too.
995 do {
996 r = SSL_read(tls->ssl, buf, 128);
997 } while (r>0);
998 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
999 LOG_INFO);
1000 if (err == _TOR_TLS_ZERORETURN) {
1001 tls->state = TOR_TLS_ST_GOTCLOSE;
1002 /* fall through... */
1003 } else {
1004 return err;
1008 r = SSL_shutdown(tls->ssl);
1009 if (r == 1) {
1010 /* If shutdown returns 1, the connection is entirely closed. */
1011 tls->state = TOR_TLS_ST_CLOSED;
1012 return TOR_TLS_DONE;
1014 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1015 LOG_INFO);
1016 if (err == _TOR_TLS_SYSCALL) {
1017 /* The underlying TCP connection closed while we were shutting down. */
1018 tls->state = TOR_TLS_ST_CLOSED;
1019 return TOR_TLS_DONE;
1020 } else if (err == _TOR_TLS_ZERORETURN) {
1021 /* The TLS connection says that it sent a shutdown record, but
1022 * isn't done shutting down yet. Make sure that this hasn't
1023 * happened before, then go back to the start of the function
1024 * and try to read.
1026 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1027 tls->state == TOR_TLS_ST_SENTCLOSE) {
1028 log(LOG_WARN, LD_NET,
1029 "TLS returned \"half-closed\" value while already half-closed");
1030 return TOR_TLS_ERROR_MISC;
1032 tls->state = TOR_TLS_ST_SENTCLOSE;
1033 /* fall through ... */
1034 } else {
1035 return err;
1037 } /* end loop */
1040 /** Return true iff this TLS connection is authenticated.
1043 tor_tls_peer_has_cert(tor_tls_t *tls)
1045 X509 *cert;
1046 cert = SSL_get_peer_certificate(tls->ssl);
1047 tls_log_errors(LOG_WARN, "getting peer certificate");
1048 if (!cert)
1049 return 0;
1050 X509_free(cert);
1051 return 1;
1054 /** Warn that a certificate lifetime extends through a certain range. */
1055 static void
1056 log_cert_lifetime(X509 *cert, const char *problem)
1058 BIO *bio = NULL;
1059 BUF_MEM *buf;
1060 char *s1=NULL, *s2=NULL;
1061 char mytime[33];
1062 time_t now = time(NULL);
1063 struct tm tm;
1065 if (problem)
1066 log_warn(LD_GENERAL,
1067 "Certificate %s: is your system clock set incorrectly?",
1068 problem);
1070 if (!(bio = BIO_new(BIO_s_mem()))) {
1071 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1073 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1074 tls_log_errors(LOG_WARN, "printing certificate lifetime");
1075 goto end;
1077 BIO_get_mem_ptr(bio, &buf);
1078 s1 = tor_strndup(buf->data, buf->length);
1080 (void)BIO_reset(bio);
1081 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1082 tls_log_errors(LOG_WARN, "printing certificate lifetime");
1083 goto end;
1085 BIO_get_mem_ptr(bio, &buf);
1086 s2 = tor_strndup(buf->data, buf->length);
1088 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1090 log_warn(LD_GENERAL,
1091 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1092 s1,s2,mytime);
1094 end:
1095 /* Not expected to get invoked */
1096 tls_log_errors(LOG_WARN, "getting certificate lifetime");
1097 if (bio)
1098 BIO_free(bio);
1099 if (s1)
1100 tor_free(s1);
1101 if (s2)
1102 tor_free(s2);
1105 /** DOCDOC helper.
1106 * cert_out needs to be freed. id_cert_out doesn't. */
1107 static void
1108 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1109 X509 **cert_out, X509 **id_cert_out)
1111 X509 *cert = NULL, *id_cert = NULL;
1112 STACK_OF(X509) *chain = NULL;
1113 int num_in_chain, i;
1114 *cert_out = *id_cert_out = NULL;
1116 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1117 return;
1118 *cert_out = cert;
1119 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1120 return;
1121 num_in_chain = sk_X509_num(chain);
1122 /* 1 means we're receiving (server-side), and it's just the id_cert.
1123 * 2 means we're connecting (client-side), and it's both the link
1124 * cert and the id_cert.
1126 if (num_in_chain < 1) {
1127 log_fn(severity,LD_PROTOCOL,
1128 "Unexpected number of certificates in chain (%d)",
1129 num_in_chain);
1130 return;
1132 for (i=0; i<num_in_chain; ++i) {
1133 id_cert = sk_X509_value(chain, i);
1134 if (X509_cmp(id_cert, cert) != 0)
1135 break;
1137 *id_cert_out = id_cert;
1140 /** If the provided tls connection is authenticated and has a
1141 * certificate that is currently valid and signed, then set
1142 * *<b>identity_key</b> to the identity certificate's key and return
1143 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1146 tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1148 X509 *cert = NULL, *id_cert = NULL;
1149 EVP_PKEY *id_pkey = NULL;
1150 RSA *rsa;
1151 int r = -1;
1153 *identity_key = NULL;
1155 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1156 if (!cert)
1157 goto done;
1158 if (!id_cert) {
1159 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1160 goto done;
1162 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1163 X509_verify(cert, id_pkey) <= 0) {
1164 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1165 tls_log_errors(severity,"verifying certificate");
1166 goto done;
1169 rsa = EVP_PKEY_get1_RSA(id_pkey);
1170 if (!rsa)
1171 goto done;
1172 *identity_key = _crypto_new_pk_env_rsa(rsa);
1174 r = 0;
1176 done:
1177 if (cert)
1178 X509_free(cert);
1179 if (id_pkey)
1180 EVP_PKEY_free(id_pkey);
1182 /* This should never get invoked, but let's make sure in case OpenSSL
1183 * acts unexpectedly. */
1184 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
1186 return r;
1189 /** Check whether the certificate set on the connection <b>tls</b> is
1190 * expired or not-yet-valid, give or take <b>tolerance</b>
1191 * seconds. Return 0 for valid, -1 for failure.
1193 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1196 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1198 time_t now, t;
1199 X509 *cert;
1200 int r = -1;
1202 now = time(NULL);
1204 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1205 goto done;
1207 t = now + tolerance;
1208 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1209 log_cert_lifetime(cert, "not yet valid");
1210 goto done;
1212 t = now - tolerance;
1213 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1214 log_cert_lifetime(cert, "already expired");
1215 goto done;
1218 r = 0;
1219 done:
1220 if (cert)
1221 X509_free(cert);
1222 /* Not expected to get invoked */
1223 tls_log_errors(LOG_WARN, "checking certificate lifetime");
1225 return r;
1228 /** Return the number of bytes available for reading from <b>tls</b>.
1231 tor_tls_get_pending_bytes(tor_tls_t *tls)
1233 tor_assert(tls);
1234 return SSL_pending(tls->ssl);
1237 /** If <b>tls</b> requires that the next write be of a particular size,
1238 * return that size. Otherwise, return 0. */
1239 size_t
1240 tor_tls_get_forced_write_size(tor_tls_t *tls)
1242 return tls->wantwrite_n;
1245 /** Sets n_read and n_written to the number of bytes read and written,
1246 * respectivey, on the raw socket used by <b>tls</b> since the last time this
1247 * function was called on <b>tls</b>. */
1248 void
1249 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1251 unsigned long r, w;
1252 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1253 w = BIO_number_written(SSL_get_wbio(tls->ssl));
1255 /* We are ok with letting these unsigned ints go "negative" here:
1256 * If we wrapped around, this should still give us the right answer, unless
1257 * we wrapped around by more than ULONG_MAX since the last time we called
1258 * this function.
1261 *n_read = (size_t)(r - tls->last_read_count);
1262 *n_written = (size_t)(w - tls->last_write_count);
1263 tls->last_read_count = r;
1264 tls->last_write_count = w;
1267 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1268 * errors, log an error message. */
1269 void
1270 _check_no_tls_errors(const char *fname, int line)
1272 if (ERR_peek_error() == 0)
1273 return;
1274 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1275 tor_fix_source_file(fname), line);
1276 tls_log_errors(LOG_WARN, NULL);
1279 /**DOCDOC */
1281 tor_tls_used_v1_handshake(tor_tls_t *tls)
1283 if (tls->isServer) {
1284 #ifdef V2_HANDSHAKE_SERVER
1285 return ! tls->wasV2Handshake;
1286 #endif
1287 } else {
1288 #ifdef V2_HANDSHAKE_CLIENT
1289 return ! tls->wasV2Handshake;
1290 #endif
1292 return 1;