1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, 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.)
24 #ifdef MS_WINDOWS /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
26 #define WIN32_WINNT 0x400
29 #define _WIN32_WINNT 0x400
31 #define WIN32_LEAN_AND_MEAN
32 #if defined(_MSC_VER) && (_MSC_VER < 1300)
39 #include <openssl/ssl.h>
40 #include <openssl/ssl3.h>
41 #include <openssl/err.h>
42 #include <openssl/tls1.h>
43 #include <openssl/asn1.h>
44 #include <openssl/bio.h>
45 #include <openssl/opensslv.h>
47 #if OPENSSL_VERSION_NUMBER < 0x00907000l
48 #error "We require OpenSSL >= 0.9.7"
51 #ifdef USE_BUFFEREVENTS
52 #include <event2/bufferevent_ssl.h>
53 #include <event2/buffer.h>
54 #include "compat_libevent.h"
57 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
58 #define TORTLS_PRIVATE
64 #include "container.h"
67 /* Enable the "v2" TLS handshake.
69 #define V2_HANDSHAKE_SERVER
70 #define V2_HANDSHAKE_CLIENT
72 /* Copied from or.h */
73 #define LEGAL_NICKNAME_CHARACTERS \
74 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
76 /** How long do identity certificates live? (sec) */
77 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
79 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
81 /* We redefine these so that we can run correctly even if the vendor gives us
82 * a version of OpenSSL that does not match its header files. (Apple: I am
85 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
86 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
88 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
89 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
92 /** Does the run-time openssl version look like we need
93 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
94 static int use_unsafe_renegotiation_op
= 0;
95 /** Does the run-time openssl version look like we need
96 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
97 static int use_unsafe_renegotiation_flag
= 0;
99 /** Holds a SSL_CTX object and related state used to configure TLS
102 typedef struct tor_tls_context_t
{
107 crypto_pk_env_t
*key
;
110 #define TOR_TLS_MAGIC 0x71571571
112 /** Holds a SSL object and its associated data. Members are only
113 * accessed from within tortls.c.
117 tor_tls_context_t
*context
; /** A link to the context object for this tls. */
118 SSL
*ssl
; /**< An OpenSSL SSL object. */
119 int socket
; /**< The underlying file descriptor for this TLS connection. */
120 char *address
; /**< An address to log when describing this connection. */
122 TOR_TLS_ST_HANDSHAKE
, TOR_TLS_ST_OPEN
, TOR_TLS_ST_GOTCLOSE
,
123 TOR_TLS_ST_SENTCLOSE
, TOR_TLS_ST_CLOSED
, TOR_TLS_ST_RENEGOTIATE
,
124 TOR_TLS_ST_BUFFEREVENT
125 } state
: 3; /**< The current SSL state, depending on which operations have
126 * completed successfully. */
127 unsigned int isServer
:1; /**< True iff this is a server-side connection */
128 unsigned int wasV2Handshake
:1; /**< True iff the original handshake for
129 * this connection used the updated version
130 * of the connection protocol (client sends
131 * different cipher list, server sends only
132 * one certificate). */
133 /** True iff we should call negotiated_callback when we're done reading. */
134 unsigned int got_renegotiate
:1;
135 /** Incremented every time we start the server side of a handshake. */
136 uint8_t server_handshake_count
;
137 size_t wantwrite_n
; /**< 0 normally, >0 if we returned wantwrite last
139 /** Last values retrieved from BIO_number_read()/write(); see
140 * tor_tls_get_n_raw_bytes() for usage.
142 unsigned long last_write_count
;
143 unsigned long last_read_count
;
144 /** If set, a callback to invoke whenever the client tries to renegotiate
146 void (*negotiated_callback
)(tor_tls_t
*tls
, void *arg
);
147 /** Argument to pass to negotiated_callback. */
151 #ifdef V2_HANDSHAKE_CLIENT
152 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
153 * in client mode into advertising the ciphers we want. See
154 * rectify_client_ciphers() for details. */
155 static SSL_CIPHER
*CLIENT_CIPHER_DUMMIES
= NULL
;
156 /** A stack of SSL_CIPHER objects, some real, some fake.
157 * See rectify_client_ciphers() for details. */
158 static STACK_OF(SSL_CIPHER
) *CLIENT_CIPHER_STACK
= NULL
;
161 /** The ex_data index in which we store a pointer to an SSL object's
162 * corresponding tor_tls_t object. */
163 static int tor_tls_object_ex_data_index
= -1;
165 /** Helper: Allocate tor_tls_object_ex_data_index. */
167 tor_tls_allocate_tor_tls_object_ex_data_index(void)
169 if (tor_tls_object_ex_data_index
== -1) {
170 tor_tls_object_ex_data_index
=
171 SSL_get_ex_new_index(0, NULL
, NULL
, NULL
, NULL
);
172 tor_assert(tor_tls_object_ex_data_index
!= -1);
176 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
178 static INLINE tor_tls_t
*
179 tor_tls_get_by_ssl(const SSL
*ssl
)
181 tor_tls_t
*result
= SSL_get_ex_data(ssl
, tor_tls_object_ex_data_index
);
183 tor_assert(result
->magic
== TOR_TLS_MAGIC
);
187 static void tor_tls_context_decref(tor_tls_context_t
*ctx
);
188 static void tor_tls_context_incref(tor_tls_context_t
*ctx
);
189 static X509
* tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
190 crypto_pk_env_t
*rsa_sign
,
192 const char *cname_sign
,
193 unsigned int lifetime
);
195 static int tor_tls_context_init_one(tor_tls_context_t
**ppcontext
,
196 crypto_pk_env_t
*identity
,
197 unsigned int key_lifetime
);
198 static tor_tls_context_t
*tor_tls_context_new(crypto_pk_env_t
*identity
,
199 unsigned int key_lifetime
);
201 /** Global TLS contexts. We keep them here because nobody else needs
203 static tor_tls_context_t
*server_tls_context
= NULL
;
204 static tor_tls_context_t
*client_tls_context
= NULL
;
206 /** True iff tor_tls_init() has been called. */
207 static int tls_library_is_initialized
= 0;
209 /* Module-internal error codes. */
210 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
211 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
213 #include "tortls_states.h"
215 /** Return the symbolic name of an OpenSSL state. */
217 ssl_state_to_string(int ssl_state
)
221 for (i
= 0; state_map
[i
].name
; ++i
) {
222 if (state_map
[i
].state
== ssl_state
)
223 return state_map
[i
].name
;
225 tor_snprintf(buf
, sizeof(buf
), "Unknown state %d", ssl_state
);
229 /** Write a description of the current state of <b>tls</b> into the
230 * <b>sz</b>-byte buffer at <b>buf</b>. */
232 tor_tls_get_state_description(tor_tls_t
*tls
, char *buf
, size_t sz
)
234 const char *ssl_state
;
235 const char *tortls_state
;
237 if (PREDICT_UNLIKELY(!tls
|| !tls
->ssl
)) {
238 strlcpy(buf
, "(No SSL object)", sz
);
242 ssl_state
= ssl_state_to_string(tls
->ssl
->state
);
243 switch (tls
->state
) {
244 #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
252 case TOR_TLS_ST_BUFFEREVENT
:
256 tortls_state
= " in unknown TLS state";
260 tor_snprintf(buf
, sz
, "%s%s", ssl_state
, tortls_state
);
264 tor_tls_log_one_error(tor_tls_t
*tls
, unsigned long err
,
265 int severity
, int domain
, const char *doing
)
267 const char *state
= NULL
, *addr
;
268 const char *msg
, *lib
, *func
;
271 st
= (tls
&& tls
->ssl
) ? tls
->ssl
->state
: -1;
272 state
= (st
>=0)?ssl_state_to_string(st
):"---";
274 addr
= tls
? tls
->address
: NULL
;
276 /* Some errors are known-benign, meaning they are the fault of the other
277 * side of the connection. The caller doesn't know this, so override the
278 * priority for those cases. */
279 switch (ERR_GET_REASON(err
)) {
280 case SSL_R_HTTP_REQUEST
:
281 case SSL_R_HTTPS_PROXY_REQUEST
:
282 case SSL_R_RECORD_LENGTH_MISMATCH
:
283 case SSL_R_RECORD_TOO_LARGE
:
284 case SSL_R_UNKNOWN_PROTOCOL
:
285 case SSL_R_UNSUPPORTED_PROTOCOL
:
292 msg
= (const char*)ERR_reason_error_string(err
);
293 lib
= (const char*)ERR_lib_error_string(err
);
294 func
= (const char*)ERR_func_error_string(err
);
295 if (!msg
) msg
= "(null)";
296 if (!lib
) lib
= "(null)";
297 if (!func
) func
= "(null)";
299 log(severity
, domain
, "TLS error while %s%s%s: %s (in %s:%s:%s)",
300 doing
, addr
?" with ":"", addr
?addr
:"",
301 msg
, lib
, func
, state
);
303 log(severity
, domain
, "TLS error%s%s: %s (in %s:%s:%s)",
304 addr
?" with ":"", addr
?addr
:"",
305 msg
, lib
, func
, state
);
309 /** Log all pending tls errors at level <b>severity</b>. Use
310 * <b>doing</b> to describe our current activities.
313 tls_log_errors(tor_tls_t
*tls
, int severity
, int domain
, const char *doing
)
317 while ((err
= ERR_get_error()) != 0) {
318 tor_tls_log_one_error(tls
, err
, severity
, domain
, doing
);
322 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
325 tor_errno_to_tls_error(int e
)
327 #if defined(MS_WINDOWS)
329 case WSAECONNRESET
: // most common
330 return TOR_TLS_ERROR_CONNRESET
;
332 return TOR_TLS_ERROR_TIMEOUT
;
334 case WSAEHOSTUNREACH
:
335 return TOR_TLS_ERROR_NO_ROUTE
;
336 case WSAECONNREFUSED
:
337 return TOR_TLS_ERROR_CONNREFUSED
; // least common
339 return TOR_TLS_ERROR_MISC
;
343 case ECONNRESET
: // most common
344 return TOR_TLS_ERROR_CONNRESET
;
346 return TOR_TLS_ERROR_TIMEOUT
;
349 return TOR_TLS_ERROR_NO_ROUTE
;
351 return TOR_TLS_ERROR_CONNREFUSED
; // least common
353 return TOR_TLS_ERROR_MISC
;
358 /** Given a TOR_TLS_* error code, return a string equivalent. */
360 tor_tls_err_to_string(int err
)
363 return "[Not an error.]";
365 case TOR_TLS_ERROR_MISC
: return "misc error";
366 case TOR_TLS_ERROR_IO
: return "unexpected close";
367 case TOR_TLS_ERROR_CONNREFUSED
: return "connection refused";
368 case TOR_TLS_ERROR_CONNRESET
: return "connection reset";
369 case TOR_TLS_ERROR_NO_ROUTE
: return "host unreachable";
370 case TOR_TLS_ERROR_TIMEOUT
: return "connection timed out";
371 case TOR_TLS_CLOSE
: return "closed";
372 case TOR_TLS_WANTREAD
: return "want to read";
373 case TOR_TLS_WANTWRITE
: return "want to write";
374 default: return "(unknown error code)";
378 #define CATCH_SYSCALL 1
381 /** Given a TLS object and the result of an SSL_* call, use
382 * SSL_get_error to determine whether an error has occurred, and if so
383 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
384 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
385 * reporting syscall errors. If extra&CATCH_ZERO is true, return
386 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
388 * If an error has occurred, log it at level <b>severity</b> and describe the
389 * current action as <b>doing</b>.
392 tor_tls_get_error(tor_tls_t
*tls
, int r
, int extra
,
393 const char *doing
, int severity
, int domain
)
395 int err
= SSL_get_error(tls
->ssl
, r
);
396 int tor_error
= TOR_TLS_ERROR_MISC
;
400 case SSL_ERROR_WANT_READ
:
401 return TOR_TLS_WANTREAD
;
402 case SSL_ERROR_WANT_WRITE
:
403 return TOR_TLS_WANTWRITE
;
404 case SSL_ERROR_SYSCALL
:
405 if (extra
&CATCH_SYSCALL
)
406 return _TOR_TLS_SYSCALL
;
408 log(severity
, LD_NET
, "TLS error: unexpected close while %s (%s)",
409 doing
, ssl_state_to_string(tls
->ssl
->state
));
410 tor_error
= TOR_TLS_ERROR_IO
;
412 int e
= tor_socket_errno(tls
->socket
);
413 log(severity
, LD_NET
,
414 "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
415 doing
, e
, tor_socket_strerror(e
),
416 ssl_state_to_string(tls
->ssl
->state
));
417 tor_error
= tor_errno_to_tls_error(e
);
419 tls_log_errors(tls
, severity
, domain
, doing
);
421 case SSL_ERROR_ZERO_RETURN
:
422 if (extra
&CATCH_ZERO
)
423 return _TOR_TLS_ZERORETURN
;
424 log(severity
, LD_NET
, "TLS connection closed while %s in state %s",
425 doing
, ssl_state_to_string(tls
->ssl
->state
));
426 tls_log_errors(tls
, severity
, domain
, doing
);
427 return TOR_TLS_CLOSE
;
429 tls_log_errors(tls
, severity
, domain
, doing
);
430 return TOR_TLS_ERROR_MISC
;
434 /** Initialize OpenSSL, unless it has already been initialized.
439 if (!tls_library_is_initialized
) {
442 SSL_load_error_strings();
446 /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
447 * here, but without thinking too hard about it: it turns out that the
448 * flag in question needed to be set at the last minute, and that it
449 * conflicted with an existing flag number that had already been added
450 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
451 * the flag with an option and (it seems) broke anything that used
452 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
453 * and we mustn't use the SSL3_FLAGS option with anything besides
456 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
457 * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
458 * set option 0x00040000L everywhere.
460 * No, we can't simply detect whether the flag or the option is present
461 * in the headers at build-time: some vendors (notably Apple) like to
462 * leave their headers out of sync with their libraries.
464 * Yes, it _is_ almost as if the OpenSSL developers decided that no
465 * program should be allowed to use renegotiation unless it first passed
466 * a test of intelligence and determination.
468 if (version
>= 0x009080c0L
&& version
< 0x009080d0L
) {
469 log_notice(LD_GENERAL
, "OpenSSL %s looks like version 0.9.8l; "
470 "I will try SSL3_FLAGS to enable renegotation.",
471 SSLeay_version(SSLEAY_VERSION
));
472 use_unsafe_renegotiation_flag
= 1;
473 use_unsafe_renegotiation_op
= 1;
474 } else if (version
>= 0x009080d0L
) {
475 log_notice(LD_GENERAL
, "OpenSSL %s looks like version 0.9.8m or later; "
476 "I will try SSL_OP to enable renegotiation",
477 SSLeay_version(SSLEAY_VERSION
));
478 use_unsafe_renegotiation_op
= 1;
479 } else if (version
< 0x009080c0L
) {
480 log_notice(LD_GENERAL
, "OpenSSL %s [%lx] looks like it's older than "
481 "0.9.8l, but some vendors have backported 0.9.8l's "
482 "renegotiation code to earlier versions, and some have "
483 "backported the code from 0.9.8m or 0.9.8n. I'll set both "
484 "SSL3_FLAGS and SSL_OP just to be safe.",
485 SSLeay_version(SSLEAY_VERSION
), version
);
486 use_unsafe_renegotiation_flag
= 1;
487 use_unsafe_renegotiation_op
= 1;
489 log_info(LD_GENERAL
, "OpenSSL %s has version %lx",
490 SSLeay_version(SSLEAY_VERSION
), version
);
493 tor_tls_allocate_tor_tls_object_ex_data_index();
495 tls_library_is_initialized
= 1;
499 /** Free all global TLS structures. */
501 tor_tls_free_all(void)
503 if (server_tls_context
) {
504 tor_tls_context_t
*ctx
= server_tls_context
;
505 server_tls_context
= NULL
;
506 tor_tls_context_decref(ctx
);
508 if (client_tls_context
) {
509 tor_tls_context_t
*ctx
= client_tls_context
;
510 client_tls_context
= NULL
;
511 tor_tls_context_decref(ctx
);
513 #ifdef V2_HANDSHAKE_CLIENT
514 if (CLIENT_CIPHER_DUMMIES
)
515 tor_free(CLIENT_CIPHER_DUMMIES
);
516 if (CLIENT_CIPHER_STACK
)
517 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK
);
521 /** We need to give OpenSSL a callback to verify certificates. This is
522 * it: We always accept peer certs and complete the handshake. We
523 * don't validate them until later.
526 always_accept_verify_cb(int preverify_ok
,
527 X509_STORE_CTX
*x509_ctx
)
534 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
536 tor_x509_name_new(const char *cname
)
540 if (!(name
= X509_NAME_new()))
542 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
543 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
544 (unsigned char*)cname
, -1, -1, 0)))
548 X509_NAME_free(name
);
552 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
553 * signed by the private key <b>rsa_sign</b>. The commonName of the
554 * certificate will be <b>cname</b>; the commonName of the issuer will be
555 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
556 * starting from now. Return a certificate on success, NULL on
560 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
561 crypto_pk_env_t
*rsa_sign
,
563 const char *cname_sign
,
564 unsigned int cert_lifetime
)
566 time_t start_time
, end_time
;
567 EVP_PKEY
*sign_pkey
= NULL
, *pkey
=NULL
;
569 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
573 start_time
= time(NULL
);
577 tor_assert(rsa_sign
);
578 tor_assert(cname_sign
);
579 if (!(sign_pkey
= _crypto_pk_env_get_evp_pkey(rsa_sign
,1)))
581 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
583 if (!(x509
= X509_new()))
585 if (!(X509_set_version(x509
, 2)))
587 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
590 if (!(name
= tor_x509_name_new(cname
)))
592 if (!(X509_set_subject_name(x509
, name
)))
594 if (!(name_issuer
= tor_x509_name_new(cname_sign
)))
596 if (!(X509_set_issuer_name(x509
, name_issuer
)))
599 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
601 end_time
= start_time
+ cert_lifetime
;
602 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
604 if (!X509_set_pubkey(x509
, pkey
))
606 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
616 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "generating certificate");
618 EVP_PKEY_free(sign_pkey
);
622 X509_NAME_free(name
);
624 X509_NAME_free(name_issuer
);
628 /** List of ciphers that servers should select from.*/
629 #define SERVER_CIPHER_LIST \
630 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
631 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
632 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
633 /* Note: to set up your own private testing network with link crypto
634 * disabled, set your Tors' cipher list to
635 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
636 * with any of the "real" Tors, though. */
638 #ifdef V2_HANDSHAKE_CLIENT
639 #define CIPHER(id, name) name ":"
640 #define XCIPHER(id, name)
641 /** List of ciphers that clients should advertise, omitting items that
642 * our OpenSSL doesn't know about. */
643 static const char CLIENT_CIPHER_LIST
[] =
644 #include "./ciphers.inc"
649 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
650 typedef struct cipher_info_t
{ unsigned id
; const char *name
; } cipher_info_t
;
651 /** A list of all the ciphers that clients should advertise, including items
652 * that OpenSSL might not know about. */
653 static const cipher_info_t CLIENT_CIPHER_INFO_LIST
[] = {
654 #define CIPHER(id, name) { id, name },
655 #define XCIPHER(id, name) { id, #name },
656 #include "./ciphers.inc"
661 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
662 static const int N_CLIENT_CIPHERS
=
663 sizeof(CLIENT_CIPHER_INFO_LIST
)/sizeof(CLIENT_CIPHER_INFO_LIST
[0]);
666 #ifndef V2_HANDSHAKE_CLIENT
667 #undef CLIENT_CIPHER_LIST
668 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
669 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
672 /** Remove a reference to <b>ctx</b>, and free it if it has no more
675 tor_tls_context_decref(tor_tls_context_t
*ctx
)
678 if (--ctx
->refcnt
== 0) {
679 SSL_CTX_free(ctx
->ctx
);
680 X509_free(ctx
->my_cert
);
681 X509_free(ctx
->my_id_cert
);
682 crypto_free_pk_env(ctx
->key
);
687 /** Increase the reference count of <b>ctx</b>. */
689 tor_tls_context_incref(tor_tls_context_t
*ctx
)
694 /** Create new global client and server TLS contexts.
696 * If <b>server_identity</b> is NULL, this will not generate a server
697 * TLS context. If <b>is_public_server</b> is non-zero, this will use
698 * the same TLS context for incoming and outgoing connections, and
699 * ignore <b>client_identity</b>. */
701 tor_tls_context_init(int is_public_server
,
702 crypto_pk_env_t
*client_identity
,
703 crypto_pk_env_t
*server_identity
,
704 unsigned int key_lifetime
)
709 if (is_public_server
) {
710 tor_tls_context_t
*new_ctx
;
711 tor_tls_context_t
*old_ctx
;
713 tor_assert(server_identity
!= NULL
);
715 rv1
= tor_tls_context_init_one(&server_tls_context
,
720 new_ctx
= server_tls_context
;
721 tor_tls_context_incref(new_ctx
);
722 old_ctx
= client_tls_context
;
723 client_tls_context
= new_ctx
;
725 if (old_ctx
!= NULL
) {
726 tor_tls_context_decref(old_ctx
);
730 if (server_identity
!= NULL
) {
731 rv1
= tor_tls_context_init_one(&server_tls_context
,
735 tor_tls_context_t
*old_ctx
= server_tls_context
;
736 server_tls_context
= NULL
;
738 if (old_ctx
!= NULL
) {
739 tor_tls_context_decref(old_ctx
);
743 rv2
= tor_tls_context_init_one(&client_tls_context
,
748 return MIN(rv1
, rv2
);
751 /** Create a new global TLS context.
753 * You can call this function multiple times. Each time you call it,
754 * it generates new certificates; all new connections will use
755 * the new SSL context.
758 tor_tls_context_init_one(tor_tls_context_t
**ppcontext
,
759 crypto_pk_env_t
*identity
,
760 unsigned int key_lifetime
)
762 tor_tls_context_t
*new_ctx
= tor_tls_context_new(identity
,
764 tor_tls_context_t
*old_ctx
= *ppcontext
;
766 if (new_ctx
!= NULL
) {
767 *ppcontext
= new_ctx
;
769 /* Free the old context if one existed. */
770 if (old_ctx
!= NULL
) {
771 /* This is safe even if there are open connections: we reference-
772 * count tor_tls_context_t objects. */
773 tor_tls_context_decref(old_ctx
);
777 return ((new_ctx
!= NULL
) ? 0 : -1);
780 /** Create a new TLS context for use with Tor TLS handshakes.
781 * <b>identity</b> should be set to the identity key used to sign the
784 static tor_tls_context_t
*
785 tor_tls_context_new(crypto_pk_env_t
*identity
, unsigned int key_lifetime
)
787 crypto_pk_env_t
*rsa
= NULL
;
788 EVP_PKEY
*pkey
= NULL
;
789 tor_tls_context_t
*result
= NULL
;
790 X509
*cert
= NULL
, *idcert
= NULL
;
791 char *nickname
= NULL
, *nn2
= NULL
;
794 nickname
= crypto_random_hostname(8, 20, "www.", ".net");
795 nn2
= crypto_random_hostname(8, 20, "www.", ".net");
797 /* Generate short-term RSA key. */
798 if (!(rsa
= crypto_new_pk_env()))
800 if (crypto_pk_generate_key(rsa
)<0)
802 /* Create certificate signed by identity key. */
803 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
805 /* Create self-signed certificate for identity key. */
806 idcert
= tor_tls_create_certificate(identity
, identity
, nn2
, nn2
,
807 IDENTITY_CERT_LIFETIME
);
808 if (!cert
|| !idcert
) {
809 log(LOG_WARN
, LD_CRYPTO
, "Error creating certificate");
813 result
= tor_malloc_zero(sizeof(tor_tls_context_t
));
815 result
->my_cert
= X509_dup(cert
);
816 result
->my_id_cert
= X509_dup(idcert
);
817 result
->key
= crypto_pk_dup_key(rsa
);
819 #ifdef EVERYONE_HAS_AES
820 /* Tell OpenSSL to only use TLS1 */
821 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
824 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
825 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
827 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
829 SSL_CTX_set_options(result
->ctx
, SSL_OP_SINGLE_DH_USE
);
831 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
832 SSL_CTX_set_options(result
->ctx
,
833 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
);
835 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
836 * as authenticating any earlier-received data.
838 if (use_unsafe_renegotiation_op
) {
839 SSL_CTX_set_options(result
->ctx
,
840 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
);
842 /* Don't actually allow compression; it uses ram and time, but the data
843 * we transmit is all encrypted anyway. */
844 if (result
->ctx
->comp_methods
)
845 result
->ctx
->comp_methods
= NULL
;
846 #ifdef SSL_MODE_RELEASE_BUFFERS
847 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_RELEASE_BUFFERS
);
849 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
851 X509_free(cert
); /* We just added a reference to cert. */
854 X509_STORE
*s
= SSL_CTX_get_cert_store(result
->ctx
);
856 X509_STORE_add_cert(s
, idcert
);
857 X509_free(idcert
); /* The context now owns the reference to idcert */
860 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
862 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
864 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
868 if (!SSL_CTX_check_private_key(result
->ctx
))
871 crypto_dh_env_t
*dh
= crypto_dh_new(DH_TYPE_TLS
);
873 SSL_CTX_set_tmp_dh(result
->ctx
, _crypto_dh_env_get_dh(dh
));
876 SSL_CTX_set_verify(result
->ctx
, SSL_VERIFY_PEER
,
877 always_accept_verify_cb
);
878 /* let us realloc bufs that we're writing from */
879 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
882 crypto_free_pk_env(rsa
);
888 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "creating TLS context");
894 crypto_free_pk_env(rsa
);
896 tor_tls_context_decref(result
);
904 #ifdef V2_HANDSHAKE_SERVER
905 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
906 * a list that indicates that the client knows how to do the v2 TLS connection
909 tor_tls_client_is_using_v2_ciphers(const SSL
*ssl
, const char *address
)
912 SSL_SESSION
*session
;
913 /* If we reached this point, we just got a client hello. See if there is
915 if (!(session
= SSL_get_session((SSL
*)ssl
))) {
916 log_info(LD_NET
, "No session on TLS?");
919 if (!session
->ciphers
) {
920 log_info(LD_NET
, "No ciphers on session");
923 /* Now we need to see if there are any ciphers whose presence means we're
924 * dealing with an updated Tor. */
925 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
926 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
927 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
928 if (strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
) &&
929 strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA
) &&
930 strcmp(ciphername
, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
) &&
931 strcmp(ciphername
, "(NONE)")) {
932 log_debug(LD_NET
, "Got a non-version-1 cipher called '%s'", ciphername
);
940 smartlist_t
*elts
= smartlist_create();
942 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
943 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
944 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
945 smartlist_add(elts
, (char*)ciphername
);
947 s
= smartlist_join_strings(elts
, ":", 0, NULL
);
948 log_debug(LD_NET
, "Got a non-version-1 cipher list from %s. It is: '%s'",
951 smartlist_free(elts
);
957 tor_tls_debug_state_callback(const SSL
*ssl
, int type
, int val
)
959 log_debug(LD_HANDSHAKE
, "SSL %p is now in state %s [type=%d,val=%d].",
960 ssl
, ssl_state_to_string(ssl
->state
), type
, val
);
963 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
964 * changes state. We use this:
965 * <ul><li>To alter the state of the handshake partway through, so we
966 * do not send or request extra certificates in v2 handshakes.</li>
967 * <li>To detect renegotiation</li></ul>
970 tor_tls_server_info_callback(const SSL
*ssl
, int type
, int val
)
975 tor_tls_debug_state_callback(ssl
, type
, val
);
977 if (type
!= SSL_CB_ACCEPT_LOOP
)
979 if (ssl
->state
!= SSL3_ST_SW_SRVR_HELLO_A
)
982 tls
= tor_tls_get_by_ssl(ssl
);
984 /* Check whether we're watching for renegotiates. If so, this is one! */
985 if (tls
->negotiated_callback
)
986 tls
->got_renegotiate
= 1;
987 if (tls
->server_handshake_count
< 127) /*avoid any overflow possibility*/
988 ++tls
->server_handshake_count
;
990 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
994 /* Now check the cipher list. */
995 if (tor_tls_client_is_using_v2_ciphers(ssl
, ADDR(tls
))) {
996 /*XXXX_TLS keep this from happening more than once! */
998 /* Yes, we're casting away the const from ssl. This is very naughty of us.
999 * Let's hope openssl doesn't notice! */
1001 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
1002 SSL_set_mode((SSL
*) ssl
, SSL_MODE_NO_AUTO_CHAIN
);
1003 /* Don't send a hello request. */
1004 SSL_set_verify((SSL
*) ssl
, SSL_VERIFY_NONE
, NULL
);
1007 tls
->wasV2Handshake
= 1;
1008 #ifdef USE_BUFFEREVENTS
1009 if (use_unsafe_renegotiation_flag
)
1010 tls
->ssl
->s3
->flags
|= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
;
1013 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
1019 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
1020 * a list designed to mimic a common web browser. Some of the ciphers in the
1021 * list won't actually be implemented by OpenSSL: that's okay so long as the
1022 * server doesn't select them, and the server won't select anything besides
1023 * what's in SERVER_CIPHER_LIST.
1025 * [If the server <b>does</b> select a bogus cipher, we won't crash or
1026 * anything; we'll just fail later when we try to look up the cipher in
1027 * ssl->cipher_list_by_id.]
1030 rectify_client_ciphers(STACK_OF(SSL_CIPHER
) **ciphers
)
1032 #ifdef V2_HANDSHAKE_CLIENT
1033 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK
)) {
1034 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
1038 /* First, create a dummy SSL_CIPHER for every cipher. */
1039 CLIENT_CIPHER_DUMMIES
=
1040 tor_malloc_zero(sizeof(SSL_CIPHER
)*N_CLIENT_CIPHERS
);
1041 for (i
=0; i
< N_CLIENT_CIPHERS
; ++i
) {
1042 CLIENT_CIPHER_DUMMIES
[i
].valid
= 1;
1043 CLIENT_CIPHER_DUMMIES
[i
].id
= CLIENT_CIPHER_INFO_LIST
[i
].id
| (3<<24);
1044 CLIENT_CIPHER_DUMMIES
[i
].name
= CLIENT_CIPHER_INFO_LIST
[i
].name
;
1047 CLIENT_CIPHER_STACK
= sk_SSL_CIPHER_new_null();
1048 tor_assert(CLIENT_CIPHER_STACK
);
1050 log_debug(LD_NET
, "List was: %s", CLIENT_CIPHER_LIST
);
1051 for (j
= 0; j
< sk_SSL_CIPHER_num(*ciphers
); ++j
) {
1052 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
1053 log_debug(LD_NET
, "Cipher %d: %lx %s", j
, cipher
->id
, cipher
->name
);
1056 /* Then copy as many ciphers as we can from the good list, inserting
1057 * dummies as needed. */
1059 for (i
= 0; i
< N_CLIENT_CIPHERS
; ) {
1060 SSL_CIPHER
*cipher
= NULL
;
1061 if (j
< sk_SSL_CIPHER_num(*ciphers
))
1062 cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
1063 if (cipher
&& ((cipher
->id
>> 24) & 0xff) != 3) {
1064 log_debug(LD_NET
, "Skipping v2 cipher %s", cipher
->name
);
1066 } else if (cipher
&&
1067 (cipher
->id
& 0xffff) == CLIENT_CIPHER_INFO_LIST
[i
].id
) {
1068 log_debug(LD_NET
, "Found cipher %s", cipher
->name
);
1069 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, cipher
);
1073 log_debug(LD_NET
, "Inserting fake %s", CLIENT_CIPHER_DUMMIES
[i
].name
);
1074 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, &CLIENT_CIPHER_DUMMIES
[i
]);
1080 sk_SSL_CIPHER_free(*ciphers
);
1081 *ciphers
= sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK
);
1082 tor_assert(*ciphers
);
1089 /** Create a new TLS object from a file descriptor, and a flag to
1090 * determine whether it is functioning as a server.
1093 tor_tls_new(int sock
, int isServer
)
1096 tor_tls_t
*result
= tor_malloc_zero(sizeof(tor_tls_t
));
1097 tor_tls_context_t
*context
= isServer
? server_tls_context
:
1099 result
->magic
= TOR_TLS_MAGIC
;
1101 tor_assert(context
); /* make sure somebody made it first */
1102 if (!(result
->ssl
= SSL_new(context
->ctx
))) {
1103 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "creating SSL object");
1108 #ifdef SSL_set_tlsext_host_name
1109 /* Browsers use the TLS hostname extension, so we should too. */
1111 char *fake_hostname
= crypto_random_hostname(4,25, "www.",".com");
1112 SSL_set_tlsext_host_name(result
->ssl
, fake_hostname
);
1113 tor_free(fake_hostname
);
1117 if (!SSL_set_cipher_list(result
->ssl
,
1118 isServer
? SERVER_CIPHER_LIST
: CLIENT_CIPHER_LIST
)) {
1119 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "setting ciphers");
1120 #ifdef SSL_set_tlsext_host_name
1121 SSL_set_tlsext_host_name(result
->ssl
, NULL
);
1123 SSL_free(result
->ssl
);
1128 rectify_client_ciphers(&result
->ssl
->cipher_list
);
1129 result
->socket
= sock
;
1130 bio
= BIO_new_socket(sock
, BIO_NOCLOSE
);
1132 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "opening BIO");
1133 #ifdef SSL_set_tlsext_host_name
1134 SSL_set_tlsext_host_name(result
->ssl
, NULL
);
1136 SSL_free(result
->ssl
);
1142 SSL_set_ex_data(result
->ssl
, tor_tls_object_ex_data_index
, result
);
1145 "Couldn't set the tls for an SSL*; connection will fail");
1148 SSL_set_bio(result
->ssl
, bio
, bio
);
1149 tor_tls_context_incref(context
);
1150 result
->context
= context
;
1151 result
->state
= TOR_TLS_ST_HANDSHAKE
;
1152 result
->isServer
= isServer
;
1153 result
->wantwrite_n
= 0;
1154 result
->last_write_count
= BIO_number_written(bio
);
1155 result
->last_read_count
= BIO_number_read(bio
);
1156 if (result
->last_write_count
|| result
->last_read_count
) {
1157 log_warn(LD_NET
, "Newly created BIO has read count %lu, write count %lu",
1158 result
->last_read_count
, result
->last_write_count
);
1160 #ifdef V2_HANDSHAKE_SERVER
1162 SSL_set_info_callback(result
->ssl
, tor_tls_server_info_callback
);
1166 SSL_set_info_callback(result
->ssl
, tor_tls_debug_state_callback
);
1169 /* Not expected to get called. */
1170 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "creating tor_tls_t object");
1174 /** Make future log messages about <b>tls</b> display the address
1178 tor_tls_set_logged_address(tor_tls_t
*tls
, const char *address
)
1181 tor_free(tls
->address
);
1182 tls
->address
= tor_strdup(address
);
1185 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1186 * next gets a client-side renegotiate in the middle of a read. Do not
1187 * invoke this function until <em>after</em> initial handshaking is done!
1190 tor_tls_set_renegotiate_callback(tor_tls_t
*tls
,
1191 void (*cb
)(tor_tls_t
*, void *arg
),
1194 tls
->negotiated_callback
= cb
;
1195 tls
->callback_arg
= arg
;
1196 tls
->got_renegotiate
= 0;
1197 #ifdef V2_HANDSHAKE_SERVER
1199 SSL_set_info_callback(tls
->ssl
, tor_tls_server_info_callback
);
1201 SSL_set_info_callback(tls
->ssl
, tor_tls_debug_state_callback
);
1206 /** If this version of openssl requires it, turn on renegotiation on
1210 tor_tls_unblock_renegotiation(tor_tls_t
*tls
)
1212 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1213 * as authenticating any earlier-received data. */
1214 if (use_unsafe_renegotiation_flag
) {
1215 tls
->ssl
->s3
->flags
|= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
;
1217 if (use_unsafe_renegotiation_op
) {
1218 SSL_set_options(tls
->ssl
,
1219 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
);
1223 /** If this version of openssl supports it, turn off renegotiation on
1224 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1225 * to use belt-and-suspenders here.)
1228 tor_tls_block_renegotiation(tor_tls_t
*tls
)
1230 tls
->ssl
->s3
->flags
&= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
;
1234 tor_tls_assert_renegotiation_unblocked(tor_tls_t
*tls
)
1236 if (use_unsafe_renegotiation_flag
) {
1237 tor_assert(0 != (tls
->ssl
->s3
->flags
&
1238 SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
));
1240 if (use_unsafe_renegotiation_op
) {
1241 long options
= SSL_get_options(tls
->ssl
);
1242 tor_assert(0 != (options
& SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
));
1246 /** Return whether this tls initiated the connect (client) or
1247 * received it (server). */
1249 tor_tls_is_server(tor_tls_t
*tls
)
1252 return tls
->isServer
;
1255 /** Release resources associated with a TLS object. Does not close the
1256 * underlying file descriptor.
1259 tor_tls_free(tor_tls_t
*tls
)
1263 tor_assert(tls
->ssl
);
1264 #ifdef SSL_set_tlsext_host_name
1265 SSL_set_tlsext_host_name(tls
->ssl
, NULL
);
1269 tls
->negotiated_callback
= NULL
;
1271 tor_tls_context_decref(tls
->context
);
1272 tor_free(tls
->address
);
1273 tls
->magic
= 0x99999999;
1277 /** Underlying function for TLS reading. Reads up to <b>len</b>
1278 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1279 * number of characters read. On failure, returns TOR_TLS_ERROR,
1280 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1283 tor_tls_read(tor_tls_t
*tls
, char *cp
, size_t len
)
1287 tor_assert(tls
->ssl
);
1288 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
1289 tor_assert(len
<INT_MAX
);
1290 r
= SSL_read(tls
->ssl
, cp
, (int)len
);
1292 #ifdef V2_HANDSHAKE_SERVER
1293 if (tls
->got_renegotiate
) {
1294 /* Renegotiation happened! */
1295 log_info(LD_NET
, "Got a TLS renegotiation from %s", ADDR(tls
));
1296 if (tls
->negotiated_callback
)
1297 tls
->negotiated_callback(tls
, tls
->callback_arg
);
1298 tls
->got_renegotiate
= 0;
1303 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_DEBUG
, LD_NET
);
1304 if (err
== _TOR_TLS_ZERORETURN
|| err
== TOR_TLS_CLOSE
) {
1305 log_debug(LD_NET
,"read returned r=%d; TLS is closed",r
);
1306 tls
->state
= TOR_TLS_ST_CLOSED
;
1307 return TOR_TLS_CLOSE
;
1309 tor_assert(err
!= TOR_TLS_DONE
);
1310 log_debug(LD_NET
,"read returned r=%d, err=%d",r
,err
);
1315 /** Underlying function for TLS writing. Write up to <b>n</b>
1316 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1317 * number of characters written. On failure, returns TOR_TLS_ERROR,
1318 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1321 tor_tls_write(tor_tls_t
*tls
, const char *cp
, size_t n
)
1325 tor_assert(tls
->ssl
);
1326 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
1327 tor_assert(n
< INT_MAX
);
1330 if (tls
->wantwrite_n
) {
1331 /* if WANTWRITE last time, we must use the _same_ n as before */
1332 tor_assert(n
>= tls
->wantwrite_n
);
1333 log_debug(LD_NET
,"resuming pending-write, (%d to flush, reusing %d)",
1334 (int)n
, (int)tls
->wantwrite_n
);
1335 n
= tls
->wantwrite_n
;
1336 tls
->wantwrite_n
= 0;
1338 r
= SSL_write(tls
->ssl
, cp
, (int)n
);
1339 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
, LD_NET
);
1340 if (err
== TOR_TLS_DONE
) {
1343 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
1344 tls
->wantwrite_n
= n
;
1349 /** Perform initial handshake on <b>tls</b>. When finished, returns
1350 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1351 * or TOR_TLS_WANTWRITE.
1354 tor_tls_handshake(tor_tls_t
*tls
)
1359 tor_assert(tls
->ssl
);
1360 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
1361 check_no_tls_errors();
1362 oldstate
= tls
->ssl
->state
;
1363 if (tls
->isServer
) {
1364 log_debug(LD_HANDSHAKE
, "About to call SSL_accept on %p (%s)", tls
,
1365 ssl_state_to_string(tls
->ssl
->state
));
1366 r
= SSL_accept(tls
->ssl
);
1368 log_debug(LD_HANDSHAKE
, "About to call SSL_connect on %p (%s)", tls
,
1369 ssl_state_to_string(tls
->ssl
->state
));
1370 r
= SSL_connect(tls
->ssl
);
1372 if (oldstate
!= tls
->ssl
->state
)
1373 log_debug(LD_HANDSHAKE
, "After call, %p was in state %s",
1374 tls
, ssl_state_to_string(tls
->ssl
->state
));
1375 /* We need to call this here and not earlier, since OpenSSL has a penchant
1376 * for clearing its flags when you say accept or connect. */
1377 tor_tls_unblock_renegotiation(tls
);
1378 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
, LD_HANDSHAKE
);
1379 if (ERR_peek_error() != 0) {
1380 tls_log_errors(tls
, tls
->isServer
? LOG_INFO
: LOG_WARN
, LD_HANDSHAKE
,
1382 return TOR_TLS_ERROR_MISC
;
1384 if (r
== TOR_TLS_DONE
) {
1385 tls
->state
= TOR_TLS_ST_OPEN
;
1386 return tor_tls_finish_handshake(tls
);
1391 /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
1392 * should be called for the first handshake only: it determines whether the v1
1393 * or the v2 handshake was used, and adjusts things for the renegotiation
1394 * handshake as appropriate.
1396 * tor_tls_handshake() calls this on its own; you only need to call this if
1397 * bufferevent is doing the handshake for you.
1400 tor_tls_finish_handshake(tor_tls_t
*tls
)
1402 int r
= TOR_TLS_DONE
;
1403 if (tls
->isServer
) {
1404 SSL_set_info_callback(tls
->ssl
, NULL
);
1405 SSL_set_verify(tls
->ssl
, SSL_VERIFY_PEER
, always_accept_verify_cb
);
1406 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1407 tls
->ssl
->mode
&= ~SSL_MODE_NO_AUTO_CHAIN
;
1408 #ifdef V2_HANDSHAKE_SERVER
1409 if (tor_tls_client_is_using_v2_ciphers(tls
->ssl
, ADDR(tls
))) {
1410 /* This check is redundant, but back when we did it in the callback,
1411 * we might have not been able to look up the tor_tls_t if the code
1412 * was buggy. Fixing that. */
1413 if (!tls
->wasV2Handshake
) {
1414 log_warn(LD_BUG
, "For some reason, wasV2Handshake didn't"
1415 " get set. Fixing that.");
1417 tls
->wasV2Handshake
= 1;
1418 log_debug(LD_HANDSHAKE
, "Completed V2 TLS handshake with client; waiting"
1419 " for renegotiation.");
1421 tls
->wasV2Handshake
= 0;
1425 #ifdef V2_HANDSHAKE_CLIENT
1426 /* If we got no ID cert, we're a v2 handshake. */
1427 X509
*cert
= SSL_get_peer_certificate(tls
->ssl
);
1428 STACK_OF(X509
) *chain
= SSL_get_peer_cert_chain(tls
->ssl
);
1429 int n_certs
= sk_X509_num(chain
);
1430 if (n_certs
> 1 || (n_certs
== 1 && cert
!= sk_X509_value(chain
, 0))) {
1431 log_debug(LD_HANDSHAKE
, "Server sent back multiple certificates; it "
1432 "looks like a v1 handshake on %p", tls
);
1433 tls
->wasV2Handshake
= 0;
1435 log_debug(LD_HANDSHAKE
,
1436 "Server sent back a single certificate; looks like "
1437 "a v2 handshake on %p.", tls
);
1438 tls
->wasV2Handshake
= 1;
1443 if (SSL_set_cipher_list(tls
->ssl
, SERVER_CIPHER_LIST
) == 0) {
1444 tls_log_errors(NULL
, LOG_WARN
, LD_HANDSHAKE
, "re-setting ciphers");
1445 r
= TOR_TLS_ERROR_MISC
;
1451 #ifdef USE_BUFFEREVENTS
1452 /** Put <b>tls</b>, which must be a client connection, into renegotiation
1455 tor_tls_start_renegotiating(tor_tls_t
*tls
)
1457 int r
= SSL_renegotiate(tls
->ssl
);
1459 return tor_tls_get_error(tls
, r
, 0, "renegotiating", LOG_WARN
,
1466 /** Client only: Renegotiate a TLS session. When finished, returns
1467 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1468 * TOR_TLS_WANTWRITE.
1471 tor_tls_renegotiate(tor_tls_t
*tls
)
1475 /* We could do server-initiated renegotiation too, but that would be tricky.
1476 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1477 tor_assert(!tls
->isServer
);
1478 if (tls
->state
!= TOR_TLS_ST_RENEGOTIATE
) {
1479 int r
= SSL_renegotiate(tls
->ssl
);
1481 return tor_tls_get_error(tls
, r
, 0, "renegotiating", LOG_WARN
,
1484 tls
->state
= TOR_TLS_ST_RENEGOTIATE
;
1486 r
= SSL_do_handshake(tls
->ssl
);
1488 tls
->state
= TOR_TLS_ST_OPEN
;
1489 return TOR_TLS_DONE
;
1491 return tor_tls_get_error(tls
, r
, 0, "renegotiating handshake", LOG_INFO
,
1495 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1496 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1497 * or TOR_TLS_WANTWRITE.
1500 tor_tls_shutdown(tor_tls_t
*tls
)
1505 tor_assert(tls
->ssl
);
1508 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1509 /* If we've already called shutdown once to send a close message,
1510 * we read until the other side has closed too.
1513 r
= SSL_read(tls
->ssl
, buf
, 128);
1515 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
1517 if (err
== _TOR_TLS_ZERORETURN
) {
1518 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
1519 /* fall through... */
1525 r
= SSL_shutdown(tls
->ssl
);
1527 /* If shutdown returns 1, the connection is entirely closed. */
1528 tls
->state
= TOR_TLS_ST_CLOSED
;
1529 return TOR_TLS_DONE
;
1531 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
1533 if (err
== _TOR_TLS_SYSCALL
) {
1534 /* The underlying TCP connection closed while we were shutting down. */
1535 tls
->state
= TOR_TLS_ST_CLOSED
;
1536 return TOR_TLS_DONE
;
1537 } else if (err
== _TOR_TLS_ZERORETURN
) {
1538 /* The TLS connection says that it sent a shutdown record, but
1539 * isn't done shutting down yet. Make sure that this hasn't
1540 * happened before, then go back to the start of the function
1543 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
1544 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1545 log(LOG_WARN
, LD_NET
,
1546 "TLS returned \"half-closed\" value while already half-closed");
1547 return TOR_TLS_ERROR_MISC
;
1549 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
1550 /* fall through ... */
1557 /** Return true iff this TLS connection is authenticated.
1560 tor_tls_peer_has_cert(tor_tls_t
*tls
)
1563 cert
= SSL_get_peer_certificate(tls
->ssl
);
1564 tls_log_errors(tls
, LOG_WARN
, LD_HANDSHAKE
, "getting peer certificate");
1571 /** Warn that a certificate lifetime extends through a certain range. */
1573 log_cert_lifetime(X509
*cert
, const char *problem
)
1577 char *s1
=NULL
, *s2
=NULL
;
1579 time_t now
= time(NULL
);
1583 log_warn(LD_GENERAL
,
1584 "Certificate %s: is your system clock set incorrectly?",
1587 if (!(bio
= BIO_new(BIO_s_mem()))) {
1588 log_warn(LD_GENERAL
, "Couldn't allocate BIO!"); goto end
;
1590 if (!(ASN1_TIME_print(bio
, X509_get_notBefore(cert
)))) {
1591 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "printing certificate lifetime");
1594 BIO_get_mem_ptr(bio
, &buf
);
1595 s1
= tor_strndup(buf
->data
, buf
->length
);
1597 (void)BIO_reset(bio
);
1598 if (!(ASN1_TIME_print(bio
, X509_get_notAfter(cert
)))) {
1599 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "printing certificate lifetime");
1602 BIO_get_mem_ptr(bio
, &buf
);
1603 s2
= tor_strndup(buf
->data
, buf
->length
);
1605 strftime(mytime
, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now
, &tm
));
1607 log_warn(LD_GENERAL
,
1608 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1612 /* Not expected to get invoked */
1613 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "getting certificate lifetime");
1620 /** Helper function: try to extract a link certificate and an identity
1621 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1622 * *<b>id_cert_out</b> respectively. Log all messages at level
1625 * Note that a reference is added to cert_out, so it needs to be
1626 * freed. id_cert_out doesn't. */
1628 try_to_extract_certs_from_tls(int severity
, tor_tls_t
*tls
,
1629 X509
**cert_out
, X509
**id_cert_out
)
1631 X509
*cert
= NULL
, *id_cert
= NULL
;
1632 STACK_OF(X509
) *chain
= NULL
;
1633 int num_in_chain
, i
;
1634 *cert_out
= *id_cert_out
= NULL
;
1636 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1639 if (!(chain
= SSL_get_peer_cert_chain(tls
->ssl
)))
1641 num_in_chain
= sk_X509_num(chain
);
1642 /* 1 means we're receiving (server-side), and it's just the id_cert.
1643 * 2 means we're connecting (client-side), and it's both the link
1644 * cert and the id_cert.
1646 if (num_in_chain
< 1) {
1647 log_fn(severity
,LD_PROTOCOL
,
1648 "Unexpected number of certificates in chain (%d)",
1652 for (i
=0; i
<num_in_chain
; ++i
) {
1653 id_cert
= sk_X509_value(chain
, i
);
1654 if (X509_cmp(id_cert
, cert
) != 0)
1657 *id_cert_out
= id_cert
;
1660 /** If the provided tls connection is authenticated and has a
1661 * certificate chain that is currently valid and signed, then set
1662 * *<b>identity_key</b> to the identity certificate's key and return
1663 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1666 tor_tls_verify(int severity
, tor_tls_t
*tls
, crypto_pk_env_t
**identity_key
)
1668 X509
*cert
= NULL
, *id_cert
= NULL
;
1669 EVP_PKEY
*id_pkey
= NULL
;
1673 *identity_key
= NULL
;
1675 try_to_extract_certs_from_tls(severity
, tls
, &cert
, &id_cert
);
1679 log_fn(severity
,LD_PROTOCOL
,"No distinct identity certificate found");
1682 tls_log_errors(tls
, severity
, LD_HANDSHAKE
, "before verifying certificate");
1684 if (!(id_pkey
= X509_get_pubkey(id_cert
)) ||
1685 X509_verify(cert
, id_pkey
) <= 0) {
1686 log_fn(severity
,LD_PROTOCOL
,"X509_verify on cert and pkey returned <= 0");
1687 tls_log_errors(tls
, severity
, LD_HANDSHAKE
, "verifying certificate");
1691 rsa
= EVP_PKEY_get1_RSA(id_pkey
);
1694 *identity_key
= _crypto_new_pk_env_rsa(rsa
);
1702 EVP_PKEY_free(id_pkey
);
1704 /* This should never get invoked, but let's make sure in case OpenSSL
1705 * acts unexpectedly. */
1706 tls_log_errors(tls
, LOG_WARN
, LD_HANDSHAKE
, "finishing tor_tls_verify");
1711 /** Check whether the certificate set on the connection <b>tls</b> is
1712 * expired or not-yet-valid, give or take <b>tolerance</b>
1713 * seconds. Return 0 for valid, -1 for failure.
1715 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1718 tor_tls_check_lifetime(tor_tls_t
*tls
, int tolerance
)
1726 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1729 t
= now
+ tolerance
;
1730 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
1731 log_cert_lifetime(cert
, "not yet valid");
1734 t
= now
- tolerance
;
1735 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
1736 log_cert_lifetime(cert
, "already expired");
1744 /* Not expected to get invoked */
1745 tls_log_errors(tls
, LOG_WARN
, LD_NET
, "checking certificate lifetime");
1750 /** Return the number of bytes available for reading from <b>tls</b>.
1753 tor_tls_get_pending_bytes(tor_tls_t
*tls
)
1756 return SSL_pending(tls
->ssl
);
1759 /** If <b>tls</b> requires that the next write be of a particular size,
1760 * return that size. Otherwise, return 0. */
1762 tor_tls_get_forced_write_size(tor_tls_t
*tls
)
1764 return tls
->wantwrite_n
;
1767 /** Sets n_read and n_written to the number of bytes read and written,
1768 * respectively, on the raw socket used by <b>tls</b> since the last time this
1769 * function was called on <b>tls</b>. */
1771 tor_tls_get_n_raw_bytes(tor_tls_t
*tls
, size_t *n_read
, size_t *n_written
)
1775 r
= BIO_number_read(SSL_get_rbio(tls
->ssl
));
1776 /* We want the number of bytes actually for real written. Unfortunately,
1777 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1778 * which makes the answer turn out wrong. Let's cope with that. Note
1779 * that this approach will fail if we ever replace tls->ssl's BIOs with
1780 * buffering bios for reasons of our own. As an alternative, we could
1781 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1782 * that would be tempting fate. */
1783 wbio
= SSL_get_wbio(tls
->ssl
);
1784 if (wbio
->method
== BIO_f_buffer() && (tmpbio
= BIO_next(wbio
)) != NULL
)
1786 w
= BIO_number_written(wbio
);
1788 /* We are ok with letting these unsigned ints go "negative" here:
1789 * If we wrapped around, this should still give us the right answer, unless
1790 * we wrapped around by more than ULONG_MAX since the last time we called
1793 *n_read
= (size_t)(r
- tls
->last_read_count
);
1794 *n_written
= (size_t)(w
- tls
->last_write_count
);
1795 if (*n_read
> INT_MAX
|| *n_written
> INT_MAX
) {
1796 log_warn(LD_BUG
, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1797 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1798 r
, tls
->last_read_count
, w
, tls
->last_write_count
);
1800 tls
->last_read_count
= r
;
1801 tls
->last_write_count
= w
;
1804 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1805 * errors, log an error message. */
1807 _check_no_tls_errors(const char *fname
, int line
)
1809 if (ERR_peek_error() == 0)
1811 log(LOG_WARN
, LD_CRYPTO
, "Unhandled OpenSSL errors found at %s:%d: ",
1812 tor_fix_source_file(fname
), line
);
1813 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, NULL
);
1816 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1817 * TLS handshake. Output is undefined if the handshake isn't finished. */
1819 tor_tls_used_v1_handshake(tor_tls_t
*tls
)
1821 if (tls
->isServer
) {
1822 #ifdef V2_HANDSHAKE_SERVER
1823 return ! tls
->wasV2Handshake
;
1826 #ifdef V2_HANDSHAKE_CLIENT
1827 return ! tls
->wasV2Handshake
;
1833 /** Return the number of server handshakes that we've noticed doing on
1836 tor_tls_get_num_server_handshakes(tor_tls_t
*tls
)
1838 return tls
->server_handshake_count
;
1841 /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
1842 * request it was waiting for. */
1844 tor_tls_server_got_renegotiate(tor_tls_t
*tls
)
1846 return tls
->got_renegotiate
;
1849 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1850 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1851 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1852 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1853 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1855 tor_tls_get_buffer_sizes(tor_tls_t
*tls
,
1856 size_t *rbuf_capacity
, size_t *rbuf_bytes
,
1857 size_t *wbuf_capacity
, size_t *wbuf_bytes
)
1859 if (tls
->ssl
->s3
->rbuf
.buf
)
1860 *rbuf_capacity
= tls
->ssl
->s3
->rbuf
.len
;
1863 if (tls
->ssl
->s3
->wbuf
.buf
)
1864 *wbuf_capacity
= tls
->ssl
->s3
->wbuf
.len
;
1867 *rbuf_bytes
= tls
->ssl
->s3
->rbuf
.left
;
1868 *wbuf_bytes
= tls
->ssl
->s3
->wbuf
.left
;
1871 #ifdef USE_BUFFEREVENTS
1872 /** Construct and return an TLS-encrypting bufferevent to send data over
1873 * <b>socket</b>, which must match the socket of the underlying bufferevent
1874 * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
1876 * This function will either create a filtering bufferevent that wraps around
1877 * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
1878 * uses the <b>tls</b> to talk to the network directly. Do not use
1879 * <b>bufev_in</b> after calling this function.
1881 * The connection will start out doing a server handshake if <b>receiving</b>
1882 * is strue, and a client handshake otherwise.
1884 * Returns NULL on failure.
1886 struct bufferevent
*
1887 tor_tls_init_bufferevent(tor_tls_t
*tls
, struct bufferevent
*bufev_in
,
1888 evutil_socket_t socket
, int receiving
,
1891 struct bufferevent
*out
;
1892 const enum bufferevent_ssl_state state
= receiving
?
1893 BUFFEREVENT_SSL_ACCEPTING
: BUFFEREVENT_SSL_CONNECTING
;
1896 /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
1897 means that the SSL will get freed too.
1899 This increment makes our SSL usage not-threadsafe, BTW. We should
1900 see if we're allowed to use CRYPTO_add from outside openssl. */
1901 tls
->ssl
->references
+= 1;
1902 out
= bufferevent_openssl_filter_new(tor_libevent_get_base(),
1906 BEV_OPT_DEFER_CALLBACKS
|
1907 BEV_OPT_CLOSE_ON_FREE
);
1910 evutil_socket_t s
= bufferevent_getfd(bufev_in
);
1911 tor_assert(s
== -1 || s
== socket
);
1912 tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in
)) == 0);
1913 tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in
)) == 0);
1914 tor_assert(BIO_number_read(SSL_get_rbio(tls
->ssl
)) == 0);
1915 tor_assert(BIO_number_written(SSL_get_rbio(tls
->ssl
)) == 0);
1916 bufferevent_free(bufev_in
);
1919 /* Current versions (as of 2.0.x) of Libevent need to defer
1920 * bufferevent_openssl callbacks, or else our callback functions will
1921 * get called reentrantly, which is bad for us.
1923 out
= bufferevent_openssl_socket_new(tor_libevent_get_base(),
1927 BEV_OPT_DEFER_CALLBACKS
);
1929 tls
->state
= TOR_TLS_ST_BUFFEREVENT
;
1931 /* Unblock _after_ creating the bufferevent, since accept/connect tend to
1933 tor_tls_unblock_renegotiation(tls
);