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 */
8 * \brief Wrapper functions to present a consistent interface to
9 * TLS, SSL, and X.509 functions from OpenSSL.
12 /* (Unlike other tor functions, these
13 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
14 * functions and variables.)
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"
32 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
38 #include "container.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 /** Structure holding the TLS state for a single connection. */
57 typedef struct tor_tls_context_t
{
65 /** Holds a SSL object and its associated data. Members are only
66 * accessed from within tortls.c.
69 HT_ENTRY(tor_tls_t
) node
;
70 tor_tls_context_t
*context
; /** A link to the context object for this tls. */
71 SSL
*ssl
; /**< An OpenSSL SSL object. */
72 int socket
; /**< The underlying file descriptor for this TLS connection. */
73 char *address
; /**< An address to log when describing this connection. */
75 TOR_TLS_ST_HANDSHAKE
, TOR_TLS_ST_OPEN
, TOR_TLS_ST_GOTCLOSE
,
76 TOR_TLS_ST_SENTCLOSE
, TOR_TLS_ST_CLOSED
, TOR_TLS_ST_RENEGOTIATE
,
77 } state
: 3; /**< The current SSL state, depending on which operations have
78 * completed successfully. */
79 unsigned int isServer
:1; /**< True iff this is a server-side connection */
80 unsigned int wasV2Handshake
:1; /**< True iff the original handshake for
81 * this connection used the updated version
82 * of the connection protocol (client sends
83 * different cipher list, server sends only
84 * one certificate). */
85 /** True iff we should call negotiated_callback when we're done reading. */
86 unsigned int got_renegotiate
:1;
87 size_t wantwrite_n
; /**< 0 normally, >0 if we returned wantwrite last
89 /** Last values retrieved from BIO_number_read()/write(); see
90 * tor_tls_get_n_raw_bytes() for usage.
92 unsigned long last_write_count
;
93 unsigned long last_read_count
;
94 /** If set, a callback to invoke whenever the client tries to renegotiate
96 void (*negotiated_callback
)(tor_tls_t
*tls
, void *arg
);
97 /** Argument to pass to negotiated_callback. */
101 #ifdef V2_HANDSHAKE_CLIENT
102 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
103 * in client mode into advertising the ciphers we want. See
104 * rectify_client_ciphers() for details. */
105 static SSL_CIPHER
*CLIENT_CIPHER_DUMMIES
= NULL
;
106 /** A stack of SSL_CIPHER objects, some real, some fake.
107 * See rectify_client_ciphers() for details. */
108 static STACK_OF(SSL_CIPHER
) *CLIENT_CIPHER_STACK
= NULL
;
111 /** Helper: compare tor_tls_t objects by its SSL. */
113 tor_tls_entries_eq(const tor_tls_t
*a
, const tor_tls_t
*b
)
115 return a
->ssl
== b
->ssl
;
118 /** Helper: return a hash value for a tor_tls_t by its SSL. */
119 static INLINE
unsigned int
120 tor_tls_entry_hash(const tor_tls_t
*a
)
122 #if SIZEOF_INT == SIZEOF_VOID_P
123 return ((unsigned int)(uintptr_t)a
->ssl
);
125 return (unsigned int) ((((uint64_t)a
->ssl
)>>2) & UINT_MAX
);
129 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
131 static HT_HEAD(tlsmap
, tor_tls_t
) tlsmap_root
= HT_INITIALIZER();
133 HT_PROTOTYPE(tlsmap
, tor_tls_t
, node
, tor_tls_entry_hash
,
135 HT_GENERATE(tlsmap
, tor_tls_t
, node
, tor_tls_entry_hash
,
136 tor_tls_entries_eq
, 0.6, malloc
, realloc
, free
)
138 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
140 static INLINE tor_tls_t
*
141 tor_tls_get_by_ssl(const SSL
*ssl
)
143 tor_tls_t search
, *result
;
144 memset(&search
, 0, sizeof(search
));
145 search
.ssl
= (SSL
*)ssl
;
146 result
= HT_FIND(tlsmap
, &tlsmap_root
, &search
);
150 static void tor_tls_context_decref(tor_tls_context_t
*ctx
);
151 static void tor_tls_context_incref(tor_tls_context_t
*ctx
);
152 static X509
* tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
153 crypto_pk_env_t
*rsa_sign
,
155 const char *cname_sign
,
156 unsigned int lifetime
);
158 /** Global tls context. We keep it here because nobody else needs to
160 static tor_tls_context_t
*global_tls_context
= NULL
;
161 /** True iff tor_tls_init() has been called. */
162 static int tls_library_is_initialized
= 0;
164 /* Module-internal error codes. */
165 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
166 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
168 /** Log all pending tls errors at level <b>severity</b>. Use
169 * <b>doing</b> to describe our current activities.
172 tls_log_errors(tor_tls_t
*tls
, int severity
, const char *doing
)
175 const char *msg
, *lib
, *func
, *addr
;
176 addr
= tls
? tls
->address
: NULL
;
177 while ((err
= ERR_get_error()) != 0) {
178 msg
= (const char*)ERR_reason_error_string(err
);
179 lib
= (const char*)ERR_lib_error_string(err
);
180 func
= (const char*)ERR_func_error_string(err
);
181 if (!msg
) msg
= "(null)";
183 log(severity
, LD_NET
, "TLS error while %s%s%s: %s (in %s:%s)",
184 doing
, addr
?" with ":"", addr
?addr
:"",
187 log(severity
, LD_NET
, "TLS error%s%s: %s (in %s:%s)",
188 addr
?" with ":"", addr
?addr
:"",
194 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
197 tor_errno_to_tls_error(int e
)
199 #if defined(MS_WINDOWS)
201 case WSAECONNRESET
: // most common
202 return TOR_TLS_ERROR_CONNRESET
;
204 return TOR_TLS_ERROR_TIMEOUT
;
206 case WSAEHOSTUNREACH
:
207 return TOR_TLS_ERROR_NO_ROUTE
;
208 case WSAECONNREFUSED
:
209 return TOR_TLS_ERROR_CONNREFUSED
; // least common
211 return TOR_TLS_ERROR_MISC
;
215 case ECONNRESET
: // most common
216 return TOR_TLS_ERROR_CONNRESET
;
218 return TOR_TLS_ERROR_TIMEOUT
;
221 return TOR_TLS_ERROR_NO_ROUTE
;
223 return TOR_TLS_ERROR_CONNREFUSED
; // least common
225 return TOR_TLS_ERROR_MISC
;
230 /** Given a TOR_TLS_* error code, return a string equivalent. */
232 tor_tls_err_to_string(int err
)
235 return "[Not an error.]";
237 case TOR_TLS_ERROR_MISC
: return "misc error";
238 case TOR_TLS_ERROR_IO
: return "unexpected close";
239 case TOR_TLS_ERROR_CONNREFUSED
: return "connection refused";
240 case TOR_TLS_ERROR_CONNRESET
: return "connection reset";
241 case TOR_TLS_ERROR_NO_ROUTE
: return "host unreachable";
242 case TOR_TLS_ERROR_TIMEOUT
: return "connection timed out";
243 case TOR_TLS_CLOSE
: return "closed";
244 case TOR_TLS_WANTREAD
: return "want to read";
245 case TOR_TLS_WANTWRITE
: return "want to write";
246 default: return "(unknown error code)";
250 #define CATCH_SYSCALL 1
253 /** Given a TLS object and the result of an SSL_* call, use
254 * SSL_get_error to determine whether an error has occurred, and if so
255 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
256 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
257 * reporting syscall errors. If extra&CATCH_ZERO is true, return
258 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
260 * If an error has occurred, log it at level <b>severity</b> and describe the
261 * current action as <b>doing</b>.
264 tor_tls_get_error(tor_tls_t
*tls
, int r
, int extra
,
265 const char *doing
, int severity
)
267 int err
= SSL_get_error(tls
->ssl
, r
);
268 int tor_error
= TOR_TLS_ERROR_MISC
;
272 case SSL_ERROR_WANT_READ
:
273 return TOR_TLS_WANTREAD
;
274 case SSL_ERROR_WANT_WRITE
:
275 return TOR_TLS_WANTWRITE
;
276 case SSL_ERROR_SYSCALL
:
277 if (extra
&CATCH_SYSCALL
)
278 return _TOR_TLS_SYSCALL
;
280 log(severity
, LD_NET
, "TLS error: unexpected close while %s", doing
);
281 tor_error
= TOR_TLS_ERROR_IO
;
283 int e
= tor_socket_errno(tls
->socket
);
284 log(severity
, LD_NET
,
285 "TLS error: <syscall error while %s> (errno=%d: %s)",
286 doing
, e
, tor_socket_strerror(e
));
287 tor_error
= tor_errno_to_tls_error(e
);
289 tls_log_errors(tls
, severity
, doing
);
291 case SSL_ERROR_ZERO_RETURN
:
292 if (extra
&CATCH_ZERO
)
293 return _TOR_TLS_ZERORETURN
;
294 log(severity
, LD_NET
, "TLS connection closed while %s", doing
);
295 tls_log_errors(tls
, severity
, doing
);
296 return TOR_TLS_CLOSE
;
298 tls_log_errors(tls
, severity
, doing
);
299 return TOR_TLS_ERROR_MISC
;
303 /** Initialize OpenSSL, unless it has already been initialized.
308 if (!tls_library_is_initialized
) {
310 SSL_load_error_strings();
311 crypto_global_init(-1);
312 tls_library_is_initialized
= 1;
316 /** Free all global TLS structures. */
318 tor_tls_free_all(void)
320 if (global_tls_context
) {
321 tor_tls_context_decref(global_tls_context
);
322 global_tls_context
= NULL
;
324 if (!HT_EMPTY(&tlsmap_root
)) {
325 log_warn(LD_MM
, "Still have entries in the tlsmap at shutdown.");
327 HT_CLEAR(tlsmap
, &tlsmap_root
);
328 #ifdef V2_HANDSHAKE_CLIENT
329 if (CLIENT_CIPHER_DUMMIES
)
330 tor_free(CLIENT_CIPHER_DUMMIES
);
331 if (CLIENT_CIPHER_STACK
)
332 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK
);
336 /** We need to give OpenSSL a callback to verify certificates. This is
337 * it: We always accept peer certs and complete the handshake. We
338 * don't validate them until later.
341 always_accept_verify_cb(int preverify_ok
,
342 X509_STORE_CTX
*x509_ctx
)
349 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
351 tor_x509_name_new(const char *cname
)
355 if (!(name
= X509_NAME_new()))
357 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
358 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
359 (unsigned char*)cname
, -1, -1, 0)))
363 X509_NAME_free(name
);
367 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
368 * signed by the private key <b>rsa_sign</b>. The commonName of the
369 * certificate will be <b>cname</b>; the commonName of the issuer will be
370 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
371 * starting from now. Return a certificate on success, NULL on
375 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
376 crypto_pk_env_t
*rsa_sign
,
378 const char *cname_sign
,
379 unsigned int cert_lifetime
)
381 time_t start_time
, end_time
;
382 EVP_PKEY
*sign_pkey
= NULL
, *pkey
=NULL
;
384 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
388 start_time
= time(NULL
);
392 tor_assert(rsa_sign
);
393 tor_assert(cname_sign
);
394 if (!(sign_pkey
= _crypto_pk_env_get_evp_pkey(rsa_sign
,1)))
396 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
398 if (!(x509
= X509_new()))
400 if (!(X509_set_version(x509
, 2)))
402 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
405 if (!(name
= tor_x509_name_new(cname
)))
407 if (!(X509_set_subject_name(x509
, name
)))
409 if (!(name_issuer
= tor_x509_name_new(cname_sign
)))
411 if (!(X509_set_issuer_name(x509
, name_issuer
)))
414 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
416 end_time
= start_time
+ cert_lifetime
;
417 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
419 if (!X509_set_pubkey(x509
, pkey
))
421 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
431 tls_log_errors(NULL
, LOG_WARN
, "generating certificate");
433 EVP_PKEY_free(sign_pkey
);
437 X509_NAME_free(name
);
439 X509_NAME_free(name_issuer
);
443 /** List of ciphers that servers should select from.*/
444 #define SERVER_CIPHER_LIST \
445 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
446 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
447 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
448 /* Note: for setting up your own private testing network with link crypto
449 * disabled, set the cipher lists to your cipher list to
450 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
451 * with any of the "real" Tors, though. */
453 #ifdef V2_HANDSHAKE_CLIENT
454 #define CIPHER(id, name) name ":"
455 #define XCIPHER(id, name)
456 /** List of ciphers that clients should advertise, omitting items that
457 * our OpenSSL doesn't know about. */
458 static const char CLIENT_CIPHER_LIST
[] =
459 #include "./ciphers.inc"
464 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
465 typedef struct cipher_info_t
{ unsigned id
; const char *name
; } cipher_info_t
;
466 /** A list of all the ciphers that clients should advertise, including items
467 * that OpenSSL might not know about. */
468 static const cipher_info_t CLIENT_CIPHER_INFO_LIST
[] = {
469 #define CIPHER(id, name) { id, name },
470 #define XCIPHER(id, name) { id, #name },
471 #include "./ciphers.inc"
476 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
477 static const int N_CLIENT_CIPHERS
=
478 sizeof(CLIENT_CIPHER_INFO_LIST
)/sizeof(CLIENT_CIPHER_INFO_LIST
[0]);
481 #ifndef V2_HANDSHAKE_CLIENT
482 #undef CLIENT_CIPHER_LIST
483 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
484 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
487 /** Remove a reference to <b>ctx</b>, and free it if it has no more
490 tor_tls_context_decref(tor_tls_context_t
*ctx
)
493 if (--ctx
->refcnt
== 0) {
494 SSL_CTX_free(ctx
->ctx
);
495 X509_free(ctx
->my_cert
);
496 X509_free(ctx
->my_id_cert
);
497 crypto_free_pk_env(ctx
->key
);
502 /** Increase the reference count of <b>ctx</b>. */
504 tor_tls_context_incref(tor_tls_context_t
*ctx
)
509 /** Create a new TLS context for use with Tor TLS handshakes.
510 * <b>identity</b> should be set to the identity key used to sign the
511 * certificate, and <b>nickname</b> set to the nickname to use.
513 * You can call this function multiple times. Each time you call it,
514 * it generates new certificates; all new connections will use
515 * the new SSL context.
518 tor_tls_context_new(crypto_pk_env_t
*identity
, unsigned int key_lifetime
)
520 crypto_pk_env_t
*rsa
= NULL
;
521 EVP_PKEY
*pkey
= NULL
;
522 tor_tls_context_t
*result
= NULL
;
523 X509
*cert
= NULL
, *idcert
= NULL
;
524 char *nickname
= NULL
, *nn2
= NULL
;
527 nickname
= crypto_random_hostname(8, 20, "www.", ".net");
528 nn2
= crypto_random_hostname(8, 20, "www.", ".net");
530 /* Generate short-term RSA key. */
531 if (!(rsa
= crypto_new_pk_env()))
533 if (crypto_pk_generate_key(rsa
)<0)
535 /* Create certificate signed by identity key. */
536 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
538 /* Create self-signed certificate for identity key. */
539 idcert
= tor_tls_create_certificate(identity
, identity
, nn2
, nn2
,
540 IDENTITY_CERT_LIFETIME
);
541 if (!cert
|| !idcert
) {
542 log(LOG_WARN
, LD_CRYPTO
, "Error creating certificate");
546 result
= tor_malloc_zero(sizeof(tor_tls_context_t
));
548 result
->my_cert
= X509_dup(cert
);
549 result
->my_id_cert
= X509_dup(idcert
);
550 result
->key
= crypto_pk_dup_key(rsa
);
552 #ifdef EVERYONE_HAS_AES
553 /* Tell OpenSSL to only use TLS1 */
554 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
557 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
558 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
560 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
562 SSL_CTX_set_options(result
->ctx
, SSL_OP_SINGLE_DH_USE
);
564 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
565 SSL_CTX_set_options(result
->ctx
,
566 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
);
568 /* Don't actually allow compression; it uses ram and time, but the data
569 * we transmit is all encrypted anyway. */
570 if (result
->ctx
->comp_methods
)
571 result
->ctx
->comp_methods
= NULL
;
572 #ifdef SSL_MODE_RELEASE_BUFFERS
573 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_RELEASE_BUFFERS
);
575 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
577 X509_free(cert
); /* We just added a reference to cert. */
580 X509_STORE
*s
= SSL_CTX_get_cert_store(result
->ctx
);
582 X509_STORE_add_cert(s
, idcert
);
583 X509_free(idcert
); /* The context now owns the reference to idcert */
586 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
588 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
590 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
594 if (!SSL_CTX_check_private_key(result
->ctx
))
597 crypto_dh_env_t
*dh
= crypto_dh_new();
598 SSL_CTX_set_tmp_dh(result
->ctx
, _crypto_dh_env_get_dh(dh
));
601 SSL_CTX_set_verify(result
->ctx
, SSL_VERIFY_PEER
,
602 always_accept_verify_cb
);
603 /* let us realloc bufs that we're writing from */
604 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
605 /* Free the old context if one exists. */
606 if (global_tls_context
) {
607 /* This is safe even if there are open connections: OpenSSL does
608 * reference counting with SSL and SSL_CTX objects. */
609 tor_tls_context_decref(global_tls_context
);
611 global_tls_context
= result
;
613 crypto_free_pk_env(rsa
);
619 tls_log_errors(NULL
, LOG_WARN
, "creating TLS context");
625 crypto_free_pk_env(rsa
);
627 tor_tls_context_decref(result
);
635 #ifdef V2_HANDSHAKE_SERVER
636 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
637 * a list that indicates that the client knows how to do the v2 TLS connection
640 tor_tls_client_is_using_v2_ciphers(const SSL
*ssl
, const char *address
)
643 SSL_SESSION
*session
;
644 /* If we reached this point, we just got a client hello. See if there is
646 if (!(session
= SSL_get_session((SSL
*)ssl
))) {
647 log_warn(LD_NET
, "No session on TLS?");
650 if (!session
->ciphers
) {
651 log_warn(LD_NET
, "No ciphers on session");
654 /* Now we need to see if there are any ciphers whose presence means we're
655 * dealing with an updated Tor. */
656 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
657 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
658 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
659 if (strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
) &&
660 strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA
) &&
661 strcmp(ciphername
, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
) &&
662 strcmp(ciphername
, "(NONE)")) {
663 /* XXXX should be ld_debug */
664 log_info(LD_NET
, "Got a non-version-1 cipher called '%s'", ciphername
);
672 smartlist_t
*elts
= smartlist_create();
674 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
675 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
676 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
677 smartlist_add(elts
, (char*)ciphername
);
679 s
= smartlist_join_strings(elts
, ":", 0, NULL
);
680 log_info(LD_NET
, "Got a non-version-1 cipher list from %s. It is: '%s'",
683 smartlist_free(elts
);
688 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
689 * changes state. We use this:
690 * <ul><li>To alter the state of the handshake partway through, so we
691 * do not send or request extra certificates in v2 handshakes.</li>
692 * <li>To detect renegotiation</li></ul>
695 tor_tls_server_info_callback(const SSL
*ssl
, int type
, int val
)
699 if (type
!= SSL_CB_ACCEPT_LOOP
)
701 if (ssl
->state
!= SSL3_ST_SW_SRVR_HELLO_A
)
704 tls
= tor_tls_get_by_ssl(ssl
);
706 /* Check whether we're watching for renegotiates. If so, this is one! */
707 if (tls
->negotiated_callback
)
708 tls
->got_renegotiate
= 1;
710 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
713 /* Now check the cipher list. */
714 if (tor_tls_client_is_using_v2_ciphers(ssl
, ADDR(tls
))) {
715 /*XXXX_TLS keep this from happening more than once! */
717 /* Yes, we're casting away the const from ssl. This is very naughty of us.
718 * Let's hope openssl doesn't notice! */
720 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
721 SSL_set_mode((SSL
*) ssl
, SSL_MODE_NO_AUTO_CHAIN
);
722 /* Don't send a hello request. */
723 SSL_set_verify((SSL
*) ssl
, SSL_VERIFY_NONE
, NULL
);
726 tls
->wasV2Handshake
= 1;
728 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
734 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
735 * a list designed to mimic a common web browser. Some of the ciphers in the
736 * list won't actually be implemented by OpenSSL: that's okay so long as the
737 * server doesn't select them, and the server won't select anything besides
738 * what's in SERVER_CIPHER_LIST.
740 * [If the server <b>does</b> select a bogus cipher, we won't crash or
741 * anything; we'll just fail later when we try to look up the cipher in
742 * ssl->cipher_list_by_id.]
745 rectify_client_ciphers(STACK_OF(SSL_CIPHER
) **ciphers
)
747 #ifdef V2_HANDSHAKE_CLIENT
748 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK
)) {
749 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
753 /* First, create a dummy SSL_CIPHER for every cipher. */
754 CLIENT_CIPHER_DUMMIES
=
755 tor_malloc_zero(sizeof(SSL_CIPHER
)*N_CLIENT_CIPHERS
);
756 for (i
=0; i
< N_CLIENT_CIPHERS
; ++i
) {
757 CLIENT_CIPHER_DUMMIES
[i
].valid
= 1;
758 CLIENT_CIPHER_DUMMIES
[i
].id
= CLIENT_CIPHER_INFO_LIST
[i
].id
| (3<<24);
759 CLIENT_CIPHER_DUMMIES
[i
].name
= CLIENT_CIPHER_INFO_LIST
[i
].name
;
762 CLIENT_CIPHER_STACK
= sk_SSL_CIPHER_new_null();
763 tor_assert(CLIENT_CIPHER_STACK
);
765 log_debug(LD_NET
, "List was: %s", CLIENT_CIPHER_LIST
);
766 for (j
= 0; j
< sk_SSL_CIPHER_num(*ciphers
); ++j
) {
767 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
768 log_debug(LD_NET
, "Cipher %d: %lx %s", j
, cipher
->id
, cipher
->name
);
771 /* Then copy as many ciphers as we can from the good list, inserting
772 * dummies as needed. */
774 for (i
= 0; i
< N_CLIENT_CIPHERS
; ) {
775 SSL_CIPHER
*cipher
= NULL
;
776 if (j
< sk_SSL_CIPHER_num(*ciphers
))
777 cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
778 if (cipher
&& ((cipher
->id
>> 24) & 0xff) != 3) {
779 log_debug(LD_NET
, "Skipping v2 cipher %s", cipher
->name
);
782 (cipher
->id
& 0xffff) == CLIENT_CIPHER_INFO_LIST
[i
].id
) {
783 log_debug(LD_NET
, "Found cipher %s", cipher
->name
);
784 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, cipher
);
788 log_debug(LD_NET
, "Inserting fake %s", CLIENT_CIPHER_DUMMIES
[i
].name
);
789 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, &CLIENT_CIPHER_DUMMIES
[i
]);
795 sk_SSL_CIPHER_free(*ciphers
);
796 *ciphers
= sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK
);
797 tor_assert(*ciphers
);
804 /** Create a new TLS object from a file descriptor, and a flag to
805 * determine whether it is functioning as a server.
808 tor_tls_new(int sock
, int isServer
)
811 tor_tls_t
*result
= tor_malloc_zero(sizeof(tor_tls_t
));
813 tor_assert(global_tls_context
); /* make sure somebody made it first */
814 if (!(result
->ssl
= SSL_new(global_tls_context
->ctx
))) {
815 tls_log_errors(NULL
, LOG_WARN
, "generating TLS context");
820 #ifdef SSL_set_tlsext_host_name
821 /* Browsers use the TLS hostname extension, so we should too. */
823 char *fake_hostname
= crypto_random_hostname(4,25, "www.",".com");
824 SSL_set_tlsext_host_name(result
->ssl
, fake_hostname
);
825 tor_free(fake_hostname
);
829 if (!SSL_set_cipher_list(result
->ssl
,
830 isServer
? SERVER_CIPHER_LIST
: CLIENT_CIPHER_LIST
)) {
831 tls_log_errors(NULL
, LOG_WARN
, "setting ciphers");
832 SSL_free(result
->ssl
);
837 rectify_client_ciphers(&result
->ssl
->cipher_list
);
838 result
->socket
= sock
;
839 bio
= BIO_new_socket(sock
, BIO_NOCLOSE
);
841 tls_log_errors(NULL
, LOG_WARN
, "opening BIO");
842 SSL_free(result
->ssl
);
846 HT_INSERT(tlsmap
, &tlsmap_root
, result
);
847 SSL_set_bio(result
->ssl
, bio
, bio
);
848 tor_tls_context_incref(global_tls_context
);
849 result
->context
= global_tls_context
;
850 result
->state
= TOR_TLS_ST_HANDSHAKE
;
851 result
->isServer
= isServer
;
852 result
->wantwrite_n
= 0;
853 result
->last_write_count
= BIO_number_written(bio
);
854 result
->last_read_count
= BIO_number_read(bio
);
855 if (result
->last_write_count
|| result
->last_read_count
) {
856 log_warn(LD_NET
, "Newly created BIO has read count %lu, write count %lu",
857 result
->last_read_count
, result
->last_write_count
);
859 #ifdef V2_HANDSHAKE_SERVER
861 SSL_set_info_callback(result
->ssl
, tor_tls_server_info_callback
);
864 /* Not expected to get called. */
865 tls_log_errors(NULL
, LOG_WARN
, "generating TLS context");
869 /** Make future log messages about <b>tls</b> display the address
873 tor_tls_set_logged_address(tor_tls_t
*tls
, const char *address
)
876 tor_free(tls
->address
);
877 tls
->address
= tor_strdup(address
);
880 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
881 * next gets a client-side renegotiate in the middle of a read. Do not
882 * invoke this function until <em>after</em> initial handshaking is done!
885 tor_tls_set_renegotiate_callback(tor_tls_t
*tls
,
886 void (*cb
)(tor_tls_t
*, void *arg
),
889 tls
->negotiated_callback
= cb
;
890 tls
->callback_arg
= arg
;
891 tls
->got_renegotiate
= 0;
892 #ifdef V2_HANDSHAKE_SERVER
894 SSL_set_info_callback(tls
->ssl
, tor_tls_server_info_callback
);
896 SSL_set_info_callback(tls
->ssl
, NULL
);
901 /** Return whether this tls initiated the connect (client) or
902 * received it (server). */
904 tor_tls_is_server(tor_tls_t
*tls
)
907 return tls
->isServer
;
910 /** Release resources associated with a TLS object. Does not close the
911 * underlying file descriptor.
914 tor_tls_free(tor_tls_t
*tls
)
917 tor_assert(tls
&& tls
->ssl
);
918 removed
= HT_REMOVE(tlsmap
, &tlsmap_root
, tls
);
920 log_warn(LD_BUG
, "Freeing a TLS that was not in the ssl->tls map.");
924 tls
->negotiated_callback
= NULL
;
926 tor_tls_context_decref(tls
->context
);
927 tor_free(tls
->address
);
931 /** Underlying function for TLS reading. Reads up to <b>len</b>
932 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
933 * number of characters read. On failure, returns TOR_TLS_ERROR,
934 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
937 tor_tls_read(tor_tls_t
*tls
, char *cp
, size_t len
)
941 tor_assert(tls
->ssl
);
942 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
943 tor_assert(len
<INT_MAX
);
944 r
= SSL_read(tls
->ssl
, cp
, (int)len
);
946 #ifdef V2_HANDSHAKE_SERVER
947 if (tls
->got_renegotiate
) {
948 /* Renegotiation happened! */
949 log_info(LD_NET
, "Got a TLS renegotiation from %s", ADDR(tls
));
950 if (tls
->negotiated_callback
)
951 tls
->negotiated_callback(tls
, tls
->callback_arg
);
952 tls
->got_renegotiate
= 0;
957 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_DEBUG
);
958 if (err
== _TOR_TLS_ZERORETURN
|| err
== TOR_TLS_CLOSE
) {
959 log_debug(LD_NET
,"read returned r=%d; TLS is closed",r
);
960 tls
->state
= TOR_TLS_ST_CLOSED
;
961 return TOR_TLS_CLOSE
;
963 tor_assert(err
!= TOR_TLS_DONE
);
964 log_debug(LD_NET
,"read returned r=%d, err=%d",r
,err
);
969 /** Underlying function for TLS writing. Write up to <b>n</b>
970 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
971 * number of characters written. On failure, returns TOR_TLS_ERROR,
972 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
975 tor_tls_write(tor_tls_t
*tls
, const char *cp
, size_t n
)
979 tor_assert(tls
->ssl
);
980 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
981 tor_assert(n
< INT_MAX
);
984 if (tls
->wantwrite_n
) {
985 /* if WANTWRITE last time, we must use the _same_ n as before */
986 tor_assert(n
>= tls
->wantwrite_n
);
987 log_debug(LD_NET
,"resuming pending-write, (%d to flush, reusing %d)",
988 (int)n
, (int)tls
->wantwrite_n
);
989 n
= tls
->wantwrite_n
;
990 tls
->wantwrite_n
= 0;
992 r
= SSL_write(tls
->ssl
, cp
, (int)n
);
993 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
);
994 if (err
== TOR_TLS_DONE
) {
997 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
998 tls
->wantwrite_n
= n
;
1003 /** Perform initial handshake on <b>tls</b>. When finished, returns
1004 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1005 * or TOR_TLS_WANTWRITE.
1008 tor_tls_handshake(tor_tls_t
*tls
)
1012 tor_assert(tls
->ssl
);
1013 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
1014 check_no_tls_errors();
1015 if (tls
->isServer
) {
1016 r
= SSL_accept(tls
->ssl
);
1018 r
= SSL_connect(tls
->ssl
);
1020 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
);
1021 if (ERR_peek_error() != 0) {
1022 tls_log_errors(tls
, tls
->isServer
? LOG_INFO
: LOG_WARN
,
1024 return TOR_TLS_ERROR_MISC
;
1026 if (r
== TOR_TLS_DONE
) {
1027 tls
->state
= TOR_TLS_ST_OPEN
;
1028 if (tls
->isServer
) {
1029 SSL_set_info_callback(tls
->ssl
, NULL
);
1030 SSL_set_verify(tls
->ssl
, SSL_VERIFY_PEER
, always_accept_verify_cb
);
1031 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1032 tls
->ssl
->mode
&= ~SSL_MODE_NO_AUTO_CHAIN
;
1033 #ifdef V2_HANDSHAKE_SERVER
1034 if (tor_tls_client_is_using_v2_ciphers(tls
->ssl
, ADDR(tls
))) {
1035 /* This check is redundant, but back when we did it in the callback,
1036 * we might have not been able to look up the tor_tls_t if the code
1037 * was buggy. Fixing that. */
1038 if (!tls
->wasV2Handshake
) {
1039 log_warn(LD_BUG
, "For some reason, wasV2Handshake didn't"
1040 " get set. Fixing that.");
1042 tls
->wasV2Handshake
= 1;
1043 log_debug(LD_NET
, "Completed V2 TLS handshake with client; waiting "
1044 "for renegotiation.");
1046 tls
->wasV2Handshake
= 0;
1050 #ifdef V2_HANDSHAKE_CLIENT
1051 /* If we got no ID cert, we're a v2 handshake. */
1052 X509
*cert
= SSL_get_peer_certificate(tls
->ssl
);
1053 STACK_OF(X509
) *chain
= SSL_get_peer_cert_chain(tls
->ssl
);
1054 int n_certs
= sk_X509_num(chain
);
1055 if (n_certs
> 1 || (n_certs
== 1 && cert
!= sk_X509_value(chain
, 0)))
1056 tls
->wasV2Handshake
= 0;
1058 log_debug(LD_NET
, "Server sent back a single certificate; looks like "
1059 "a v2 handshake on %p.", tls
);
1060 tls
->wasV2Handshake
= 1;
1065 if (SSL_set_cipher_list(tls
->ssl
, SERVER_CIPHER_LIST
) == 0) {
1066 tls_log_errors(NULL
, LOG_WARN
, "re-setting ciphers");
1067 r
= TOR_TLS_ERROR_MISC
;
1074 /** Client only: Renegotiate a TLS session. When finished, returns
1075 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1076 * TOR_TLS_WANTWRITE.
1079 tor_tls_renegotiate(tor_tls_t
*tls
)
1083 /* We could do server-initiated renegotiation too, but that would be tricky.
1084 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1085 tor_assert(!tls
->isServer
);
1086 if (tls
->state
!= TOR_TLS_ST_RENEGOTIATE
) {
1087 int r
= SSL_renegotiate(tls
->ssl
);
1089 return tor_tls_get_error(tls
, r
, 0, "renegotiating", LOG_WARN
);
1091 tls
->state
= TOR_TLS_ST_RENEGOTIATE
;
1093 r
= SSL_do_handshake(tls
->ssl
);
1095 tls
->state
= TOR_TLS_ST_OPEN
;
1096 return TOR_TLS_DONE
;
1098 return tor_tls_get_error(tls
, r
, 0, "renegotiating handshake", LOG_INFO
);
1101 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1102 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1103 * or TOR_TLS_WANTWRITE.
1106 tor_tls_shutdown(tor_tls_t
*tls
)
1111 tor_assert(tls
->ssl
);
1114 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1115 /* If we've already called shutdown once to send a close message,
1116 * we read until the other side has closed too.
1119 r
= SSL_read(tls
->ssl
, buf
, 128);
1121 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
1123 if (err
== _TOR_TLS_ZERORETURN
) {
1124 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
1125 /* fall through... */
1131 r
= SSL_shutdown(tls
->ssl
);
1133 /* If shutdown returns 1, the connection is entirely closed. */
1134 tls
->state
= TOR_TLS_ST_CLOSED
;
1135 return TOR_TLS_DONE
;
1137 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
1139 if (err
== _TOR_TLS_SYSCALL
) {
1140 /* The underlying TCP connection closed while we were shutting down. */
1141 tls
->state
= TOR_TLS_ST_CLOSED
;
1142 return TOR_TLS_DONE
;
1143 } else if (err
== _TOR_TLS_ZERORETURN
) {
1144 /* The TLS connection says that it sent a shutdown record, but
1145 * isn't done shutting down yet. Make sure that this hasn't
1146 * happened before, then go back to the start of the function
1149 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
1150 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1151 log(LOG_WARN
, LD_NET
,
1152 "TLS returned \"half-closed\" value while already half-closed");
1153 return TOR_TLS_ERROR_MISC
;
1155 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
1156 /* fall through ... */
1163 /** Return true iff this TLS connection is authenticated.
1166 tor_tls_peer_has_cert(tor_tls_t
*tls
)
1169 cert
= SSL_get_peer_certificate(tls
->ssl
);
1170 tls_log_errors(tls
, LOG_WARN
, "getting peer certificate");
1177 /** Warn that a certificate lifetime extends through a certain range. */
1179 log_cert_lifetime(X509
*cert
, const char *problem
)
1183 char *s1
=NULL
, *s2
=NULL
;
1185 time_t now
= time(NULL
);
1189 log_warn(LD_GENERAL
,
1190 "Certificate %s: is your system clock set incorrectly?",
1193 if (!(bio
= BIO_new(BIO_s_mem()))) {
1194 log_warn(LD_GENERAL
, "Couldn't allocate BIO!"); goto end
;
1196 if (!(ASN1_TIME_print(bio
, X509_get_notBefore(cert
)))) {
1197 tls_log_errors(NULL
, LOG_WARN
, "printing certificate lifetime");
1200 BIO_get_mem_ptr(bio
, &buf
);
1201 s1
= tor_strndup(buf
->data
, buf
->length
);
1203 (void)BIO_reset(bio
);
1204 if (!(ASN1_TIME_print(bio
, X509_get_notAfter(cert
)))) {
1205 tls_log_errors(NULL
, LOG_WARN
, "printing certificate lifetime");
1208 BIO_get_mem_ptr(bio
, &buf
);
1209 s2
= tor_strndup(buf
->data
, buf
->length
);
1211 strftime(mytime
, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now
, &tm
));
1213 log_warn(LD_GENERAL
,
1214 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1218 /* Not expected to get invoked */
1219 tls_log_errors(NULL
, LOG_WARN
, "getting certificate lifetime");
1228 /** Helper function: try to extract a link certificate and an identity
1229 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1230 * *<b>id_cert_out</b> respectively. Log all messages at level
1233 * Note that a reference is added to cert_out, so it needs to be
1234 * freed. id_cert_out doesn't. */
1236 try_to_extract_certs_from_tls(int severity
, tor_tls_t
*tls
,
1237 X509
**cert_out
, X509
**id_cert_out
)
1239 X509
*cert
= NULL
, *id_cert
= NULL
;
1240 STACK_OF(X509
) *chain
= NULL
;
1241 int num_in_chain
, i
;
1242 *cert_out
= *id_cert_out
= NULL
;
1244 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1247 if (!(chain
= SSL_get_peer_cert_chain(tls
->ssl
)))
1249 num_in_chain
= sk_X509_num(chain
);
1250 /* 1 means we're receiving (server-side), and it's just the id_cert.
1251 * 2 means we're connecting (client-side), and it's both the link
1252 * cert and the id_cert.
1254 if (num_in_chain
< 1) {
1255 log_fn(severity
,LD_PROTOCOL
,
1256 "Unexpected number of certificates in chain (%d)",
1260 for (i
=0; i
<num_in_chain
; ++i
) {
1261 id_cert
= sk_X509_value(chain
, i
);
1262 if (X509_cmp(id_cert
, cert
) != 0)
1265 *id_cert_out
= id_cert
;
1268 /** If the provided tls connection is authenticated and has a
1269 * certificate chain that is currently valid and signed, then set
1270 * *<b>identity_key</b> to the identity certificate's key and return
1271 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1274 tor_tls_verify(int severity
, tor_tls_t
*tls
, crypto_pk_env_t
**identity_key
)
1276 X509
*cert
= NULL
, *id_cert
= NULL
;
1277 EVP_PKEY
*id_pkey
= NULL
;
1281 *identity_key
= NULL
;
1283 try_to_extract_certs_from_tls(severity
, tls
, &cert
, &id_cert
);
1287 log_fn(severity
,LD_PROTOCOL
,"No distinct identity certificate found");
1290 if (!(id_pkey
= X509_get_pubkey(id_cert
)) ||
1291 X509_verify(cert
, id_pkey
) <= 0) {
1292 log_fn(severity
,LD_PROTOCOL
,"X509_verify on cert and pkey returned <= 0");
1293 tls_log_errors(tls
, severity
,"verifying certificate");
1297 rsa
= EVP_PKEY_get1_RSA(id_pkey
);
1300 *identity_key
= _crypto_new_pk_env_rsa(rsa
);
1308 EVP_PKEY_free(id_pkey
);
1310 /* This should never get invoked, but let's make sure in case OpenSSL
1311 * acts unexpectedly. */
1312 tls_log_errors(tls
, LOG_WARN
, "finishing tor_tls_verify");
1317 /** Check whether the certificate set on the connection <b>tls</b> is
1318 * expired or not-yet-valid, give or take <b>tolerance</b>
1319 * seconds. Return 0 for valid, -1 for failure.
1321 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1324 tor_tls_check_lifetime(tor_tls_t
*tls
, int tolerance
)
1332 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1335 t
= now
+ tolerance
;
1336 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
1337 log_cert_lifetime(cert
, "not yet valid");
1340 t
= now
- tolerance
;
1341 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
1342 log_cert_lifetime(cert
, "already expired");
1350 /* Not expected to get invoked */
1351 tls_log_errors(tls
, LOG_WARN
, "checking certificate lifetime");
1356 /** Return the number of bytes available for reading from <b>tls</b>.
1359 tor_tls_get_pending_bytes(tor_tls_t
*tls
)
1362 return SSL_pending(tls
->ssl
);
1365 /** If <b>tls</b> requires that the next write be of a particular size,
1366 * return that size. Otherwise, return 0. */
1368 tor_tls_get_forced_write_size(tor_tls_t
*tls
)
1370 return tls
->wantwrite_n
;
1373 /** Sets n_read and n_written to the number of bytes read and written,
1374 * respectively, on the raw socket used by <b>tls</b> since the last time this
1375 * function was called on <b>tls</b>. */
1377 tor_tls_get_n_raw_bytes(tor_tls_t
*tls
, size_t *n_read
, size_t *n_written
)
1381 r
= BIO_number_read(SSL_get_rbio(tls
->ssl
));
1382 /* We want the number of bytes actually for real written. Unfortunately,
1383 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1384 * which makes the answer turn out wrong. Let's cope with that. Note
1385 * that this approach will fail if we ever replace tls->ssl's BIOs with
1386 * buffering bios for reasons of our own. As an alternative, we could
1387 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1388 * that would be tempting fate. */
1389 wbio
= SSL_get_wbio(tls
->ssl
);
1390 if (wbio
->method
== BIO_f_buffer() && (tmpbio
= BIO_next(wbio
)) != NULL
)
1392 w
= BIO_number_written(wbio
);
1394 /* We are ok with letting these unsigned ints go "negative" here:
1395 * If we wrapped around, this should still give us the right answer, unless
1396 * we wrapped around by more than ULONG_MAX since the last time we called
1399 *n_read
= (size_t)(r
- tls
->last_read_count
);
1400 *n_written
= (size_t)(w
- tls
->last_write_count
);
1401 if (*n_read
> INT_MAX
|| *n_written
> INT_MAX
) {
1402 log_warn(LD_BUG
, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1403 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1404 r
, tls
->last_read_count
, w
, tls
->last_write_count
);
1406 tls
->last_read_count
= r
;
1407 tls
->last_write_count
= w
;
1410 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1411 * errors, log an error message. */
1413 _check_no_tls_errors(const char *fname
, int line
)
1415 if (ERR_peek_error() == 0)
1417 log(LOG_WARN
, LD_CRYPTO
, "Unhandled OpenSSL errors found at %s:%d: ",
1418 tor_fix_source_file(fname
), line
);
1419 tls_log_errors(NULL
, LOG_WARN
, NULL
);
1422 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1423 * TLS handshake. Output is undefined if the handshake isn't finished. */
1425 tor_tls_used_v1_handshake(tor_tls_t
*tls
)
1427 if (tls
->isServer
) {
1428 #ifdef V2_HANDSHAKE_SERVER
1429 return ! tls
->wasV2Handshake
;
1432 #ifdef V2_HANDSHAKE_CLIENT
1433 return ! tls
->wasV2Handshake
;
1439 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1440 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1441 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1442 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1443 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1445 tor_tls_get_buffer_sizes(tor_tls_t
*tls
,
1446 size_t *rbuf_capacity
, size_t *rbuf_bytes
,
1447 size_t *wbuf_capacity
, size_t *wbuf_bytes
)
1449 if (tls
->ssl
->s3
->rbuf
.buf
)
1450 *rbuf_capacity
= tls
->ssl
->s3
->rbuf
.len
;
1453 if (tls
->ssl
->s3
->wbuf
.buf
)
1454 *wbuf_capacity
= tls
->ssl
->s3
->wbuf
.len
;
1457 *rbuf_bytes
= tls
->ssl
->s3
->rbuf
.left
;
1458 *wbuf_bytes
= tls
->ssl
->s3
->wbuf
.left
;