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