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 tls_library_is_initialized
= 1;
315 /** Free all global TLS structures. */
317 tor_tls_free_all(void)
319 if (global_tls_context
) {
320 tor_tls_context_decref(global_tls_context
);
321 global_tls_context
= NULL
;
323 if (!HT_EMPTY(&tlsmap_root
)) {
324 log_warn(LD_MM
, "Still have entries in the tlsmap at shutdown.");
326 HT_CLEAR(tlsmap
, &tlsmap_root
);
327 #ifdef V2_HANDSHAKE_CLIENT
328 if (CLIENT_CIPHER_DUMMIES
)
329 tor_free(CLIENT_CIPHER_DUMMIES
);
330 if (CLIENT_CIPHER_STACK
)
331 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK
);
335 /** We need to give OpenSSL a callback to verify certificates. This is
336 * it: We always accept peer certs and complete the handshake. We
337 * don't validate them until later.
340 always_accept_verify_cb(int preverify_ok
,
341 X509_STORE_CTX
*x509_ctx
)
348 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
350 tor_x509_name_new(const char *cname
)
354 if (!(name
= X509_NAME_new()))
356 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
357 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
358 (unsigned char*)cname
, -1, -1, 0)))
362 X509_NAME_free(name
);
366 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
367 * signed by the private key <b>rsa_sign</b>. The commonName of the
368 * certificate will be <b>cname</b>; the commonName of the issuer will be
369 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
370 * starting from now. Return a certificate on success, NULL on
374 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
375 crypto_pk_env_t
*rsa_sign
,
377 const char *cname_sign
,
378 unsigned int cert_lifetime
)
380 time_t start_time
, end_time
;
381 EVP_PKEY
*sign_pkey
= NULL
, *pkey
=NULL
;
383 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
387 start_time
= time(NULL
);
391 tor_assert(rsa_sign
);
392 tor_assert(cname_sign
);
393 if (!(sign_pkey
= _crypto_pk_env_get_evp_pkey(rsa_sign
,1)))
395 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
397 if (!(x509
= X509_new()))
399 if (!(X509_set_version(x509
, 2)))
401 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
404 if (!(name
= tor_x509_name_new(cname
)))
406 if (!(X509_set_subject_name(x509
, name
)))
408 if (!(name_issuer
= tor_x509_name_new(cname_sign
)))
410 if (!(X509_set_issuer_name(x509
, name_issuer
)))
413 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
415 end_time
= start_time
+ cert_lifetime
;
416 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
418 if (!X509_set_pubkey(x509
, pkey
))
420 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
430 tls_log_errors(NULL
, LOG_WARN
, "generating certificate");
432 EVP_PKEY_free(sign_pkey
);
436 X509_NAME_free(name
);
438 X509_NAME_free(name_issuer
);
442 /** List of ciphers that servers should select from.*/
443 #define SERVER_CIPHER_LIST \
444 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
445 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
446 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
447 /* Note: for setting up your own private testing network with link crypto
448 * disabled, set the cipher lists to your cipher list to
449 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
450 * with any of the "real" Tors, though. */
452 #ifdef V2_HANDSHAKE_CLIENT
453 #define CIPHER(id, name) name ":"
454 #define XCIPHER(id, name)
455 /** List of ciphers that clients should advertise, omitting items that
456 * our OpenSSL doesn't know about. */
457 static const char CLIENT_CIPHER_LIST
[] =
458 #include "./ciphers.inc"
463 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
464 typedef struct cipher_info_t
{ unsigned id
; const char *name
; } cipher_info_t
;
465 /** A list of all the ciphers that clients should advertise, including items
466 * that OpenSSL might not know about. */
467 static const cipher_info_t CLIENT_CIPHER_INFO_LIST
[] = {
468 #define CIPHER(id, name) { id, name },
469 #define XCIPHER(id, name) { id, #name },
470 #include "./ciphers.inc"
475 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
476 static const int N_CLIENT_CIPHERS
=
477 sizeof(CLIENT_CIPHER_INFO_LIST
)/sizeof(CLIENT_CIPHER_INFO_LIST
[0]);
480 #ifndef V2_HANDSHAKE_CLIENT
481 #undef CLIENT_CIPHER_LIST
482 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
483 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
486 /** Remove a reference to <b>ctx</b>, and free it if it has no more
489 tor_tls_context_decref(tor_tls_context_t
*ctx
)
492 if (--ctx
->refcnt
== 0) {
493 SSL_CTX_free(ctx
->ctx
);
494 X509_free(ctx
->my_cert
);
495 X509_free(ctx
->my_id_cert
);
496 crypto_free_pk_env(ctx
->key
);
501 /** Increase the reference count of <b>ctx</b>. */
503 tor_tls_context_incref(tor_tls_context_t
*ctx
)
508 /** Create a new TLS context for use with Tor TLS handshakes.
509 * <b>identity</b> should be set to the identity key used to sign the
510 * certificate, and <b>nickname</b> set to the nickname to use.
512 * You can call this function multiple times. Each time you call it,
513 * it generates new certificates; all new connections will use
514 * the new SSL context.
517 tor_tls_context_new(crypto_pk_env_t
*identity
, unsigned int key_lifetime
)
519 crypto_pk_env_t
*rsa
= NULL
;
520 EVP_PKEY
*pkey
= NULL
;
521 tor_tls_context_t
*result
= NULL
;
522 X509
*cert
= NULL
, *idcert
= NULL
;
523 char *nickname
= NULL
, *nn2
= NULL
;
526 nickname
= crypto_random_hostname(8, 20, "www.", ".net");
527 nn2
= crypto_random_hostname(8, 20, "www.", ".net");
529 /* Generate short-term RSA key. */
530 if (!(rsa
= crypto_new_pk_env()))
532 if (crypto_pk_generate_key(rsa
)<0)
534 /* Create certificate signed by identity key. */
535 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
537 /* Create self-signed certificate for identity key. */
538 idcert
= tor_tls_create_certificate(identity
, identity
, nn2
, nn2
,
539 IDENTITY_CERT_LIFETIME
);
540 if (!cert
|| !idcert
) {
541 log(LOG_WARN
, LD_CRYPTO
, "Error creating certificate");
545 result
= tor_malloc_zero(sizeof(tor_tls_context_t
));
547 result
->my_cert
= X509_dup(cert
);
548 result
->my_id_cert
= X509_dup(idcert
);
549 result
->key
= crypto_pk_dup_key(rsa
);
551 #ifdef EVERYONE_HAS_AES
552 /* Tell OpenSSL to only use TLS1 */
553 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
556 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
557 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
559 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
561 SSL_CTX_set_options(result
->ctx
, SSL_OP_SINGLE_DH_USE
);
563 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
564 SSL_CTX_set_options(result
->ctx
,
565 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
);
567 /* Don't actually allow compression; it uses ram and time, but the data
568 * we transmit is all encrypted anyway. */
569 if (result
->ctx
->comp_methods
)
570 result
->ctx
->comp_methods
= NULL
;
571 #ifdef SSL_MODE_RELEASE_BUFFERS
572 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_RELEASE_BUFFERS
);
574 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
576 X509_free(cert
); /* We just added a reference to cert. */
579 X509_STORE
*s
= SSL_CTX_get_cert_store(result
->ctx
);
581 X509_STORE_add_cert(s
, idcert
);
582 X509_free(idcert
); /* The context now owns the reference to idcert */
585 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
587 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
589 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
593 if (!SSL_CTX_check_private_key(result
->ctx
))
596 crypto_dh_env_t
*dh
= crypto_dh_new();
597 SSL_CTX_set_tmp_dh(result
->ctx
, _crypto_dh_env_get_dh(dh
));
600 SSL_CTX_set_verify(result
->ctx
, SSL_VERIFY_PEER
,
601 always_accept_verify_cb
);
602 /* let us realloc bufs that we're writing from */
603 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
604 /* Free the old context if one exists. */
605 if (global_tls_context
) {
606 /* This is safe even if there are open connections: OpenSSL does
607 * reference counting with SSL and SSL_CTX objects. */
608 tor_tls_context_decref(global_tls_context
);
610 global_tls_context
= result
;
612 crypto_free_pk_env(rsa
);
618 tls_log_errors(NULL
, LOG_WARN
, "creating TLS context");
624 crypto_free_pk_env(rsa
);
626 tor_tls_context_decref(result
);
634 #ifdef V2_HANDSHAKE_SERVER
635 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
636 * a list that indicates that the client knows how to do the v2 TLS connection
639 tor_tls_client_is_using_v2_ciphers(const SSL
*ssl
, const char *address
)
642 SSL_SESSION
*session
;
643 /* If we reached this point, we just got a client hello. See if there is
645 if (!(session
= SSL_get_session((SSL
*)ssl
))) {
646 log_warn(LD_NET
, "No session on TLS?");
649 if (!session
->ciphers
) {
650 log_warn(LD_NET
, "No ciphers on session");
653 /* Now we need to see if there are any ciphers whose presence means we're
654 * dealing with an updated Tor. */
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 if (strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
) &&
659 strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA
) &&
660 strcmp(ciphername
, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
) &&
661 strcmp(ciphername
, "(NONE)")) {
662 /* XXXX should be ld_debug */
663 log_info(LD_NET
, "Got a non-version-1 cipher called '%s'", ciphername
);
671 smartlist_t
*elts
= smartlist_create();
673 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
674 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
675 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
676 smartlist_add(elts
, (char*)ciphername
);
678 s
= smartlist_join_strings(elts
, ":", 0, NULL
);
679 log_info(LD_NET
, "Got a non-version-1 cipher list from %s. It is: '%s'",
682 smartlist_free(elts
);
687 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
688 * changes state. We use this:
689 * <ul><li>To alter the state of the handshake partway through, so we
690 * do not send or request extra certificates in v2 handshakes.</li>
691 * <li>To detect renegotiation</li></ul>
694 tor_tls_server_info_callback(const SSL
*ssl
, int type
, int val
)
698 if (type
!= SSL_CB_ACCEPT_LOOP
)
700 if (ssl
->state
!= SSL3_ST_SW_SRVR_HELLO_A
)
703 tls
= tor_tls_get_by_ssl(ssl
);
705 /* Check whether we're watching for renegotiates. If so, this is one! */
706 if (tls
->negotiated_callback
)
707 tls
->got_renegotiate
= 1;
709 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
712 /* Now check the cipher list. */
713 if (tor_tls_client_is_using_v2_ciphers(ssl
, ADDR(tls
))) {
714 /*XXXX_TLS keep this from happening more than once! */
716 /* Yes, we're casting away the const from ssl. This is very naughty of us.
717 * Let's hope openssl doesn't notice! */
719 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
720 SSL_set_mode((SSL
*) ssl
, SSL_MODE_NO_AUTO_CHAIN
);
721 /* Don't send a hello request. */
722 SSL_set_verify((SSL
*) ssl
, SSL_VERIFY_NONE
, NULL
);
725 tls
->wasV2Handshake
= 1;
727 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
733 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
734 * a list designed to mimic a common web browser. Some of the ciphers in the
735 * list won't actually be implemented by OpenSSL: that's okay so long as the
736 * server doesn't select them, and the server won't select anything besides
737 * what's in SERVER_CIPHER_LIST.
739 * [If the server <b>does</b> select a bogus cipher, we won't crash or
740 * anything; we'll just fail later when we try to look up the cipher in
741 * ssl->cipher_list_by_id.]
744 rectify_client_ciphers(STACK_OF(SSL_CIPHER
) **ciphers
)
746 #ifdef V2_HANDSHAKE_CLIENT
747 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK
)) {
748 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
752 /* First, create a dummy SSL_CIPHER for every cipher. */
753 CLIENT_CIPHER_DUMMIES
=
754 tor_malloc_zero(sizeof(SSL_CIPHER
)*N_CLIENT_CIPHERS
);
755 for (i
=0; i
< N_CLIENT_CIPHERS
; ++i
) {
756 CLIENT_CIPHER_DUMMIES
[i
].valid
= 1;
757 CLIENT_CIPHER_DUMMIES
[i
].id
= CLIENT_CIPHER_INFO_LIST
[i
].id
| (3<<24);
758 CLIENT_CIPHER_DUMMIES
[i
].name
= CLIENT_CIPHER_INFO_LIST
[i
].name
;
761 CLIENT_CIPHER_STACK
= sk_SSL_CIPHER_new_null();
762 tor_assert(CLIENT_CIPHER_STACK
);
764 log_debug(LD_NET
, "List was: %s", CLIENT_CIPHER_LIST
);
765 for (j
= 0; j
< sk_SSL_CIPHER_num(*ciphers
); ++j
) {
766 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
767 log_debug(LD_NET
, "Cipher %d: %lx %s", j
, cipher
->id
, cipher
->name
);
770 /* Then copy as many ciphers as we can from the good list, inserting
771 * dummies as needed. */
773 for (i
= 0; i
< N_CLIENT_CIPHERS
; ) {
774 SSL_CIPHER
*cipher
= NULL
;
775 if (j
< sk_SSL_CIPHER_num(*ciphers
))
776 cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
777 if (cipher
&& ((cipher
->id
>> 24) & 0xff) != 3) {
778 log_debug(LD_NET
, "Skipping v2 cipher %s", cipher
->name
);
781 (cipher
->id
& 0xffff) == CLIENT_CIPHER_INFO_LIST
[i
].id
) {
782 log_debug(LD_NET
, "Found cipher %s", cipher
->name
);
783 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, cipher
);
787 log_debug(LD_NET
, "Inserting fake %s", CLIENT_CIPHER_DUMMIES
[i
].name
);
788 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, &CLIENT_CIPHER_DUMMIES
[i
]);
794 sk_SSL_CIPHER_free(*ciphers
);
795 *ciphers
= sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK
);
796 tor_assert(*ciphers
);
803 /** Create a new TLS object from a file descriptor, and a flag to
804 * determine whether it is functioning as a server.
807 tor_tls_new(int sock
, int isServer
)
810 tor_tls_t
*result
= tor_malloc_zero(sizeof(tor_tls_t
));
812 tor_assert(global_tls_context
); /* make sure somebody made it first */
813 if (!(result
->ssl
= SSL_new(global_tls_context
->ctx
))) {
814 tls_log_errors(NULL
, LOG_WARN
, "generating TLS context");
819 #ifdef SSL_set_tlsext_host_name
820 /* Browsers use the TLS hostname extension, so we should too. */
822 char *fake_hostname
= crypto_random_hostname(4,25, "www.",".com");
823 SSL_set_tlsext_host_name(result
->ssl
, fake_hostname
);
824 tor_free(fake_hostname
);
828 if (!SSL_set_cipher_list(result
->ssl
,
829 isServer
? SERVER_CIPHER_LIST
: CLIENT_CIPHER_LIST
)) {
830 tls_log_errors(NULL
, LOG_WARN
, "setting ciphers");
831 SSL_free(result
->ssl
);
836 rectify_client_ciphers(&result
->ssl
->cipher_list
);
837 result
->socket
= sock
;
838 bio
= BIO_new_socket(sock
, BIO_NOCLOSE
);
840 tls_log_errors(NULL
, LOG_WARN
, "opening BIO");
841 SSL_free(result
->ssl
);
845 HT_INSERT(tlsmap
, &tlsmap_root
, result
);
846 SSL_set_bio(result
->ssl
, bio
, bio
);
847 tor_tls_context_incref(global_tls_context
);
848 result
->context
= global_tls_context
;
849 result
->state
= TOR_TLS_ST_HANDSHAKE
;
850 result
->isServer
= isServer
;
851 result
->wantwrite_n
= 0;
852 result
->last_write_count
= BIO_number_written(bio
);
853 result
->last_read_count
= BIO_number_read(bio
);
854 if (result
->last_write_count
|| result
->last_read_count
) {
855 log_warn(LD_NET
, "Newly created BIO has read count %lu, write count %lu",
856 result
->last_read_count
, result
->last_write_count
);
858 #ifdef V2_HANDSHAKE_SERVER
860 SSL_set_info_callback(result
->ssl
, tor_tls_server_info_callback
);
863 /* Not expected to get called. */
864 tls_log_errors(NULL
, LOG_WARN
, "generating TLS context");
868 /** Make future log messages about <b>tls</b> display the address
872 tor_tls_set_logged_address(tor_tls_t
*tls
, const char *address
)
875 tor_free(tls
->address
);
876 tls
->address
= tor_strdup(address
);
879 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
880 * next gets a client-side renegotiate in the middle of a read. Do not
881 * invoke this function until <em>after</em> initial handshaking is done!
884 tor_tls_set_renegotiate_callback(tor_tls_t
*tls
,
885 void (*cb
)(tor_tls_t
*, void *arg
),
888 tls
->negotiated_callback
= cb
;
889 tls
->callback_arg
= arg
;
890 tls
->got_renegotiate
= 0;
891 #ifdef V2_HANDSHAKE_SERVER
893 SSL_set_info_callback(tls
->ssl
, tor_tls_server_info_callback
);
895 SSL_set_info_callback(tls
->ssl
, NULL
);
900 /** Return whether this tls initiated the connect (client) or
901 * received it (server). */
903 tor_tls_is_server(tor_tls_t
*tls
)
906 return tls
->isServer
;
909 /** Release resources associated with a TLS object. Does not close the
910 * underlying file descriptor.
913 tor_tls_free(tor_tls_t
*tls
)
916 tor_assert(tls
&& tls
->ssl
);
917 removed
= HT_REMOVE(tlsmap
, &tlsmap_root
, tls
);
919 log_warn(LD_BUG
, "Freeing a TLS that was not in the ssl->tls map.");
923 tls
->negotiated_callback
= NULL
;
925 tor_tls_context_decref(tls
->context
);
926 tor_free(tls
->address
);
930 /** Underlying function for TLS reading. Reads up to <b>len</b>
931 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
932 * number of characters read. On failure, returns TOR_TLS_ERROR,
933 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
936 tor_tls_read(tor_tls_t
*tls
, char *cp
, size_t len
)
940 tor_assert(tls
->ssl
);
941 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
942 tor_assert(len
<INT_MAX
);
943 r
= SSL_read(tls
->ssl
, cp
, (int)len
);
945 #ifdef V2_HANDSHAKE_SERVER
946 if (tls
->got_renegotiate
) {
947 /* Renegotiation happened! */
948 log_info(LD_NET
, "Got a TLS renegotiation from %s", ADDR(tls
));
949 if (tls
->negotiated_callback
)
950 tls
->negotiated_callback(tls
, tls
->callback_arg
);
951 tls
->got_renegotiate
= 0;
956 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_DEBUG
);
957 if (err
== _TOR_TLS_ZERORETURN
|| err
== TOR_TLS_CLOSE
) {
958 log_debug(LD_NET
,"read returned r=%d; TLS is closed",r
);
959 tls
->state
= TOR_TLS_ST_CLOSED
;
960 return TOR_TLS_CLOSE
;
962 tor_assert(err
!= TOR_TLS_DONE
);
963 log_debug(LD_NET
,"read returned r=%d, err=%d",r
,err
);
968 /** Underlying function for TLS writing. Write up to <b>n</b>
969 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
970 * number of characters written. On failure, returns TOR_TLS_ERROR,
971 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
974 tor_tls_write(tor_tls_t
*tls
, const char *cp
, size_t n
)
978 tor_assert(tls
->ssl
);
979 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
980 tor_assert(n
< INT_MAX
);
983 if (tls
->wantwrite_n
) {
984 /* if WANTWRITE last time, we must use the _same_ n as before */
985 tor_assert(n
>= tls
->wantwrite_n
);
986 log_debug(LD_NET
,"resuming pending-write, (%d to flush, reusing %d)",
987 (int)n
, (int)tls
->wantwrite_n
);
988 n
= tls
->wantwrite_n
;
989 tls
->wantwrite_n
= 0;
991 r
= SSL_write(tls
->ssl
, cp
, (int)n
);
992 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
);
993 if (err
== TOR_TLS_DONE
) {
996 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
997 tls
->wantwrite_n
= n
;
1002 /** Perform initial handshake on <b>tls</b>. When finished, returns
1003 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1004 * or TOR_TLS_WANTWRITE.
1007 tor_tls_handshake(tor_tls_t
*tls
)
1011 tor_assert(tls
->ssl
);
1012 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
1013 check_no_tls_errors();
1014 if (tls
->isServer
) {
1015 r
= SSL_accept(tls
->ssl
);
1017 r
= SSL_connect(tls
->ssl
);
1019 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
);
1020 if (ERR_peek_error() != 0) {
1021 tls_log_errors(tls
, tls
->isServer
? LOG_INFO
: LOG_WARN
,
1023 return TOR_TLS_ERROR_MISC
;
1025 if (r
== TOR_TLS_DONE
) {
1026 tls
->state
= TOR_TLS_ST_OPEN
;
1027 if (tls
->isServer
) {
1028 SSL_set_info_callback(tls
->ssl
, NULL
);
1029 SSL_set_verify(tls
->ssl
, SSL_VERIFY_PEER
, always_accept_verify_cb
);
1030 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1031 tls
->ssl
->mode
&= ~SSL_MODE_NO_AUTO_CHAIN
;
1032 #ifdef V2_HANDSHAKE_SERVER
1033 if (tor_tls_client_is_using_v2_ciphers(tls
->ssl
, ADDR(tls
))) {
1034 /* This check is redundant, but back when we did it in the callback,
1035 * we might have not been able to look up the tor_tls_t if the code
1036 * was buggy. Fixing that. */
1037 if (!tls
->wasV2Handshake
) {
1038 log_warn(LD_BUG
, "For some reason, wasV2Handshake didn't"
1039 " get set. Fixing that.");
1041 tls
->wasV2Handshake
= 1;
1042 log_debug(LD_NET
, "Completed V2 TLS handshake with client; waiting "
1043 "for renegotiation.");
1045 tls
->wasV2Handshake
= 0;
1049 #ifdef V2_HANDSHAKE_CLIENT
1050 /* If we got no ID cert, we're a v2 handshake. */
1051 X509
*cert
= SSL_get_peer_certificate(tls
->ssl
);
1052 STACK_OF(X509
) *chain
= SSL_get_peer_cert_chain(tls
->ssl
);
1053 int n_certs
= sk_X509_num(chain
);
1054 if (n_certs
> 1 || (n_certs
== 1 && cert
!= sk_X509_value(chain
, 0)))
1055 tls
->wasV2Handshake
= 0;
1057 log_debug(LD_NET
, "Server sent back a single certificate; looks like "
1058 "a v2 handshake on %p.", tls
);
1059 tls
->wasV2Handshake
= 1;
1064 if (SSL_set_cipher_list(tls
->ssl
, SERVER_CIPHER_LIST
) == 0) {
1065 tls_log_errors(NULL
, LOG_WARN
, "re-setting ciphers");
1066 r
= TOR_TLS_ERROR_MISC
;
1073 /** Client only: Renegotiate a TLS session. When finished, returns
1074 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1075 * TOR_TLS_WANTWRITE.
1078 tor_tls_renegotiate(tor_tls_t
*tls
)
1082 /* We could do server-initiated renegotiation too, but that would be tricky.
1083 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1084 tor_assert(!tls
->isServer
);
1085 if (tls
->state
!= TOR_TLS_ST_RENEGOTIATE
) {
1086 int r
= SSL_renegotiate(tls
->ssl
);
1088 return tor_tls_get_error(tls
, r
, 0, "renegotiating", LOG_WARN
);
1090 tls
->state
= TOR_TLS_ST_RENEGOTIATE
;
1092 r
= SSL_do_handshake(tls
->ssl
);
1094 tls
->state
= TOR_TLS_ST_OPEN
;
1095 return TOR_TLS_DONE
;
1097 return tor_tls_get_error(tls
, r
, 0, "renegotiating handshake", LOG_INFO
);
1100 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1101 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1102 * or TOR_TLS_WANTWRITE.
1105 tor_tls_shutdown(tor_tls_t
*tls
)
1110 tor_assert(tls
->ssl
);
1113 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1114 /* If we've already called shutdown once to send a close message,
1115 * we read until the other side has closed too.
1118 r
= SSL_read(tls
->ssl
, buf
, 128);
1120 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
1122 if (err
== _TOR_TLS_ZERORETURN
) {
1123 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
1124 /* fall through... */
1130 r
= SSL_shutdown(tls
->ssl
);
1132 /* If shutdown returns 1, the connection is entirely closed. */
1133 tls
->state
= TOR_TLS_ST_CLOSED
;
1134 return TOR_TLS_DONE
;
1136 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
1138 if (err
== _TOR_TLS_SYSCALL
) {
1139 /* The underlying TCP connection closed while we were shutting down. */
1140 tls
->state
= TOR_TLS_ST_CLOSED
;
1141 return TOR_TLS_DONE
;
1142 } else if (err
== _TOR_TLS_ZERORETURN
) {
1143 /* The TLS connection says that it sent a shutdown record, but
1144 * isn't done shutting down yet. Make sure that this hasn't
1145 * happened before, then go back to the start of the function
1148 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
1149 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1150 log(LOG_WARN
, LD_NET
,
1151 "TLS returned \"half-closed\" value while already half-closed");
1152 return TOR_TLS_ERROR_MISC
;
1154 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
1155 /* fall through ... */
1162 /** Return true iff this TLS connection is authenticated.
1165 tor_tls_peer_has_cert(tor_tls_t
*tls
)
1168 cert
= SSL_get_peer_certificate(tls
->ssl
);
1169 tls_log_errors(tls
, LOG_WARN
, "getting peer certificate");
1176 /** Warn that a certificate lifetime extends through a certain range. */
1178 log_cert_lifetime(X509
*cert
, const char *problem
)
1182 char *s1
=NULL
, *s2
=NULL
;
1184 time_t now
= time(NULL
);
1188 log_warn(LD_GENERAL
,
1189 "Certificate %s: is your system clock set incorrectly?",
1192 if (!(bio
= BIO_new(BIO_s_mem()))) {
1193 log_warn(LD_GENERAL
, "Couldn't allocate BIO!"); goto end
;
1195 if (!(ASN1_TIME_print(bio
, X509_get_notBefore(cert
)))) {
1196 tls_log_errors(NULL
, LOG_WARN
, "printing certificate lifetime");
1199 BIO_get_mem_ptr(bio
, &buf
);
1200 s1
= tor_strndup(buf
->data
, buf
->length
);
1202 (void)BIO_reset(bio
);
1203 if (!(ASN1_TIME_print(bio
, X509_get_notAfter(cert
)))) {
1204 tls_log_errors(NULL
, LOG_WARN
, "printing certificate lifetime");
1207 BIO_get_mem_ptr(bio
, &buf
);
1208 s2
= tor_strndup(buf
->data
, buf
->length
);
1210 strftime(mytime
, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now
, &tm
));
1212 log_warn(LD_GENERAL
,
1213 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1217 /* Not expected to get invoked */
1218 tls_log_errors(NULL
, LOG_WARN
, "getting certificate lifetime");
1227 /** Helper function: try to extract a link certificate and an identity
1228 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1229 * *<b>id_cert_out</b> respectively. Log all messages at level
1232 * Note that a reference is added to cert_out, so it needs to be
1233 * freed. id_cert_out doesn't. */
1235 try_to_extract_certs_from_tls(int severity
, tor_tls_t
*tls
,
1236 X509
**cert_out
, X509
**id_cert_out
)
1238 X509
*cert
= NULL
, *id_cert
= NULL
;
1239 STACK_OF(X509
) *chain
= NULL
;
1240 int num_in_chain
, i
;
1241 *cert_out
= *id_cert_out
= NULL
;
1243 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1246 if (!(chain
= SSL_get_peer_cert_chain(tls
->ssl
)))
1248 num_in_chain
= sk_X509_num(chain
);
1249 /* 1 means we're receiving (server-side), and it's just the id_cert.
1250 * 2 means we're connecting (client-side), and it's both the link
1251 * cert and the id_cert.
1253 if (num_in_chain
< 1) {
1254 log_fn(severity
,LD_PROTOCOL
,
1255 "Unexpected number of certificates in chain (%d)",
1259 for (i
=0; i
<num_in_chain
; ++i
) {
1260 id_cert
= sk_X509_value(chain
, i
);
1261 if (X509_cmp(id_cert
, cert
) != 0)
1264 *id_cert_out
= id_cert
;
1267 /** If the provided tls connection is authenticated and has a
1268 * certificate chain that is currently valid and signed, then set
1269 * *<b>identity_key</b> to the identity certificate's key and return
1270 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1273 tor_tls_verify(int severity
, tor_tls_t
*tls
, crypto_pk_env_t
**identity_key
)
1275 X509
*cert
= NULL
, *id_cert
= NULL
;
1276 EVP_PKEY
*id_pkey
= NULL
;
1280 *identity_key
= NULL
;
1282 try_to_extract_certs_from_tls(severity
, tls
, &cert
, &id_cert
);
1286 log_fn(severity
,LD_PROTOCOL
,"No distinct identity certificate found");
1289 if (!(id_pkey
= X509_get_pubkey(id_cert
)) ||
1290 X509_verify(cert
, id_pkey
) <= 0) {
1291 log_fn(severity
,LD_PROTOCOL
,"X509_verify on cert and pkey returned <= 0");
1292 tls_log_errors(tls
, severity
,"verifying certificate");
1296 rsa
= EVP_PKEY_get1_RSA(id_pkey
);
1299 *identity_key
= _crypto_new_pk_env_rsa(rsa
);
1307 EVP_PKEY_free(id_pkey
);
1309 /* This should never get invoked, but let's make sure in case OpenSSL
1310 * acts unexpectedly. */
1311 tls_log_errors(tls
, LOG_WARN
, "finishing tor_tls_verify");
1316 /** Check whether the certificate set on the connection <b>tls</b> is
1317 * expired or not-yet-valid, give or take <b>tolerance</b>
1318 * seconds. Return 0 for valid, -1 for failure.
1320 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1323 tor_tls_check_lifetime(tor_tls_t
*tls
, int tolerance
)
1331 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1334 t
= now
+ tolerance
;
1335 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
1336 log_cert_lifetime(cert
, "not yet valid");
1339 t
= now
- tolerance
;
1340 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
1341 log_cert_lifetime(cert
, "already expired");
1349 /* Not expected to get invoked */
1350 tls_log_errors(tls
, LOG_WARN
, "checking certificate lifetime");
1355 /** Return the number of bytes available for reading from <b>tls</b>.
1358 tor_tls_get_pending_bytes(tor_tls_t
*tls
)
1361 return SSL_pending(tls
->ssl
);
1364 /** If <b>tls</b> requires that the next write be of a particular size,
1365 * return that size. Otherwise, return 0. */
1367 tor_tls_get_forced_write_size(tor_tls_t
*tls
)
1369 return tls
->wantwrite_n
;
1372 /** Sets n_read and n_written to the number of bytes read and written,
1373 * respectively, on the raw socket used by <b>tls</b> since the last time this
1374 * function was called on <b>tls</b>. */
1376 tor_tls_get_n_raw_bytes(tor_tls_t
*tls
, size_t *n_read
, size_t *n_written
)
1380 r
= BIO_number_read(SSL_get_rbio(tls
->ssl
));
1381 /* We want the number of bytes actually for real written. Unfortunately,
1382 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1383 * which makes the answer turn out wrong. Let's cope with that. Note
1384 * that this approach will fail if we ever replace tls->ssl's BIOs with
1385 * buffering bios for reasons of our own. As an alternative, we could
1386 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1387 * that would be tempting fate. */
1388 wbio
= SSL_get_wbio(tls
->ssl
);
1389 if (wbio
->method
== BIO_f_buffer() && (tmpbio
= BIO_next(wbio
)) != NULL
)
1391 w
= BIO_number_written(wbio
);
1393 /* We are ok with letting these unsigned ints go "negative" here:
1394 * If we wrapped around, this should still give us the right answer, unless
1395 * we wrapped around by more than ULONG_MAX since the last time we called
1398 *n_read
= (size_t)(r
- tls
->last_read_count
);
1399 *n_written
= (size_t)(w
- tls
->last_write_count
);
1400 if (*n_read
> INT_MAX
|| *n_written
> INT_MAX
) {
1401 log_warn(LD_BUG
, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1402 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1403 r
, tls
->last_read_count
, w
, tls
->last_write_count
);
1405 tls
->last_read_count
= r
;
1406 tls
->last_write_count
= w
;
1409 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1410 * errors, log an error message. */
1412 _check_no_tls_errors(const char *fname
, int line
)
1414 if (ERR_peek_error() == 0)
1416 log(LOG_WARN
, LD_CRYPTO
, "Unhandled OpenSSL errors found at %s:%d: ",
1417 tor_fix_source_file(fname
), line
);
1418 tls_log_errors(NULL
, LOG_WARN
, NULL
);
1421 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1422 * TLS handshake. Output is undefined if the handshake isn't finished. */
1424 tor_tls_used_v1_handshake(tor_tls_t
*tls
)
1426 if (tls
->isServer
) {
1427 #ifdef V2_HANDSHAKE_SERVER
1428 return ! tls
->wasV2Handshake
;
1431 #ifdef V2_HANDSHAKE_CLIENT
1432 return ! tls
->wasV2Handshake
;
1438 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1439 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1440 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1441 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1442 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1444 tor_tls_get_buffer_sizes(tor_tls_t
*tls
,
1445 int *rbuf_capacity
, int *rbuf_bytes
,
1446 int *wbuf_capacity
, int *wbuf_bytes
)
1448 if (tls
->ssl
->s3
->rbuf
.buf
)
1449 *rbuf_capacity
= tls
->ssl
->s3
->rbuf
.len
;
1452 if (tls
->ssl
->s3
->wbuf
.buf
)
1453 *wbuf_capacity
= tls
->ssl
->s3
->wbuf
.len
;
1456 *rbuf_bytes
= tls
->ssl
->s3
->rbuf
.left
;
1457 *wbuf_bytes
= tls
->ssl
->s3
->wbuf
.left
;