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>"*/
25 #define WIN32_WINNT 0x400
26 #define _WIN32_WINNT 0x400
27 #define WIN32_LEAN_AND_MEAN
28 #if defined(_MSC_VER) && (_MSC_VER < 1300)
35 #include <openssl/ssl.h>
36 #include <openssl/ssl3.h>
37 #include <openssl/err.h>
38 #include <openssl/tls1.h>
39 #include <openssl/asn1.h>
40 #include <openssl/bio.h>
41 #include <openssl/opensslv.h>
43 #if OPENSSL_VERSION_NUMBER < 0x00907000l
44 #error "We require OpenSSL >= 0.9.7"
47 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
53 #include "container.h"
57 /* Enable the "v2" TLS handshake.
59 #define V2_HANDSHAKE_SERVER
60 #define V2_HANDSHAKE_CLIENT
62 /* Copied from or.h */
63 #define LEGAL_NICKNAME_CHARACTERS \
64 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
66 /** How long do identity certificates live? (sec) */
67 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
69 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
71 /* We redefine these so that we can run correctly even if the vendor gives us
72 * a version of OpenSSL that does not match its header files. (Apple: I am
75 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
76 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
78 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
79 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
82 /** Does the run-time openssl version look like we need
83 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
84 static int use_unsafe_renegotiation_op
= 0;
85 /** Does the run-time openssl version look like we need
86 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
87 static int use_unsafe_renegotiation_flag
= 0;
89 /** Holds a SSL_CTX object and related state used to configure TLS
92 typedef struct tor_tls_context_t
{
100 /** Holds a SSL object and its associated data. Members are only
101 * accessed from within tortls.c.
104 HT_ENTRY(tor_tls_t
) node
;
105 tor_tls_context_t
*context
; /** A link to the context object for this tls. */
106 SSL
*ssl
; /**< An OpenSSL SSL object. */
107 int socket
; /**< The underlying file descriptor for this TLS connection. */
108 char *address
; /**< An address to log when describing this connection. */
110 TOR_TLS_ST_HANDSHAKE
, TOR_TLS_ST_OPEN
, TOR_TLS_ST_GOTCLOSE
,
111 TOR_TLS_ST_SENTCLOSE
, TOR_TLS_ST_CLOSED
, TOR_TLS_ST_RENEGOTIATE
,
112 } state
: 3; /**< The current SSL state, depending on which operations have
113 * completed successfully. */
114 unsigned int isServer
:1; /**< True iff this is a server-side connection */
115 unsigned int wasV2Handshake
:1; /**< True iff the original handshake for
116 * this connection used the updated version
117 * of the connection protocol (client sends
118 * different cipher list, server sends only
119 * one certificate). */
120 /** True iff we should call negotiated_callback when we're done reading. */
121 unsigned int got_renegotiate
:1;
122 size_t wantwrite_n
; /**< 0 normally, >0 if we returned wantwrite last
124 /** Last values retrieved from BIO_number_read()/write(); see
125 * tor_tls_get_n_raw_bytes() for usage.
127 unsigned long last_write_count
;
128 unsigned long last_read_count
;
129 /** If set, a callback to invoke whenever the client tries to renegotiate
131 void (*negotiated_callback
)(tor_tls_t
*tls
, void *arg
);
132 /** Argument to pass to negotiated_callback. */
136 #ifdef V2_HANDSHAKE_CLIENT
137 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
138 * in client mode into advertising the ciphers we want. See
139 * rectify_client_ciphers() for details. */
140 static SSL_CIPHER
*CLIENT_CIPHER_DUMMIES
= NULL
;
141 /** A stack of SSL_CIPHER objects, some real, some fake.
142 * See rectify_client_ciphers() for details. */
143 static STACK_OF(SSL_CIPHER
) *CLIENT_CIPHER_STACK
= NULL
;
146 /** Helper: compare tor_tls_t objects by its SSL. */
148 tor_tls_entries_eq(const tor_tls_t
*a
, const tor_tls_t
*b
)
150 return a
->ssl
== b
->ssl
;
153 /** Helper: return a hash value for a tor_tls_t by its SSL. */
154 static INLINE
unsigned int
155 tor_tls_entry_hash(const tor_tls_t
*a
)
157 #if SIZEOF_INT == SIZEOF_VOID_P
158 return ((unsigned int)(uintptr_t)a
->ssl
);
160 return (unsigned int) ((((uint64_t)a
->ssl
)>>2) & UINT_MAX
);
164 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
166 static HT_HEAD(tlsmap
, tor_tls_t
) tlsmap_root
= HT_INITIALIZER();
168 HT_PROTOTYPE(tlsmap
, tor_tls_t
, node
, tor_tls_entry_hash
,
170 HT_GENERATE(tlsmap
, tor_tls_t
, node
, tor_tls_entry_hash
,
171 tor_tls_entries_eq
, 0.6, malloc
, realloc
, free
)
173 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
175 static INLINE tor_tls_t
*
176 tor_tls_get_by_ssl(const SSL
*ssl
)
178 tor_tls_t search
, *result
;
179 memset(&search
, 0, sizeof(search
));
180 search
.ssl
= (SSL
*)ssl
;
181 result
= HT_FIND(tlsmap
, &tlsmap_root
, &search
);
185 static void tor_tls_context_decref(tor_tls_context_t
*ctx
);
186 static void tor_tls_context_incref(tor_tls_context_t
*ctx
);
187 static X509
* tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
188 crypto_pk_env_t
*rsa_sign
,
190 const char *cname_sign
,
191 unsigned int lifetime
);
192 static void tor_tls_unblock_renegotiation(tor_tls_t
*tls
);
193 static int tor_tls_context_init_one(tor_tls_context_t
**ppcontext
,
194 crypto_pk_env_t
*identity
,
195 unsigned int key_lifetime
);
196 static tor_tls_context_t
*tor_tls_context_new(crypto_pk_env_t
*identity
,
197 unsigned int key_lifetime
);
199 /** Global TLS contexts. We keep them here because nobody else needs
201 static tor_tls_context_t
*server_tls_context
= NULL
;
202 static tor_tls_context_t
*client_tls_context
= NULL
;
203 /** True iff tor_tls_init() has been called. */
204 static int tls_library_is_initialized
= 0;
206 /* Module-internal error codes. */
207 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
208 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
210 #include "tortls_states.h"
212 /** Return the symbolic name of an OpenSSL state. */
214 ssl_state_to_string(int ssl_state
)
218 for (i
= 0; state_map
[i
].name
; ++i
) {
219 if (state_map
[i
].state
== ssl_state
)
220 return state_map
[i
].name
;
222 tor_snprintf(buf
, sizeof(buf
), "Unknown state %d", ssl_state
);
226 /** Log all pending tls errors at level <b>severity</b>. Use
227 * <b>doing</b> to describe our current activities.
230 tls_log_errors(tor_tls_t
*tls
, int severity
, int domain
, const char *doing
)
232 const char *state
= NULL
;
235 const char *msg
, *lib
, *func
, *addr
;
236 addr
= tls
? tls
->address
: NULL
;
237 st
= (tls
&& tls
->ssl
) ? tls
->ssl
->state
: -1;
238 while ((err
= ERR_get_error()) != 0) {
239 msg
= (const char*)ERR_reason_error_string(err
);
240 lib
= (const char*)ERR_lib_error_string(err
);
241 func
= (const char*)ERR_func_error_string(err
);
243 state
= (st
>=0)?ssl_state_to_string(st
):"---";
244 if (!msg
) msg
= "(null)";
245 if (!lib
) lib
= "(null)";
246 if (!func
) func
= "(null)";
248 log(severity
, domain
, "TLS error while %s%s%s: %s (in %s:%s:%s)",
249 doing
, addr
?" with ":"", addr
?addr
:"",
250 msg
, lib
, func
, state
);
252 log(severity
, domain
, "TLS error%s%s: %s (in %s:%s:%s)",
253 addr
?" with ":"", addr
?addr
:"",
254 msg
, lib
, func
, state
);
259 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
262 tor_errno_to_tls_error(int e
)
264 #if defined(MS_WINDOWS)
266 case WSAECONNRESET
: // most common
267 return TOR_TLS_ERROR_CONNRESET
;
269 return TOR_TLS_ERROR_TIMEOUT
;
271 case WSAEHOSTUNREACH
:
272 return TOR_TLS_ERROR_NO_ROUTE
;
273 case WSAECONNREFUSED
:
274 return TOR_TLS_ERROR_CONNREFUSED
; // least common
276 return TOR_TLS_ERROR_MISC
;
280 case ECONNRESET
: // most common
281 return TOR_TLS_ERROR_CONNRESET
;
283 return TOR_TLS_ERROR_TIMEOUT
;
286 return TOR_TLS_ERROR_NO_ROUTE
;
288 return TOR_TLS_ERROR_CONNREFUSED
; // least common
290 return TOR_TLS_ERROR_MISC
;
295 /** Given a TOR_TLS_* error code, return a string equivalent. */
297 tor_tls_err_to_string(int err
)
300 return "[Not an error.]";
302 case TOR_TLS_ERROR_MISC
: return "misc error";
303 case TOR_TLS_ERROR_IO
: return "unexpected close";
304 case TOR_TLS_ERROR_CONNREFUSED
: return "connection refused";
305 case TOR_TLS_ERROR_CONNRESET
: return "connection reset";
306 case TOR_TLS_ERROR_NO_ROUTE
: return "host unreachable";
307 case TOR_TLS_ERROR_TIMEOUT
: return "connection timed out";
308 case TOR_TLS_CLOSE
: return "closed";
309 case TOR_TLS_WANTREAD
: return "want to read";
310 case TOR_TLS_WANTWRITE
: return "want to write";
311 default: return "(unknown error code)";
315 #define CATCH_SYSCALL 1
318 /** Given a TLS object and the result of an SSL_* call, use
319 * SSL_get_error to determine whether an error has occurred, and if so
320 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
321 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
322 * reporting syscall errors. If extra&CATCH_ZERO is true, return
323 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
325 * If an error has occurred, log it at level <b>severity</b> and describe the
326 * current action as <b>doing</b>.
329 tor_tls_get_error(tor_tls_t
*tls
, int r
, int extra
,
330 const char *doing
, int severity
, int domain
)
332 int err
= SSL_get_error(tls
->ssl
, r
);
333 int tor_error
= TOR_TLS_ERROR_MISC
;
337 case SSL_ERROR_WANT_READ
:
338 return TOR_TLS_WANTREAD
;
339 case SSL_ERROR_WANT_WRITE
:
340 return TOR_TLS_WANTWRITE
;
341 case SSL_ERROR_SYSCALL
:
342 if (extra
&CATCH_SYSCALL
)
343 return _TOR_TLS_SYSCALL
;
345 log(severity
, LD_NET
, "TLS error: unexpected close while %s (%s)",
346 doing
, ssl_state_to_string(tls
->ssl
->state
));
347 tor_error
= TOR_TLS_ERROR_IO
;
349 int e
= tor_socket_errno(tls
->socket
);
350 log(severity
, LD_NET
,
351 "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
352 doing
, e
, tor_socket_strerror(e
),
353 ssl_state_to_string(tls
->ssl
->state
));
354 tor_error
= tor_errno_to_tls_error(e
);
356 tls_log_errors(tls
, severity
, domain
, doing
);
358 case SSL_ERROR_ZERO_RETURN
:
359 if (extra
&CATCH_ZERO
)
360 return _TOR_TLS_ZERORETURN
;
361 log(severity
, LD_NET
, "TLS connection closed while %s in state %s",
362 doing
, ssl_state_to_string(tls
->ssl
->state
));
363 tls_log_errors(tls
, severity
, domain
, doing
);
364 return TOR_TLS_CLOSE
;
366 tls_log_errors(tls
, severity
, domain
, doing
);
367 return TOR_TLS_ERROR_MISC
;
371 /** Initialize OpenSSL, unless it has already been initialized.
376 if (!tls_library_is_initialized
) {
379 SSL_load_error_strings();
383 /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
384 * here, but without thinking too hard about it: it turns out that the
385 * flag in question needed to be set at the last minute, and that it
386 * conflicted with an existing flag number that had already been added
387 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
388 * the flag with an option and (it seems) broke anything that used
389 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
390 * and we mustn't use the SSL3_FLAGS option with anything besides
393 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
394 * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
395 * set option 0x00040000L everywhere.
397 * No, we can't simply detect whether the flag or the option is present
398 * in the headers at build-time: some vendors (notably Apple) like to
399 * leave their headers out of sync with their libraries.
401 * Yes, it _is_ almost as if the OpenSSL developers decided that no
402 * program should be allowed to use renegotiation unless it first passed
403 * a test of intelligence and determination.
405 if (version
>= 0x009080c0L
&& version
< 0x009080d0L
) {
406 log_notice(LD_GENERAL
, "OpenSSL %s looks like version 0.9.8l; "
407 "I will try SSL3_FLAGS to enable renegotation.",
408 SSLeay_version(SSLEAY_VERSION
));
409 use_unsafe_renegotiation_flag
= 1;
410 use_unsafe_renegotiation_op
= 1;
411 } else if (version
>= 0x009080d0L
) {
412 log_notice(LD_GENERAL
, "OpenSSL %s looks like version 0.9.8m or later; "
413 "I will try SSL_OP to enable renegotiation",
414 SSLeay_version(SSLEAY_VERSION
));
415 use_unsafe_renegotiation_op
= 1;
416 } else if (version
< 0x009080c0L
) {
417 log_notice(LD_GENERAL
, "OpenSSL %s [%lx] looks like it's older than "
418 "0.9.8l, but some vendors have backported 0.9.8l's "
419 "renegotiation code to earlier versions, and some have "
420 "backported the code from 0.9.8m or 0.9.8n. I'll set both "
421 "SSL3_FLAGS and SSL_OP just to be safe.",
422 SSLeay_version(SSLEAY_VERSION
), version
);
423 use_unsafe_renegotiation_flag
= 1;
424 use_unsafe_renegotiation_op
= 1;
426 log_info(LD_GENERAL
, "OpenSSL %s has version %lx",
427 SSLeay_version(SSLEAY_VERSION
), version
);
430 tls_library_is_initialized
= 1;
434 /** Free all global TLS structures. */
436 tor_tls_free_all(void)
438 if (server_tls_context
) {
439 tor_tls_context_t
*ctx
= server_tls_context
;
440 server_tls_context
= NULL
;
441 tor_tls_context_decref(ctx
);
443 if (client_tls_context
) {
444 tor_tls_context_t
*ctx
= client_tls_context
;
445 client_tls_context
= NULL
;
446 tor_tls_context_decref(ctx
);
448 if (!HT_EMPTY(&tlsmap_root
)) {
449 log_warn(LD_MM
, "Still have entries in the tlsmap at shutdown.");
451 HT_CLEAR(tlsmap
, &tlsmap_root
);
452 #ifdef V2_HANDSHAKE_CLIENT
453 if (CLIENT_CIPHER_DUMMIES
)
454 tor_free(CLIENT_CIPHER_DUMMIES
);
455 if (CLIENT_CIPHER_STACK
)
456 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK
);
460 /** We need to give OpenSSL a callback to verify certificates. This is
461 * it: We always accept peer certs and complete the handshake. We
462 * don't validate them until later.
465 always_accept_verify_cb(int preverify_ok
,
466 X509_STORE_CTX
*x509_ctx
)
473 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
475 tor_x509_name_new(const char *cname
)
479 if (!(name
= X509_NAME_new()))
481 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
482 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
483 (unsigned char*)cname
, -1, -1, 0)))
487 X509_NAME_free(name
);
491 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
492 * signed by the private key <b>rsa_sign</b>. The commonName of the
493 * certificate will be <b>cname</b>; the commonName of the issuer will be
494 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
495 * starting from now. Return a certificate on success, NULL on
499 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
500 crypto_pk_env_t
*rsa_sign
,
502 const char *cname_sign
,
503 unsigned int cert_lifetime
)
505 time_t start_time
, end_time
;
506 EVP_PKEY
*sign_pkey
= NULL
, *pkey
=NULL
;
508 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
512 start_time
= time(NULL
);
516 tor_assert(rsa_sign
);
517 tor_assert(cname_sign
);
518 if (!(sign_pkey
= _crypto_pk_env_get_evp_pkey(rsa_sign
,1)))
520 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
522 if (!(x509
= X509_new()))
524 if (!(X509_set_version(x509
, 2)))
526 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
529 if (!(name
= tor_x509_name_new(cname
)))
531 if (!(X509_set_subject_name(x509
, name
)))
533 if (!(name_issuer
= tor_x509_name_new(cname_sign
)))
535 if (!(X509_set_issuer_name(x509
, name_issuer
)))
538 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
540 end_time
= start_time
+ cert_lifetime
;
541 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
543 if (!X509_set_pubkey(x509
, pkey
))
545 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
555 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "generating certificate");
557 EVP_PKEY_free(sign_pkey
);
561 X509_NAME_free(name
);
563 X509_NAME_free(name_issuer
);
567 /** List of ciphers that servers should select from.*/
568 #define SERVER_CIPHER_LIST \
569 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
570 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
571 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
572 /* Note: to set up your own private testing network with link crypto
573 * disabled, set your Tors' cipher list to
574 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
575 * with any of the "real" Tors, though. */
577 #ifdef V2_HANDSHAKE_CLIENT
578 #define CIPHER(id, name) name ":"
579 #define XCIPHER(id, name)
580 /** List of ciphers that clients should advertise, omitting items that
581 * our OpenSSL doesn't know about. */
582 static const char CLIENT_CIPHER_LIST
[] =
583 #include "./ciphers.inc"
588 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
589 typedef struct cipher_info_t
{ unsigned id
; const char *name
; } cipher_info_t
;
590 /** A list of all the ciphers that clients should advertise, including items
591 * that OpenSSL might not know about. */
592 static const cipher_info_t CLIENT_CIPHER_INFO_LIST
[] = {
593 #define CIPHER(id, name) { id, name },
594 #define XCIPHER(id, name) { id, #name },
595 #include "./ciphers.inc"
600 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
601 static const int N_CLIENT_CIPHERS
=
602 sizeof(CLIENT_CIPHER_INFO_LIST
)/sizeof(CLIENT_CIPHER_INFO_LIST
[0]);
605 #ifndef V2_HANDSHAKE_CLIENT
606 #undef CLIENT_CIPHER_LIST
607 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
608 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
611 /** Remove a reference to <b>ctx</b>, and free it if it has no more
614 tor_tls_context_decref(tor_tls_context_t
*ctx
)
617 if (--ctx
->refcnt
== 0) {
618 SSL_CTX_free(ctx
->ctx
);
619 X509_free(ctx
->my_cert
);
620 X509_free(ctx
->my_id_cert
);
621 crypto_free_pk_env(ctx
->key
);
626 /** Increase the reference count of <b>ctx</b>. */
628 tor_tls_context_incref(tor_tls_context_t
*ctx
)
633 /** Create new global client and server TLS contexts.
635 * If <b>server_identity</b> is NULL, this will not generate a server
636 * TLS context. If <b>is_public_server</b> is non-zero, this will use
637 * the same TLS context for incoming and outgoing connections, and
638 * ignore <b>client_identity</b>. */
640 tor_tls_context_init(int is_public_server
,
641 crypto_pk_env_t
*client_identity
,
642 crypto_pk_env_t
*server_identity
,
643 unsigned int key_lifetime
)
648 if (is_public_server
) {
649 tor_tls_context_t
*new_ctx
;
650 tor_tls_context_t
*old_ctx
;
652 tor_assert(server_identity
!= NULL
);
654 rv1
= tor_tls_context_init_one(&server_tls_context
,
659 new_ctx
= server_tls_context
;
660 tor_tls_context_incref(new_ctx
);
661 old_ctx
= client_tls_context
;
662 client_tls_context
= new_ctx
;
664 if (old_ctx
!= NULL
) {
665 tor_tls_context_decref(old_ctx
);
669 if (server_identity
!= NULL
) {
670 rv1
= tor_tls_context_init_one(&server_tls_context
,
674 tor_tls_context_t
*old_ctx
= server_tls_context
;
675 server_tls_context
= NULL
;
677 if (old_ctx
!= NULL
) {
678 tor_tls_context_decref(old_ctx
);
682 rv2
= tor_tls_context_init_one(&client_tls_context
,
687 return MIN(rv1
, rv2
);
690 /** Create a new global TLS context.
692 * You can call this function multiple times. Each time you call it,
693 * it generates new certificates; all new connections will use
694 * the new SSL context.
697 tor_tls_context_init_one(tor_tls_context_t
**ppcontext
,
698 crypto_pk_env_t
*identity
,
699 unsigned int key_lifetime
)
701 tor_tls_context_t
*new_ctx
= tor_tls_context_new(identity
,
703 tor_tls_context_t
*old_ctx
= *ppcontext
;
705 if (new_ctx
!= NULL
) {
706 *ppcontext
= new_ctx
;
708 /* Free the old context if one existed. */
709 if (old_ctx
!= NULL
) {
710 /* This is safe even if there are open connections: we reference-
711 * count tor_tls_context_t objects. */
712 tor_tls_context_decref(old_ctx
);
716 return ((new_ctx
!= NULL
) ? 0 : -1);
719 /** Create a new TLS context for use with Tor TLS handshakes.
720 * <b>identity</b> should be set to the identity key used to sign the
723 static tor_tls_context_t
*
724 tor_tls_context_new(crypto_pk_env_t
*identity
, unsigned int key_lifetime
)
726 crypto_pk_env_t
*rsa
= NULL
;
727 EVP_PKEY
*pkey
= NULL
;
728 tor_tls_context_t
*result
= NULL
;
729 X509
*cert
= NULL
, *idcert
= NULL
;
730 char *nickname
= NULL
, *nn2
= NULL
;
733 nickname
= crypto_random_hostname(8, 20, "www.", ".net");
734 nn2
= crypto_random_hostname(8, 20, "www.", ".net");
736 /* Generate short-term RSA key. */
737 if (!(rsa
= crypto_new_pk_env()))
739 if (crypto_pk_generate_key(rsa
)<0)
741 /* Create certificate signed by identity key. */
742 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
744 /* Create self-signed certificate for identity key. */
745 idcert
= tor_tls_create_certificate(identity
, identity
, nn2
, nn2
,
746 IDENTITY_CERT_LIFETIME
);
747 if (!cert
|| !idcert
) {
748 log(LOG_WARN
, LD_CRYPTO
, "Error creating certificate");
752 result
= tor_malloc_zero(sizeof(tor_tls_context_t
));
754 result
->my_cert
= X509_dup(cert
);
755 result
->my_id_cert
= X509_dup(idcert
);
756 result
->key
= crypto_pk_dup_key(rsa
);
758 #ifdef EVERYONE_HAS_AES
759 /* Tell OpenSSL to only use TLS1 */
760 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
763 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
764 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
766 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
768 SSL_CTX_set_options(result
->ctx
, SSL_OP_SINGLE_DH_USE
);
770 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
771 SSL_CTX_set_options(result
->ctx
,
772 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
);
774 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
775 * as authenticating any earlier-received data.
777 if (use_unsafe_renegotiation_op
) {
778 SSL_CTX_set_options(result
->ctx
,
779 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
);
781 /* Don't actually allow compression; it uses ram and time, but the data
782 * we transmit is all encrypted anyway. */
783 if (result
->ctx
->comp_methods
)
784 result
->ctx
->comp_methods
= NULL
;
785 #ifdef SSL_MODE_RELEASE_BUFFERS
786 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_RELEASE_BUFFERS
);
788 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
790 X509_free(cert
); /* We just added a reference to cert. */
793 X509_STORE
*s
= SSL_CTX_get_cert_store(result
->ctx
);
795 X509_STORE_add_cert(s
, idcert
);
796 X509_free(idcert
); /* The context now owns the reference to idcert */
799 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
801 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
803 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
807 if (!SSL_CTX_check_private_key(result
->ctx
))
810 crypto_dh_env_t
*dh
= crypto_dh_new(DH_TYPE_TLS
);
811 SSL_CTX_set_tmp_dh(result
->ctx
, _crypto_dh_env_get_dh(dh
));
814 SSL_CTX_set_verify(result
->ctx
, SSL_VERIFY_PEER
,
815 always_accept_verify_cb
);
816 /* let us realloc bufs that we're writing from */
817 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
820 crypto_free_pk_env(rsa
);
826 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "creating TLS context");
832 crypto_free_pk_env(rsa
);
834 tor_tls_context_decref(result
);
842 #ifdef V2_HANDSHAKE_SERVER
843 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
844 * a list that indicates that the client knows how to do the v2 TLS connection
847 tor_tls_client_is_using_v2_ciphers(const SSL
*ssl
, const char *address
)
850 SSL_SESSION
*session
;
851 /* If we reached this point, we just got a client hello. See if there is
853 if (!(session
= SSL_get_session((SSL
*)ssl
))) {
854 log_info(LD_NET
, "No session on TLS?");
857 if (!session
->ciphers
) {
858 log_info(LD_NET
, "No ciphers on session");
861 /* Now we need to see if there are any ciphers whose presence means we're
862 * dealing with an updated Tor. */
863 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
864 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
865 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
866 if (strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
) &&
867 strcmp(ciphername
, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA
) &&
868 strcmp(ciphername
, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
) &&
869 strcmp(ciphername
, "(NONE)")) {
870 log_debug(LD_NET
, "Got a non-version-1 cipher called '%s'", ciphername
);
878 smartlist_t
*elts
= smartlist_create();
880 for (i
= 0; i
< sk_SSL_CIPHER_num(session
->ciphers
); ++i
) {
881 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(session
->ciphers
, i
);
882 const char *ciphername
= SSL_CIPHER_get_name(cipher
);
883 smartlist_add(elts
, (char*)ciphername
);
885 s
= smartlist_join_strings(elts
, ":", 0, NULL
);
886 log_debug(LD_NET
, "Got a non-version-1 cipher list from %s. It is: '%s'",
889 smartlist_free(elts
);
894 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
895 * changes state. We use this:
896 * <ul><li>To alter the state of the handshake partway through, so we
897 * do not send or request extra certificates in v2 handshakes.</li>
898 * <li>To detect renegotiation</li></ul>
901 tor_tls_server_info_callback(const SSL
*ssl
, int type
, int val
)
905 if (type
!= SSL_CB_ACCEPT_LOOP
)
907 if (ssl
->state
!= SSL3_ST_SW_SRVR_HELLO_A
)
910 tls
= tor_tls_get_by_ssl(ssl
);
912 /* Check whether we're watching for renegotiates. If so, this is one! */
913 if (tls
->negotiated_callback
)
914 tls
->got_renegotiate
= 1;
916 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
919 /* Now check the cipher list. */
920 if (tor_tls_client_is_using_v2_ciphers(ssl
, ADDR(tls
))) {
921 /*XXXX_TLS keep this from happening more than once! */
923 /* Yes, we're casting away the const from ssl. This is very naughty of us.
924 * Let's hope openssl doesn't notice! */
926 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
927 SSL_set_mode((SSL
*) ssl
, SSL_MODE_NO_AUTO_CHAIN
);
928 /* Don't send a hello request. */
929 SSL_set_verify((SSL
*) ssl
, SSL_VERIFY_NONE
, NULL
);
932 tls
->wasV2Handshake
= 1;
934 log_warn(LD_BUG
, "Couldn't look up the tls for an SSL*. How odd!");
940 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
941 * a list designed to mimic a common web browser. Some of the ciphers in the
942 * list won't actually be implemented by OpenSSL: that's okay so long as the
943 * server doesn't select them, and the server won't select anything besides
944 * what's in SERVER_CIPHER_LIST.
946 * [If the server <b>does</b> select a bogus cipher, we won't crash or
947 * anything; we'll just fail later when we try to look up the cipher in
948 * ssl->cipher_list_by_id.]
951 rectify_client_ciphers(STACK_OF(SSL_CIPHER
) **ciphers
)
953 #ifdef V2_HANDSHAKE_CLIENT
954 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK
)) {
955 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
959 /* First, create a dummy SSL_CIPHER for every cipher. */
960 CLIENT_CIPHER_DUMMIES
=
961 tor_malloc_zero(sizeof(SSL_CIPHER
)*N_CLIENT_CIPHERS
);
962 for (i
=0; i
< N_CLIENT_CIPHERS
; ++i
) {
963 CLIENT_CIPHER_DUMMIES
[i
].valid
= 1;
964 CLIENT_CIPHER_DUMMIES
[i
].id
= CLIENT_CIPHER_INFO_LIST
[i
].id
| (3<<24);
965 CLIENT_CIPHER_DUMMIES
[i
].name
= CLIENT_CIPHER_INFO_LIST
[i
].name
;
968 CLIENT_CIPHER_STACK
= sk_SSL_CIPHER_new_null();
969 tor_assert(CLIENT_CIPHER_STACK
);
971 log_debug(LD_NET
, "List was: %s", CLIENT_CIPHER_LIST
);
972 for (j
= 0; j
< sk_SSL_CIPHER_num(*ciphers
); ++j
) {
973 SSL_CIPHER
*cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
974 log_debug(LD_NET
, "Cipher %d: %lx %s", j
, cipher
->id
, cipher
->name
);
977 /* Then copy as many ciphers as we can from the good list, inserting
978 * dummies as needed. */
980 for (i
= 0; i
< N_CLIENT_CIPHERS
; ) {
981 SSL_CIPHER
*cipher
= NULL
;
982 if (j
< sk_SSL_CIPHER_num(*ciphers
))
983 cipher
= sk_SSL_CIPHER_value(*ciphers
, j
);
984 if (cipher
&& ((cipher
->id
>> 24) & 0xff) != 3) {
985 log_debug(LD_NET
, "Skipping v2 cipher %s", cipher
->name
);
988 (cipher
->id
& 0xffff) == CLIENT_CIPHER_INFO_LIST
[i
].id
) {
989 log_debug(LD_NET
, "Found cipher %s", cipher
->name
);
990 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, cipher
);
994 log_debug(LD_NET
, "Inserting fake %s", CLIENT_CIPHER_DUMMIES
[i
].name
);
995 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK
, &CLIENT_CIPHER_DUMMIES
[i
]);
1001 sk_SSL_CIPHER_free(*ciphers
);
1002 *ciphers
= sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK
);
1003 tor_assert(*ciphers
);
1010 /** Create a new TLS object from a file descriptor, and a flag to
1011 * determine whether it is functioning as a server.
1014 tor_tls_new(int sock
, int isServer
)
1017 tor_tls_t
*result
= tor_malloc_zero(sizeof(tor_tls_t
));
1018 tor_tls_context_t
*context
= isServer
? server_tls_context
:
1021 tor_assert(context
); /* make sure somebody made it first */
1022 if (!(result
->ssl
= SSL_new(context
->ctx
))) {
1023 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "creating SSL object");
1028 #ifdef SSL_set_tlsext_host_name
1029 /* Browsers use the TLS hostname extension, so we should too. */
1031 char *fake_hostname
= crypto_random_hostname(4,25, "www.",".com");
1032 SSL_set_tlsext_host_name(result
->ssl
, fake_hostname
);
1033 tor_free(fake_hostname
);
1037 if (!SSL_set_cipher_list(result
->ssl
,
1038 isServer
? SERVER_CIPHER_LIST
: CLIENT_CIPHER_LIST
)) {
1039 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "setting ciphers");
1040 #ifdef SSL_set_tlsext_host_name
1041 SSL_set_tlsext_host_name(result
->ssl
, NULL
);
1043 SSL_free(result
->ssl
);
1048 rectify_client_ciphers(&result
->ssl
->cipher_list
);
1049 result
->socket
= sock
;
1050 bio
= BIO_new_socket(sock
, BIO_NOCLOSE
);
1052 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "opening BIO");
1053 #ifdef SSL_set_tlsext_host_name
1054 SSL_set_tlsext_host_name(result
->ssl
, NULL
);
1056 SSL_free(result
->ssl
);
1060 HT_INSERT(tlsmap
, &tlsmap_root
, result
);
1061 SSL_set_bio(result
->ssl
, bio
, bio
);
1062 tor_tls_context_incref(context
);
1063 result
->context
= context
;
1064 result
->state
= TOR_TLS_ST_HANDSHAKE
;
1065 result
->isServer
= isServer
;
1066 result
->wantwrite_n
= 0;
1067 result
->last_write_count
= BIO_number_written(bio
);
1068 result
->last_read_count
= BIO_number_read(bio
);
1069 if (result
->last_write_count
|| result
->last_read_count
) {
1070 log_warn(LD_NET
, "Newly created BIO has read count %lu, write count %lu",
1071 result
->last_read_count
, result
->last_write_count
);
1073 #ifdef V2_HANDSHAKE_SERVER
1075 SSL_set_info_callback(result
->ssl
, tor_tls_server_info_callback
);
1079 /* Not expected to get called. */
1080 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "creating tor_tls_t object");
1084 /** Make future log messages about <b>tls</b> display the address
1088 tor_tls_set_logged_address(tor_tls_t
*tls
, const char *address
)
1091 tor_free(tls
->address
);
1092 tls
->address
= tor_strdup(address
);
1095 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1096 * next gets a client-side renegotiate in the middle of a read. Do not
1097 * invoke this function until <em>after</em> initial handshaking is done!
1100 tor_tls_set_renegotiate_callback(tor_tls_t
*tls
,
1101 void (*cb
)(tor_tls_t
*, void *arg
),
1104 tls
->negotiated_callback
= cb
;
1105 tls
->callback_arg
= arg
;
1106 tls
->got_renegotiate
= 0;
1107 #ifdef V2_HANDSHAKE_SERVER
1109 SSL_set_info_callback(tls
->ssl
, tor_tls_server_info_callback
);
1111 SSL_set_info_callback(tls
->ssl
, NULL
);
1116 /** If this version of openssl requires it, turn on renegotiation on
1120 tor_tls_unblock_renegotiation(tor_tls_t
*tls
)
1122 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1123 * as authenticating any earlier-received data. */
1124 if (use_unsafe_renegotiation_flag
) {
1125 tls
->ssl
->s3
->flags
|= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
;
1127 if (use_unsafe_renegotiation_op
) {
1128 SSL_set_options(tls
->ssl
,
1129 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
);
1133 /** If this version of openssl supports it, turn off renegotiation on
1134 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1135 * to use belt-and-suspenders here.)
1138 tor_tls_block_renegotiation(tor_tls_t
*tls
)
1140 tls
->ssl
->s3
->flags
&= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
;
1143 /** Return whether this tls initiated the connect (client) or
1144 * received it (server). */
1146 tor_tls_is_server(tor_tls_t
*tls
)
1149 return tls
->isServer
;
1152 /** Release resources associated with a TLS object. Does not close the
1153 * underlying file descriptor.
1156 tor_tls_free(tor_tls_t
*tls
)
1161 tor_assert(tls
->ssl
);
1162 removed
= HT_REMOVE(tlsmap
, &tlsmap_root
, tls
);
1164 log_warn(LD_BUG
, "Freeing a TLS that was not in the ssl->tls map.");
1166 #ifdef SSL_set_tlsext_host_name
1167 SSL_set_tlsext_host_name(tls
->ssl
, NULL
);
1171 tls
->negotiated_callback
= NULL
;
1173 tor_tls_context_decref(tls
->context
);
1174 tor_free(tls
->address
);
1178 /** Underlying function for TLS reading. Reads up to <b>len</b>
1179 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1180 * number of characters read. On failure, returns TOR_TLS_ERROR,
1181 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1184 tor_tls_read(tor_tls_t
*tls
, char *cp
, size_t len
)
1188 tor_assert(tls
->ssl
);
1189 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
1190 tor_assert(len
<INT_MAX
);
1191 r
= SSL_read(tls
->ssl
, cp
, (int)len
);
1193 #ifdef V2_HANDSHAKE_SERVER
1194 if (tls
->got_renegotiate
) {
1195 /* Renegotiation happened! */
1196 log_info(LD_NET
, "Got a TLS renegotiation from %s", ADDR(tls
));
1197 if (tls
->negotiated_callback
)
1198 tls
->negotiated_callback(tls
, tls
->callback_arg
);
1199 tls
->got_renegotiate
= 0;
1204 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_DEBUG
, LD_NET
);
1205 if (err
== _TOR_TLS_ZERORETURN
|| err
== TOR_TLS_CLOSE
) {
1206 log_debug(LD_NET
,"read returned r=%d; TLS is closed",r
);
1207 tls
->state
= TOR_TLS_ST_CLOSED
;
1208 return TOR_TLS_CLOSE
;
1210 tor_assert(err
!= TOR_TLS_DONE
);
1211 log_debug(LD_NET
,"read returned r=%d, err=%d",r
,err
);
1216 /** Underlying function for TLS writing. Write up to <b>n</b>
1217 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1218 * number of characters written. On failure, returns TOR_TLS_ERROR,
1219 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1222 tor_tls_write(tor_tls_t
*tls
, const char *cp
, size_t n
)
1226 tor_assert(tls
->ssl
);
1227 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
1228 tor_assert(n
< INT_MAX
);
1231 if (tls
->wantwrite_n
) {
1232 /* if WANTWRITE last time, we must use the _same_ n as before */
1233 tor_assert(n
>= tls
->wantwrite_n
);
1234 log_debug(LD_NET
,"resuming pending-write, (%d to flush, reusing %d)",
1235 (int)n
, (int)tls
->wantwrite_n
);
1236 n
= tls
->wantwrite_n
;
1237 tls
->wantwrite_n
= 0;
1239 r
= SSL_write(tls
->ssl
, cp
, (int)n
);
1240 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
, LD_NET
);
1241 if (err
== TOR_TLS_DONE
) {
1244 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
1245 tls
->wantwrite_n
= n
;
1250 /** Perform initial handshake on <b>tls</b>. When finished, returns
1251 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1252 * or TOR_TLS_WANTWRITE.
1255 tor_tls_handshake(tor_tls_t
*tls
)
1260 tor_assert(tls
->ssl
);
1261 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
1262 check_no_tls_errors();
1263 oldstate
= tls
->ssl
->state
;
1264 if (tls
->isServer
) {
1265 log_debug(LD_HANDSHAKE
, "About to call SSL_accept on %p (%s)", tls
,
1266 ssl_state_to_string(tls
->ssl
->state
));
1267 r
= SSL_accept(tls
->ssl
);
1269 log_debug(LD_HANDSHAKE
, "About to call SSL_connect on %p (%s)", tls
,
1270 ssl_state_to_string(tls
->ssl
->state
));
1271 r
= SSL_connect(tls
->ssl
);
1273 if (oldstate
!= tls
->ssl
->state
)
1274 log_debug(LD_HANDSHAKE
, "After call, %p was in state %s",
1275 tls
, ssl_state_to_string(tls
->ssl
->state
));
1276 /* We need to call this here and not earlier, since OpenSSL has a penchant
1277 * for clearing its flags when you say accept or connect. */
1278 tor_tls_unblock_renegotiation(tls
);
1279 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
, LD_HANDSHAKE
);
1280 if (ERR_peek_error() != 0) {
1281 tls_log_errors(tls
, tls
->isServer
? LOG_INFO
: LOG_WARN
, LD_HANDSHAKE
,
1283 return TOR_TLS_ERROR_MISC
;
1285 if (r
== TOR_TLS_DONE
) {
1286 tls
->state
= TOR_TLS_ST_OPEN
;
1287 if (tls
->isServer
) {
1288 SSL_set_info_callback(tls
->ssl
, NULL
);
1289 SSL_set_verify(tls
->ssl
, SSL_VERIFY_PEER
, always_accept_verify_cb
);
1290 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1291 tls
->ssl
->mode
&= ~SSL_MODE_NO_AUTO_CHAIN
;
1292 #ifdef V2_HANDSHAKE_SERVER
1293 if (tor_tls_client_is_using_v2_ciphers(tls
->ssl
, ADDR(tls
))) {
1294 /* This check is redundant, but back when we did it in the callback,
1295 * we might have not been able to look up the tor_tls_t if the code
1296 * was buggy. Fixing that. */
1297 if (!tls
->wasV2Handshake
) {
1298 log_warn(LD_BUG
, "For some reason, wasV2Handshake didn't"
1299 " get set. Fixing that.");
1301 tls
->wasV2Handshake
= 1;
1302 log_debug(LD_HANDSHAKE
,
1303 "Completed V2 TLS handshake with client; waiting "
1304 "for renegotiation.");
1306 tls
->wasV2Handshake
= 0;
1310 #ifdef V2_HANDSHAKE_CLIENT
1311 /* If we got no ID cert, we're a v2 handshake. */
1312 X509
*cert
= SSL_get_peer_certificate(tls
->ssl
);
1313 STACK_OF(X509
) *chain
= SSL_get_peer_cert_chain(tls
->ssl
);
1314 int n_certs
= sk_X509_num(chain
);
1315 if (n_certs
> 1 || (n_certs
== 1 && cert
!= sk_X509_value(chain
, 0))) {
1316 log_debug(LD_HANDSHAKE
, "Server sent back multiple certificates; it "
1317 "looks like a v1 handshake on %p", tls
);
1318 tls
->wasV2Handshake
= 0;
1320 log_debug(LD_HANDSHAKE
,
1321 "Server sent back a single certificate; looks like "
1322 "a v2 handshake on %p.", tls
);
1323 tls
->wasV2Handshake
= 1;
1328 if (SSL_set_cipher_list(tls
->ssl
, SERVER_CIPHER_LIST
) == 0) {
1329 tls_log_errors(NULL
, LOG_WARN
, LD_HANDSHAKE
, "re-setting ciphers");
1330 r
= TOR_TLS_ERROR_MISC
;
1337 /** Client only: Renegotiate a TLS session. When finished, returns
1338 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1339 * TOR_TLS_WANTWRITE.
1342 tor_tls_renegotiate(tor_tls_t
*tls
)
1346 /* We could do server-initiated renegotiation too, but that would be tricky.
1347 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1348 tor_assert(!tls
->isServer
);
1349 if (tls
->state
!= TOR_TLS_ST_RENEGOTIATE
) {
1350 int r
= SSL_renegotiate(tls
->ssl
);
1352 return tor_tls_get_error(tls
, r
, 0, "renegotiating", LOG_WARN
,
1355 tls
->state
= TOR_TLS_ST_RENEGOTIATE
;
1357 r
= SSL_do_handshake(tls
->ssl
);
1359 tls
->state
= TOR_TLS_ST_OPEN
;
1360 return TOR_TLS_DONE
;
1362 return tor_tls_get_error(tls
, r
, 0, "renegotiating handshake", LOG_INFO
,
1366 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1367 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1368 * or TOR_TLS_WANTWRITE.
1371 tor_tls_shutdown(tor_tls_t
*tls
)
1376 tor_assert(tls
->ssl
);
1379 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1380 /* If we've already called shutdown once to send a close message,
1381 * we read until the other side has closed too.
1384 r
= SSL_read(tls
->ssl
, buf
, 128);
1386 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
1388 if (err
== _TOR_TLS_ZERORETURN
) {
1389 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
1390 /* fall through... */
1396 r
= SSL_shutdown(tls
->ssl
);
1398 /* If shutdown returns 1, the connection is entirely closed. */
1399 tls
->state
= TOR_TLS_ST_CLOSED
;
1400 return TOR_TLS_DONE
;
1402 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
1404 if (err
== _TOR_TLS_SYSCALL
) {
1405 /* The underlying TCP connection closed while we were shutting down. */
1406 tls
->state
= TOR_TLS_ST_CLOSED
;
1407 return TOR_TLS_DONE
;
1408 } else if (err
== _TOR_TLS_ZERORETURN
) {
1409 /* The TLS connection says that it sent a shutdown record, but
1410 * isn't done shutting down yet. Make sure that this hasn't
1411 * happened before, then go back to the start of the function
1414 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
1415 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
1416 log(LOG_WARN
, LD_NET
,
1417 "TLS returned \"half-closed\" value while already half-closed");
1418 return TOR_TLS_ERROR_MISC
;
1420 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
1421 /* fall through ... */
1428 /** Return true iff this TLS connection is authenticated.
1431 tor_tls_peer_has_cert(tor_tls_t
*tls
)
1434 cert
= SSL_get_peer_certificate(tls
->ssl
);
1435 tls_log_errors(tls
, LOG_WARN
, LD_HANDSHAKE
, "getting peer certificate");
1442 /** Warn that a certificate lifetime extends through a certain range. */
1444 log_cert_lifetime(X509
*cert
, const char *problem
)
1448 char *s1
=NULL
, *s2
=NULL
;
1450 time_t now
= time(NULL
);
1454 log_warn(LD_GENERAL
,
1455 "Certificate %s: is your system clock set incorrectly?",
1458 if (!(bio
= BIO_new(BIO_s_mem()))) {
1459 log_warn(LD_GENERAL
, "Couldn't allocate BIO!"); goto end
;
1461 if (!(ASN1_TIME_print(bio
, X509_get_notBefore(cert
)))) {
1462 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "printing certificate lifetime");
1465 BIO_get_mem_ptr(bio
, &buf
);
1466 s1
= tor_strndup(buf
->data
, buf
->length
);
1468 (void)BIO_reset(bio
);
1469 if (!(ASN1_TIME_print(bio
, X509_get_notAfter(cert
)))) {
1470 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "printing certificate lifetime");
1473 BIO_get_mem_ptr(bio
, &buf
);
1474 s2
= tor_strndup(buf
->data
, buf
->length
);
1476 strftime(mytime
, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now
, &tm
));
1478 log_warn(LD_GENERAL
,
1479 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1483 /* Not expected to get invoked */
1484 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, "getting certificate lifetime");
1491 /** Helper function: try to extract a link certificate and an identity
1492 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1493 * *<b>id_cert_out</b> respectively. Log all messages at level
1496 * Note that a reference is added to cert_out, so it needs to be
1497 * freed. id_cert_out doesn't. */
1499 try_to_extract_certs_from_tls(int severity
, tor_tls_t
*tls
,
1500 X509
**cert_out
, X509
**id_cert_out
)
1502 X509
*cert
= NULL
, *id_cert
= NULL
;
1503 STACK_OF(X509
) *chain
= NULL
;
1504 int num_in_chain
, i
;
1505 *cert_out
= *id_cert_out
= NULL
;
1507 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1510 if (!(chain
= SSL_get_peer_cert_chain(tls
->ssl
)))
1512 num_in_chain
= sk_X509_num(chain
);
1513 /* 1 means we're receiving (server-side), and it's just the id_cert.
1514 * 2 means we're connecting (client-side), and it's both the link
1515 * cert and the id_cert.
1517 if (num_in_chain
< 1) {
1518 log_fn(severity
,LD_PROTOCOL
,
1519 "Unexpected number of certificates in chain (%d)",
1523 for (i
=0; i
<num_in_chain
; ++i
) {
1524 id_cert
= sk_X509_value(chain
, i
);
1525 if (X509_cmp(id_cert
, cert
) != 0)
1528 *id_cert_out
= id_cert
;
1531 /** If the provided tls connection is authenticated and has a
1532 * certificate chain that is currently valid and signed, then set
1533 * *<b>identity_key</b> to the identity certificate's key and return
1534 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1537 tor_tls_verify(int severity
, tor_tls_t
*tls
, crypto_pk_env_t
**identity_key
)
1539 X509
*cert
= NULL
, *id_cert
= NULL
;
1540 EVP_PKEY
*id_pkey
= NULL
;
1544 *identity_key
= NULL
;
1546 try_to_extract_certs_from_tls(severity
, tls
, &cert
, &id_cert
);
1550 log_fn(severity
,LD_PROTOCOL
,"No distinct identity certificate found");
1553 if (!(id_pkey
= X509_get_pubkey(id_cert
)) ||
1554 X509_verify(cert
, id_pkey
) <= 0) {
1555 log_fn(severity
,LD_PROTOCOL
,"X509_verify on cert and pkey returned <= 0");
1556 tls_log_errors(tls
, severity
, LD_HANDSHAKE
, "verifying certificate");
1560 rsa
= EVP_PKEY_get1_RSA(id_pkey
);
1563 *identity_key
= _crypto_new_pk_env_rsa(rsa
);
1571 EVP_PKEY_free(id_pkey
);
1573 /* This should never get invoked, but let's make sure in case OpenSSL
1574 * acts unexpectedly. */
1575 tls_log_errors(tls
, LOG_WARN
, LD_HANDSHAKE
, "finishing tor_tls_verify");
1580 /** Check whether the certificate set on the connection <b>tls</b> is
1581 * expired or not-yet-valid, give or take <b>tolerance</b>
1582 * seconds. Return 0 for valid, -1 for failure.
1584 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1587 tor_tls_check_lifetime(tor_tls_t
*tls
, int tolerance
)
1595 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
1598 t
= now
+ tolerance
;
1599 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
1600 log_cert_lifetime(cert
, "not yet valid");
1603 t
= now
- tolerance
;
1604 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
1605 log_cert_lifetime(cert
, "already expired");
1613 /* Not expected to get invoked */
1614 tls_log_errors(tls
, LOG_WARN
, LD_NET
, "checking certificate lifetime");
1619 /** Return the number of bytes available for reading from <b>tls</b>.
1622 tor_tls_get_pending_bytes(tor_tls_t
*tls
)
1625 return SSL_pending(tls
->ssl
);
1628 /** If <b>tls</b> requires that the next write be of a particular size,
1629 * return that size. Otherwise, return 0. */
1631 tor_tls_get_forced_write_size(tor_tls_t
*tls
)
1633 return tls
->wantwrite_n
;
1636 /** Sets n_read and n_written to the number of bytes read and written,
1637 * respectively, on the raw socket used by <b>tls</b> since the last time this
1638 * function was called on <b>tls</b>. */
1640 tor_tls_get_n_raw_bytes(tor_tls_t
*tls
, size_t *n_read
, size_t *n_written
)
1644 r
= BIO_number_read(SSL_get_rbio(tls
->ssl
));
1645 /* We want the number of bytes actually for real written. Unfortunately,
1646 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1647 * which makes the answer turn out wrong. Let's cope with that. Note
1648 * that this approach will fail if we ever replace tls->ssl's BIOs with
1649 * buffering bios for reasons of our own. As an alternative, we could
1650 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1651 * that would be tempting fate. */
1652 wbio
= SSL_get_wbio(tls
->ssl
);
1653 if (wbio
->method
== BIO_f_buffer() && (tmpbio
= BIO_next(wbio
)) != NULL
)
1655 w
= BIO_number_written(wbio
);
1657 /* We are ok with letting these unsigned ints go "negative" here:
1658 * If we wrapped around, this should still give us the right answer, unless
1659 * we wrapped around by more than ULONG_MAX since the last time we called
1662 *n_read
= (size_t)(r
- tls
->last_read_count
);
1663 *n_written
= (size_t)(w
- tls
->last_write_count
);
1664 if (*n_read
> INT_MAX
|| *n_written
> INT_MAX
) {
1665 log_warn(LD_BUG
, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1666 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1667 r
, tls
->last_read_count
, w
, tls
->last_write_count
);
1669 tls
->last_read_count
= r
;
1670 tls
->last_write_count
= w
;
1673 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1674 * errors, log an error message. */
1676 _check_no_tls_errors(const char *fname
, int line
)
1678 if (ERR_peek_error() == 0)
1680 log(LOG_WARN
, LD_CRYPTO
, "Unhandled OpenSSL errors found at %s:%d: ",
1681 tor_fix_source_file(fname
), line
);
1682 tls_log_errors(NULL
, LOG_WARN
, LD_NET
, NULL
);
1685 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1686 * TLS handshake. Output is undefined if the handshake isn't finished. */
1688 tor_tls_used_v1_handshake(tor_tls_t
*tls
)
1690 if (tls
->isServer
) {
1691 #ifdef V2_HANDSHAKE_SERVER
1692 return ! tls
->wasV2Handshake
;
1695 #ifdef V2_HANDSHAKE_CLIENT
1696 return ! tls
->wasV2Handshake
;
1702 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1703 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1704 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1705 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1706 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1708 tor_tls_get_buffer_sizes(tor_tls_t
*tls
,
1709 size_t *rbuf_capacity
, size_t *rbuf_bytes
,
1710 size_t *wbuf_capacity
, size_t *wbuf_bytes
)
1712 if (tls
->ssl
->s3
->rbuf
.buf
)
1713 *rbuf_capacity
= tls
->ssl
->s3
->rbuf
.len
;
1716 if (tls
->ssl
->s3
->wbuf
.buf
)
1717 *wbuf_capacity
= tls
->ssl
->s3
->wbuf
.len
;
1720 *rbuf_bytes
= tls
->ssl
->s3
->rbuf
.left
;
1721 *wbuf_bytes
= tls
->ssl
->s3
->wbuf
.left
;