Maintain separate server and client TLS contexts.
[tor.git] / src / common / tortls.c
blobc78a9ec9530f7ad74e9772a91f4150b6efcd8851
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 */
6 /**
7 * \file tortls.c
8 * \brief Wrapper functions to present a consistent interface to
9 * TLS, SSL, and X.509 functions from OpenSSL.
10 **/
12 /* (Unlike other tor functions, these
13 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
14 * functions and variables.)
17 #include "orconfig.h"
19 #include <assert.h>
20 #ifdef MS_WINDOWS /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
21 #define WIN32_WINNT 0x400
22 #define _WIN32_WINNT 0x400
23 #define WIN32_LEAN_AND_MEAN
24 #if defined(_MSC_VER) && (_MSC_VER < 1300)
25 #include <winsock.h>
26 #else
27 #include <winsock2.h>
28 #include <ws2tcpip.h>
29 #endif
30 #endif
31 #include <openssl/ssl.h>
32 #include <openssl/ssl3.h>
33 #include <openssl/err.h>
34 #include <openssl/tls1.h>
35 #include <openssl/asn1.h>
36 #include <openssl/bio.h>
37 #include <openssl/opensslv.h>
39 #if OPENSSL_VERSION_NUMBER < 0x00907000l
40 #error "We require OpenSSL >= 0.9.7"
41 #endif
43 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
45 #include "crypto.h"
46 #include "tortls.h"
47 #include "util.h"
48 #include "log.h"
49 #include "container.h"
50 #include "ht.h"
51 #include <string.h>
53 /* Enable the "v2" TLS handshake.
55 #define V2_HANDSHAKE_SERVER
56 #define V2_HANDSHAKE_CLIENT
58 /* Copied from or.h */
59 #define LEGAL_NICKNAME_CHARACTERS \
60 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
62 /** How long do identity certificates live? (sec) */
63 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
65 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
67 /* We redefine these so that we can run correctly even if the vendor gives us
68 * a version of OpenSSL that does not match its header files. (Apple: I am
69 * looking at you.)
71 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
72 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
73 #endif
74 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
75 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
76 #endif
78 /** Does the run-time openssl version look like we need
79 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
80 static int use_unsafe_renegotiation_op = 0;
81 /** Does the run-time openssl version look like we need
82 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
83 static int use_unsafe_renegotiation_flag = 0;
85 /** Structure holding the TLS state for a single connection. */
86 typedef struct tor_tls_context_t {
87 int refcnt;
88 SSL_CTX *ctx;
89 X509 *my_cert;
90 X509 *my_id_cert;
91 crypto_pk_env_t *key;
92 } tor_tls_context_t;
94 /** Holds a SSL object and its associated data. Members are only
95 * accessed from within tortls.c.
97 struct tor_tls_t {
98 HT_ENTRY(tor_tls_t) node;
99 tor_tls_context_t *context; /** A link to the context object for this tls. */
100 SSL *ssl; /**< An OpenSSL SSL object. */
101 int socket; /**< The underlying file descriptor for this TLS connection. */
102 char *address; /**< An address to log when describing this connection. */
103 enum {
104 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
105 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
106 } state : 3; /**< The current SSL state, depending on which operations have
107 * completed successfully. */
108 unsigned int isServer:1; /**< True iff this is a server-side connection */
109 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
110 * this connection used the updated version
111 * of the connection protocol (client sends
112 * different cipher list, server sends only
113 * one certificate). */
114 /** True iff we should call negotiated_callback when we're done reading. */
115 unsigned int got_renegotiate:1;
116 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
117 * time. */
118 /** Last values retrieved from BIO_number_read()/write(); see
119 * tor_tls_get_n_raw_bytes() for usage.
121 unsigned long last_write_count;
122 unsigned long last_read_count;
123 /** If set, a callback to invoke whenever the client tries to renegotiate
124 * the handshake. */
125 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
126 /** Argument to pass to negotiated_callback. */
127 void *callback_arg;
130 #ifdef V2_HANDSHAKE_CLIENT
131 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
132 * in client mode into advertising the ciphers we want. See
133 * rectify_client_ciphers() for details. */
134 static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
135 /** A stack of SSL_CIPHER objects, some real, some fake.
136 * See rectify_client_ciphers() for details. */
137 static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
138 #endif
140 /** Helper: compare tor_tls_t objects by its SSL. */
141 static INLINE int
142 tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
144 return a->ssl == b->ssl;
147 /** Helper: return a hash value for a tor_tls_t by its SSL. */
148 static INLINE unsigned int
149 tor_tls_entry_hash(const tor_tls_t *a)
151 #if SIZEOF_INT == SIZEOF_VOID_P
152 return ((unsigned int)(uintptr_t)a->ssl);
153 #else
154 return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
155 #endif
158 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
160 static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
162 HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
163 tor_tls_entries_eq)
164 HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
165 tor_tls_entries_eq, 0.6, malloc, realloc, free)
167 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
168 * pointer. */
169 static INLINE tor_tls_t *
170 tor_tls_get_by_ssl(const SSL *ssl)
172 tor_tls_t search, *result;
173 memset(&search, 0, sizeof(search));
174 search.ssl = (SSL*)ssl;
175 result = HT_FIND(tlsmap, &tlsmap_root, &search);
176 return result;
179 static void tor_tls_context_decref(tor_tls_context_t *ctx);
180 static void tor_tls_context_incref(tor_tls_context_t *ctx);
181 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
182 crypto_pk_env_t *rsa_sign,
183 const char *cname,
184 const char *cname_sign,
185 unsigned int lifetime);
186 static void tor_tls_unblock_renegotiation(tor_tls_t *tls);
187 static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
188 crypto_pk_env_t *identity,
189 unsigned int key_lifetime);
190 static tor_tls_context_t *tor_tls_context_new(crypto_pk_env_t *identity,
191 unsigned int key_lifetime);
193 /** Global TLS contexts. We keep them here because nobody else needs
194 * to touch them. */
195 static tor_tls_context_t *server_tls_context = NULL;
196 static tor_tls_context_t *client_tls_context = NULL;
197 /** True iff tor_tls_init() has been called. */
198 static int tls_library_is_initialized = 0;
200 /* Module-internal error codes. */
201 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
202 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
204 /** Log all pending tls errors at level <b>severity</b>. Use
205 * <b>doing</b> to describe our current activities.
207 static void
208 tls_log_errors(tor_tls_t *tls, int severity, const char *doing)
210 unsigned long err;
211 const char *msg, *lib, *func, *addr;
212 addr = tls ? tls->address : NULL;
213 while ((err = ERR_get_error()) != 0) {
214 msg = (const char*)ERR_reason_error_string(err);
215 lib = (const char*)ERR_lib_error_string(err);
216 func = (const char*)ERR_func_error_string(err);
217 if (!msg) msg = "(null)";
218 if (!lib) lib = "(null)";
219 if (!func) func = "(null)";
220 if (doing) {
221 log(severity, LD_NET, "TLS error while %s%s%s: %s (in %s:%s)",
222 doing, addr?" with ":"", addr?addr:"",
223 msg, lib, func);
224 } else {
225 log(severity, LD_NET, "TLS error%s%s: %s (in %s:%s)",
226 addr?" with ":"", addr?addr:"",
227 msg, lib, func);
232 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
233 * code. */
234 static int
235 tor_errno_to_tls_error(int e)
237 #if defined(MS_WINDOWS)
238 switch (e) {
239 case WSAECONNRESET: // most common
240 return TOR_TLS_ERROR_CONNRESET;
241 case WSAETIMEDOUT:
242 return TOR_TLS_ERROR_TIMEOUT;
243 case WSAENETUNREACH:
244 case WSAEHOSTUNREACH:
245 return TOR_TLS_ERROR_NO_ROUTE;
246 case WSAECONNREFUSED:
247 return TOR_TLS_ERROR_CONNREFUSED; // least common
248 default:
249 return TOR_TLS_ERROR_MISC;
251 #else
252 switch (e) {
253 case ECONNRESET: // most common
254 return TOR_TLS_ERROR_CONNRESET;
255 case ETIMEDOUT:
256 return TOR_TLS_ERROR_TIMEOUT;
257 case EHOSTUNREACH:
258 case ENETUNREACH:
259 return TOR_TLS_ERROR_NO_ROUTE;
260 case ECONNREFUSED:
261 return TOR_TLS_ERROR_CONNREFUSED; // least common
262 default:
263 return TOR_TLS_ERROR_MISC;
265 #endif
268 /** Given a TOR_TLS_* error code, return a string equivalent. */
269 const char *
270 tor_tls_err_to_string(int err)
272 if (err >= 0)
273 return "[Not an error.]";
274 switch (err) {
275 case TOR_TLS_ERROR_MISC: return "misc error";
276 case TOR_TLS_ERROR_IO: return "unexpected close";
277 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
278 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
279 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
280 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
281 case TOR_TLS_CLOSE: return "closed";
282 case TOR_TLS_WANTREAD: return "want to read";
283 case TOR_TLS_WANTWRITE: return "want to write";
284 default: return "(unknown error code)";
288 #define CATCH_SYSCALL 1
289 #define CATCH_ZERO 2
291 /** Given a TLS object and the result of an SSL_* call, use
292 * SSL_get_error to determine whether an error has occurred, and if so
293 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
294 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
295 * reporting syscall errors. If extra&CATCH_ZERO is true, return
296 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
298 * If an error has occurred, log it at level <b>severity</b> and describe the
299 * current action as <b>doing</b>.
301 static int
302 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
303 const char *doing, int severity)
305 int err = SSL_get_error(tls->ssl, r);
306 int tor_error = TOR_TLS_ERROR_MISC;
307 switch (err) {
308 case SSL_ERROR_NONE:
309 return TOR_TLS_DONE;
310 case SSL_ERROR_WANT_READ:
311 return TOR_TLS_WANTREAD;
312 case SSL_ERROR_WANT_WRITE:
313 return TOR_TLS_WANTWRITE;
314 case SSL_ERROR_SYSCALL:
315 if (extra&CATCH_SYSCALL)
316 return _TOR_TLS_SYSCALL;
317 if (r == 0) {
318 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
319 tor_error = TOR_TLS_ERROR_IO;
320 } else {
321 int e = tor_socket_errno(tls->socket);
322 log(severity, LD_NET,
323 "TLS error: <syscall error while %s> (errno=%d: %s)",
324 doing, e, tor_socket_strerror(e));
325 tor_error = tor_errno_to_tls_error(e);
327 tls_log_errors(tls, severity, doing);
328 return tor_error;
329 case SSL_ERROR_ZERO_RETURN:
330 if (extra&CATCH_ZERO)
331 return _TOR_TLS_ZERORETURN;
332 log(severity, LD_NET, "TLS connection closed while %s", doing);
333 tls_log_errors(tls, severity, doing);
334 return TOR_TLS_CLOSE;
335 default:
336 tls_log_errors(tls, severity, doing);
337 return TOR_TLS_ERROR_MISC;
341 /** Initialize OpenSSL, unless it has already been initialized.
343 static void
344 tor_tls_init(void)
346 if (!tls_library_is_initialized) {
347 long version;
348 SSL_library_init();
349 SSL_load_error_strings();
350 crypto_global_init(-1);
352 version = SSLeay();
354 /* OpenSSL 0.9.8l introdeced SSL3_FLAGS_ALLOW_UNSAGE_LEGACY_RENEGOTIATION
355 * here, but without thinking too hard about it: it turns out that the
356 * flag in question needed to be set at the last minute, and that it
357 * conflicted with an existing flag number that had already been added
358 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
359 * the flag with an option and (it seems) broke anything that used
360 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
361 * and we mustn't use the SSL3_FLAGS option with anything besides
362 * OpenSSL 0.9.8l.
364 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
365 * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
366 * set option 0x00040000L everywhere.
368 * No, we can't simply detect whether the flag or the option is present
369 * in the headers at build-time: some vendors (notably Apple) like to
370 * leave their headers out of sync with their libraries.
372 * Yes, it _is_ almost as if the OpenSSL developers decided that no
373 * program should be allowed to use renegotiation its first passed an
374 * test of intelligence and determination.
376 if (version >= 0x009080c0L && version < 0x009080d0L) {
377 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
378 "I will try SSL3_FLAGS to enable renegotation.",
379 SSLeay_version(SSLEAY_VERSION));
380 use_unsafe_renegotiation_flag = 1;
381 use_unsafe_renegotiation_op = 1;
382 } else if (version >= 0x009080d0L) {
383 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
384 "I will try SSL_OP to enable renegotiation",
385 SSLeay_version(SSLEAY_VERSION));
386 use_unsafe_renegotiation_op = 1;
387 } else if (version < 0x009080c0L) {
388 log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
389 "0.9.8l, but some vendors have backported 0.9.8l's "
390 "renegotiation code to earlier versions, and some have "
391 "backported the code from 0.9.8m or 0.9.8n. I'll set both "
392 "SSL3_FLAGS and SSL_OP just to be safe.",
393 SSLeay_version(SSLEAY_VERSION), version);
394 use_unsafe_renegotiation_flag = 1;
395 use_unsafe_renegotiation_op = 1;
396 } else {
397 log_info(LD_GENERAL, "OpenSSL %s has version %lx",
398 SSLeay_version(SSLEAY_VERSION), version);
401 tls_library_is_initialized = 1;
405 /** Free all global TLS structures. */
406 void
407 tor_tls_free_all(void)
409 if (server_tls_context) {
410 tor_tls_context_t *ctx = server_tls_context;
411 server_tls_context = NULL;
412 tor_tls_context_decref(ctx);
414 if (client_tls_context) {
415 tor_tls_context_t *ctx = client_tls_context;
416 client_tls_context = NULL;
417 tor_tls_context_decref(ctx);
419 if (!HT_EMPTY(&tlsmap_root)) {
420 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
422 HT_CLEAR(tlsmap, &tlsmap_root);
423 #ifdef V2_HANDSHAKE_CLIENT
424 if (CLIENT_CIPHER_DUMMIES)
425 tor_free(CLIENT_CIPHER_DUMMIES);
426 if (CLIENT_CIPHER_STACK)
427 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
428 #endif
431 /** We need to give OpenSSL a callback to verify certificates. This is
432 * it: We always accept peer certs and complete the handshake. We
433 * don't validate them until later.
435 static int
436 always_accept_verify_cb(int preverify_ok,
437 X509_STORE_CTX *x509_ctx)
439 (void) preverify_ok;
440 (void) x509_ctx;
441 return 1;
444 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
445 static X509_NAME *
446 tor_x509_name_new(const char *cname)
448 int nid;
449 X509_NAME *name;
450 if (!(name = X509_NAME_new()))
451 return NULL;
452 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
453 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
454 (unsigned char*)cname, -1, -1, 0)))
455 goto error;
456 return name;
457 error:
458 X509_NAME_free(name);
459 return NULL;
462 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
463 * signed by the private key <b>rsa_sign</b>. The commonName of the
464 * certificate will be <b>cname</b>; the commonName of the issuer will be
465 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
466 * starting from now. Return a certificate on success, NULL on
467 * failure.
469 static X509 *
470 tor_tls_create_certificate(crypto_pk_env_t *rsa,
471 crypto_pk_env_t *rsa_sign,
472 const char *cname,
473 const char *cname_sign,
474 unsigned int cert_lifetime)
476 time_t start_time, end_time;
477 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
478 X509 *x509 = NULL;
479 X509_NAME *name = NULL, *name_issuer=NULL;
481 tor_tls_init();
483 start_time = time(NULL);
485 tor_assert(rsa);
486 tor_assert(cname);
487 tor_assert(rsa_sign);
488 tor_assert(cname_sign);
489 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
490 goto error;
491 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
492 goto error;
493 if (!(x509 = X509_new()))
494 goto error;
495 if (!(X509_set_version(x509, 2)))
496 goto error;
497 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
498 goto error;
500 if (!(name = tor_x509_name_new(cname)))
501 goto error;
502 if (!(X509_set_subject_name(x509, name)))
503 goto error;
504 if (!(name_issuer = tor_x509_name_new(cname_sign)))
505 goto error;
506 if (!(X509_set_issuer_name(x509, name_issuer)))
507 goto error;
509 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
510 goto error;
511 end_time = start_time + cert_lifetime;
512 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
513 goto error;
514 if (!X509_set_pubkey(x509, pkey))
515 goto error;
516 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
517 goto error;
519 goto done;
520 error:
521 if (x509) {
522 X509_free(x509);
523 x509 = NULL;
525 done:
526 tls_log_errors(NULL, LOG_WARN, "generating certificate");
527 if (sign_pkey)
528 EVP_PKEY_free(sign_pkey);
529 if (pkey)
530 EVP_PKEY_free(pkey);
531 if (name)
532 X509_NAME_free(name);
533 if (name_issuer)
534 X509_NAME_free(name_issuer);
535 return x509;
538 /** List of ciphers that servers should select from.*/
539 #define SERVER_CIPHER_LIST \
540 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
541 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
542 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
543 /* Note: for setting up your own private testing network with link crypto
544 * disabled, set the cipher lists to your cipher list to
545 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
546 * with any of the "real" Tors, though. */
548 #ifdef V2_HANDSHAKE_CLIENT
549 #define CIPHER(id, name) name ":"
550 #define XCIPHER(id, name)
551 /** List of ciphers that clients should advertise, omitting items that
552 * our OpenSSL doesn't know about. */
553 static const char CLIENT_CIPHER_LIST[] =
554 #include "./ciphers.inc"
556 #undef CIPHER
557 #undef XCIPHER
559 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
560 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
561 /** A list of all the ciphers that clients should advertise, including items
562 * that OpenSSL might not know about. */
563 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
564 #define CIPHER(id, name) { id, name },
565 #define XCIPHER(id, name) { id, #name },
566 #include "./ciphers.inc"
567 #undef CIPHER
568 #undef XCIPHER
571 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
572 static const int N_CLIENT_CIPHERS =
573 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
574 #endif
576 #ifndef V2_HANDSHAKE_CLIENT
577 #undef CLIENT_CIPHER_LIST
578 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
579 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
580 #endif
582 /** Remove a reference to <b>ctx</b>, and free it if it has no more
583 * references. */
584 static void
585 tor_tls_context_decref(tor_tls_context_t *ctx)
587 tor_assert(ctx);
588 if (--ctx->refcnt == 0) {
589 SSL_CTX_free(ctx->ctx);
590 X509_free(ctx->my_cert);
591 X509_free(ctx->my_id_cert);
592 crypto_free_pk_env(ctx->key);
593 tor_free(ctx);
597 /** Increase the reference count of <b>ctx</b>. */
598 static void
599 tor_tls_context_incref(tor_tls_context_t *ctx)
601 ++ctx->refcnt;
604 /** Create new global client and server TLS contexts.
606 * If <b>server_identity</b> is NULL, this will not generate a server
607 * TLS context. If <b>is_public_server</b> is non-zero, this will use
608 * the same TLS context for incoming and outgoing connections, and
609 * ignore <b>client_identity</b>. */
611 tor_tls_context_init(int is_public_server,
612 crypto_pk_env_t *client_identity,
613 crypto_pk_env_t *server_identity,
614 unsigned int key_lifetime)
616 int rv1 = 0;
617 int rv2 = 0;
619 if (is_public_server) {
620 tor_tls_context_t *new_ctx;
621 tor_tls_context_t *old_ctx;
623 tor_assert(server_identity != NULL);
625 rv1 = tor_tls_context_init_one(&server_tls_context,
626 server_identity,
627 key_lifetime);
629 if (rv1 >= 0) {
630 new_ctx = server_tls_context;
631 tor_tls_context_incref(new_ctx);
632 old_ctx = client_tls_context;
633 client_tls_context = new_ctx;
635 if (old_ctx != NULL) {
636 tor_tls_context_decref(old_ctx);
639 } else {
640 if (server_identity != NULL) {
641 rv1 = tor_tls_context_init_one(&server_tls_context,
642 server_identity,
643 key_lifetime);
644 } else {
645 tor_tls_context_t *old_ctx = server_tls_context;
646 server_tls_context = NULL;
648 if (old_ctx != NULL) {
649 tor_tls_context_decref(old_ctx);
653 rv2 = tor_tls_context_init_one(&client_tls_context,
654 client_identity,
655 key_lifetime);
658 return rv1 < rv2 ? rv1 : rv2;
661 /** Create a new TLS context for use with Tor TLS handshakes.
662 * <b>identity</b> should be set to the identity key used to sign the
663 * certificate.
665 * You can call this function multiple times. Each time you call it,
666 * it generates new certificates; all new connections will use
667 * the new SSL context.
669 static int
670 tor_tls_context_init_one(tor_tls_context_t **ppcontext,
671 crypto_pk_env_t *identity,
672 unsigned int key_lifetime)
674 tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
675 key_lifetime);
676 tor_tls_context_t *old_ctx = *ppcontext;
678 if (new_ctx != NULL) {
679 *ppcontext = new_ctx;
681 /* Free the old context if one existed. */
682 if (old_ctx != NULL) {
683 /* This is safe even if there are open connections: we reference-
684 * count tor_tls_context_t objects. */
685 tor_tls_context_decref(old_ctx);
689 return ((new_ctx != NULL) ? 0 : -1);
692 /** Create a new TLS context for use with Tor TLS handshakes.
693 * <b>identity</b> should be set to the identity key used to sign the
694 * certificate.
696 static tor_tls_context_t *
697 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
699 crypto_pk_env_t *rsa = NULL;
700 EVP_PKEY *pkey = NULL;
701 tor_tls_context_t *result = NULL;
702 X509 *cert = NULL, *idcert = NULL;
703 char *nickname = NULL, *nn2 = NULL;
705 tor_tls_init();
706 nickname = crypto_random_hostname(8, 20, "www.", ".net");
707 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
709 /* Generate short-term RSA key. */
710 if (!(rsa = crypto_new_pk_env()))
711 goto error;
712 if (crypto_pk_generate_key(rsa)<0)
713 goto error;
714 /* Create certificate signed by identity key. */
715 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
716 key_lifetime);
717 /* Create self-signed certificate for identity key. */
718 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
719 IDENTITY_CERT_LIFETIME);
720 if (!cert || !idcert) {
721 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
722 goto error;
725 result = tor_malloc_zero(sizeof(tor_tls_context_t));
726 result->refcnt = 1;
727 result->my_cert = X509_dup(cert);
728 result->my_id_cert = X509_dup(idcert);
729 result->key = crypto_pk_dup_key(rsa);
731 #ifdef EVERYONE_HAS_AES
732 /* Tell OpenSSL to only use TLS1 */
733 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
734 goto error;
735 #else
736 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
737 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
738 goto error;
739 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
740 #endif
741 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
743 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
744 SSL_CTX_set_options(result->ctx,
745 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
746 #endif
747 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
748 * as authenticating any earlier-received data.
750 if (use_unsafe_renegotiation_op) {
751 SSL_CTX_set_options(result->ctx,
752 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
754 /* Don't actually allow compression; it uses ram and time, but the data
755 * we transmit is all encrypted anyway. */
756 if (result->ctx->comp_methods)
757 result->ctx->comp_methods = NULL;
758 #ifdef SSL_MODE_RELEASE_BUFFERS
759 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
760 #endif
761 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
762 goto error;
763 X509_free(cert); /* We just added a reference to cert. */
764 cert=NULL;
765 if (idcert) {
766 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
767 tor_assert(s);
768 X509_STORE_add_cert(s, idcert);
769 X509_free(idcert); /* The context now owns the reference to idcert */
770 idcert = NULL;
772 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
773 tor_assert(rsa);
774 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
775 goto error;
776 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
777 goto error;
778 EVP_PKEY_free(pkey);
779 pkey = NULL;
780 if (!SSL_CTX_check_private_key(result->ctx))
781 goto error;
783 crypto_dh_env_t *dh = crypto_dh_new(DH_TYPE_TLS);
784 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
785 crypto_dh_free(dh);
787 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
788 always_accept_verify_cb);
789 /* let us realloc bufs that we're writing from */
790 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
792 if (rsa)
793 crypto_free_pk_env(rsa);
794 tor_free(nickname);
795 tor_free(nn2);
796 return result;
798 error:
799 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
800 tor_free(nickname);
801 tor_free(nn2);
802 if (pkey)
803 EVP_PKEY_free(pkey);
804 if (rsa)
805 crypto_free_pk_env(rsa);
806 if (result)
807 tor_tls_context_decref(result);
808 if (cert)
809 X509_free(cert);
810 if (idcert)
811 X509_free(idcert);
812 return NULL;
815 #ifdef V2_HANDSHAKE_SERVER
816 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
817 * a list that indicates that the client knows how to do the v2 TLS connection
818 * handshake. */
819 static int
820 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
822 int i;
823 SSL_SESSION *session;
824 /* If we reached this point, we just got a client hello. See if there is
825 * a cipher list. */
826 if (!(session = SSL_get_session((SSL *)ssl))) {
827 log_warn(LD_NET, "No session on TLS?");
828 return 0;
830 if (!session->ciphers) {
831 log_warn(LD_NET, "No ciphers on session");
832 return 0;
834 /* Now we need to see if there are any ciphers whose presence means we're
835 * dealing with an updated Tor. */
836 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
837 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
838 const char *ciphername = SSL_CIPHER_get_name(cipher);
839 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
840 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
841 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
842 strcmp(ciphername, "(NONE)")) {
843 /* XXXX should be ld_debug */
844 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
845 // return 1;
846 goto dump_list;
849 return 0;
850 dump_list:
852 smartlist_t *elts = smartlist_create();
853 char *s;
854 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
855 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
856 const char *ciphername = SSL_CIPHER_get_name(cipher);
857 smartlist_add(elts, (char*)ciphername);
859 s = smartlist_join_strings(elts, ":", 0, NULL);
860 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
861 address, s);
862 tor_free(s);
863 smartlist_free(elts);
865 return 1;
868 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
869 * changes state. We use this:
870 * <ul><li>To alter the state of the handshake partway through, so we
871 * do not send or request extra certificates in v2 handshakes.</li>
872 * <li>To detect renegotiation</li></ul>
874 static void
875 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
877 tor_tls_t *tls;
878 (void) val;
879 if (type != SSL_CB_ACCEPT_LOOP)
880 return;
881 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
882 return;
884 tls = tor_tls_get_by_ssl(ssl);
885 if (tls) {
886 /* Check whether we're watching for renegotiates. If so, this is one! */
887 if (tls->negotiated_callback)
888 tls->got_renegotiate = 1;
889 } else {
890 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
893 /* Now check the cipher list. */
894 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
895 /*XXXX_TLS keep this from happening more than once! */
897 /* Yes, we're casting away the const from ssl. This is very naughty of us.
898 * Let's hope openssl doesn't notice! */
900 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
901 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
902 /* Don't send a hello request. */
903 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
905 if (tls) {
906 tls->wasV2Handshake = 1;
907 } else {
908 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
912 #endif
914 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
915 * a list designed to mimic a common web browser. Some of the ciphers in the
916 * list won't actually be implemented by OpenSSL: that's okay so long as the
917 * server doesn't select them, and the server won't select anything besides
918 * what's in SERVER_CIPHER_LIST.
920 * [If the server <b>does</b> select a bogus cipher, we won't crash or
921 * anything; we'll just fail later when we try to look up the cipher in
922 * ssl->cipher_list_by_id.]
924 static void
925 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
927 #ifdef V2_HANDSHAKE_CLIENT
928 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
929 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
930 * we want.*/
931 int i = 0, j = 0;
933 /* First, create a dummy SSL_CIPHER for every cipher. */
934 CLIENT_CIPHER_DUMMIES =
935 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
936 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
937 CLIENT_CIPHER_DUMMIES[i].valid = 1;
938 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
939 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
942 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
943 tor_assert(CLIENT_CIPHER_STACK);
945 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
946 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
947 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
948 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
951 /* Then copy as many ciphers as we can from the good list, inserting
952 * dummies as needed. */
953 j=0;
954 for (i = 0; i < N_CLIENT_CIPHERS; ) {
955 SSL_CIPHER *cipher = NULL;
956 if (j < sk_SSL_CIPHER_num(*ciphers))
957 cipher = sk_SSL_CIPHER_value(*ciphers, j);
958 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
959 log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
960 ++j;
961 } else if (cipher &&
962 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
963 log_debug(LD_NET, "Found cipher %s", cipher->name);
964 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
965 ++j;
966 ++i;
967 } else {
968 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
969 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
970 ++i;
975 sk_SSL_CIPHER_free(*ciphers);
976 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
977 tor_assert(*ciphers);
979 #else
980 (void)ciphers;
981 #endif
984 /** Create a new TLS object from a file descriptor, and a flag to
985 * determine whether it is functioning as a server.
987 tor_tls_t *
988 tor_tls_new(int sock, int isServer)
990 BIO *bio = NULL;
991 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
992 tor_tls_context_t *context = isServer ? server_tls_context :
993 client_tls_context;
995 tor_assert(context); /* make sure somebody made it first */
996 if (!(result->ssl = SSL_new(context->ctx))) {
997 tls_log_errors(NULL, LOG_WARN, "creating SSL object");
998 tor_free(result);
999 return NULL;
1002 #ifdef SSL_set_tlsext_host_name
1003 /* Browsers use the TLS hostname extension, so we should too. */
1004 if (!isServer) {
1005 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
1006 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
1007 tor_free(fake_hostname);
1009 #endif
1011 if (!SSL_set_cipher_list(result->ssl,
1012 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
1013 tls_log_errors(NULL, LOG_WARN, "setting ciphers");
1014 #ifdef SSL_set_tlsext_host_name
1015 SSL_set_tlsext_host_name(result->ssl, NULL);
1016 #endif
1017 SSL_free(result->ssl);
1018 tor_free(result);
1019 return NULL;
1021 if (!isServer)
1022 rectify_client_ciphers(&result->ssl->cipher_list);
1023 result->socket = sock;
1024 bio = BIO_new_socket(sock, BIO_NOCLOSE);
1025 if (! bio) {
1026 tls_log_errors(NULL, LOG_WARN, "opening BIO");
1027 #ifdef SSL_set_tlsext_host_name
1028 SSL_set_tlsext_host_name(result->ssl, NULL);
1029 #endif
1030 SSL_free(result->ssl);
1031 tor_free(result);
1032 return NULL;
1034 HT_INSERT(tlsmap, &tlsmap_root, result);
1035 SSL_set_bio(result->ssl, bio, bio);
1036 tor_tls_context_incref(context);
1037 result->context = context;
1038 result->state = TOR_TLS_ST_HANDSHAKE;
1039 result->isServer = isServer;
1040 result->wantwrite_n = 0;
1041 result->last_write_count = BIO_number_written(bio);
1042 result->last_read_count = BIO_number_read(bio);
1043 if (result->last_write_count || result->last_read_count) {
1044 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
1045 result->last_read_count, result->last_write_count);
1047 #ifdef V2_HANDSHAKE_SERVER
1048 if (isServer) {
1049 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
1051 #endif
1053 /* Not expected to get called. */
1054 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
1055 return result;
1058 /** Make future log messages about <b>tls</b> display the address
1059 * <b>address</b>.
1061 void
1062 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
1064 tor_assert(tls);
1065 tor_free(tls->address);
1066 tls->address = tor_strdup(address);
1069 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1070 * next gets a client-side renegotiate in the middle of a read. Do not
1071 * invoke this function until <em>after</em> initial handshaking is done!
1073 void
1074 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
1075 void (*cb)(tor_tls_t *, void *arg),
1076 void *arg)
1078 tls->negotiated_callback = cb;
1079 tls->callback_arg = arg;
1080 tls->got_renegotiate = 0;
1081 #ifdef V2_HANDSHAKE_SERVER
1082 if (cb) {
1083 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
1084 } else {
1085 SSL_set_info_callback(tls->ssl, NULL);
1087 #endif
1090 /** If this version of openssl requires it, turn on renegotiation on
1091 * <b>tls</b>.
1093 static void
1094 tor_tls_unblock_renegotiation(tor_tls_t *tls)
1096 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1097 * as authenticating any earlier-received data. */
1098 if (use_unsafe_renegotiation_flag) {
1099 tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1101 if (use_unsafe_renegotiation_op) {
1102 SSL_set_options(tls->ssl,
1103 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1107 /** If this version of openssl supports it, turn off renegotiation on
1108 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1109 * to use belt-and-suspenders here.)
1111 void
1112 tor_tls_block_renegotiation(tor_tls_t *tls)
1114 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1117 /** Return whether this tls initiated the connect (client) or
1118 * received it (server). */
1120 tor_tls_is_server(tor_tls_t *tls)
1122 tor_assert(tls);
1123 return tls->isServer;
1126 /** Release resources associated with a TLS object. Does not close the
1127 * underlying file descriptor.
1129 void
1130 tor_tls_free(tor_tls_t *tls)
1132 tor_tls_t *removed;
1133 tor_assert(tls && tls->ssl);
1134 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
1135 if (!removed) {
1136 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
1138 #ifdef SSL_set_tlsext_host_name
1139 SSL_set_tlsext_host_name(tls->ssl, NULL);
1140 #endif
1141 SSL_free(tls->ssl);
1142 tls->ssl = NULL;
1143 tls->negotiated_callback = NULL;
1144 if (tls->context)
1145 tor_tls_context_decref(tls->context);
1146 tor_free(tls->address);
1147 tor_free(tls);
1150 /** Underlying function for TLS reading. Reads up to <b>len</b>
1151 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1152 * number of characters read. On failure, returns TOR_TLS_ERROR,
1153 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1156 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
1158 int r, err;
1159 tor_assert(tls);
1160 tor_assert(tls->ssl);
1161 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1162 tor_assert(len<INT_MAX);
1163 r = SSL_read(tls->ssl, cp, (int)len);
1164 if (r > 0) {
1165 #ifdef V2_HANDSHAKE_SERVER
1166 if (tls->got_renegotiate) {
1167 /* Renegotiation happened! */
1168 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1169 if (tls->negotiated_callback)
1170 tls->negotiated_callback(tls, tls->callback_arg);
1171 tls->got_renegotiate = 0;
1173 #endif
1174 return r;
1176 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
1177 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
1178 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1179 tls->state = TOR_TLS_ST_CLOSED;
1180 return TOR_TLS_CLOSE;
1181 } else {
1182 tor_assert(err != TOR_TLS_DONE);
1183 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1184 return err;
1188 /** Underlying function for TLS writing. Write up to <b>n</b>
1189 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1190 * number of characters written. On failure, returns TOR_TLS_ERROR,
1191 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1194 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1196 int r, err;
1197 tor_assert(tls);
1198 tor_assert(tls->ssl);
1199 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1200 tor_assert(n < INT_MAX);
1201 if (n == 0)
1202 return 0;
1203 if (tls->wantwrite_n) {
1204 /* if WANTWRITE last time, we must use the _same_ n as before */
1205 tor_assert(n >= tls->wantwrite_n);
1206 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1207 (int)n, (int)tls->wantwrite_n);
1208 n = tls->wantwrite_n;
1209 tls->wantwrite_n = 0;
1211 r = SSL_write(tls->ssl, cp, (int)n);
1212 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
1213 if (err == TOR_TLS_DONE) {
1214 return r;
1216 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1217 tls->wantwrite_n = n;
1219 return err;
1222 /** Perform initial handshake on <b>tls</b>. When finished, returns
1223 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1224 * or TOR_TLS_WANTWRITE.
1227 tor_tls_handshake(tor_tls_t *tls)
1229 int r;
1230 tor_assert(tls);
1231 tor_assert(tls->ssl);
1232 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1233 check_no_tls_errors();
1234 if (tls->isServer) {
1235 r = SSL_accept(tls->ssl);
1236 } else {
1237 r = SSL_connect(tls->ssl);
1239 /* We need to call this here and not earlier, since OpenSSL has a penchant
1240 * for clearing its flags when you say accept or connect. */
1241 tor_tls_unblock_renegotiation(tls);
1242 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
1243 if (ERR_peek_error() != 0) {
1244 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
1245 "handshaking");
1246 return TOR_TLS_ERROR_MISC;
1248 if (r == TOR_TLS_DONE) {
1249 tls->state = TOR_TLS_ST_OPEN;
1250 if (tls->isServer) {
1251 SSL_set_info_callback(tls->ssl, NULL);
1252 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1253 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1254 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
1255 #ifdef V2_HANDSHAKE_SERVER
1256 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
1257 /* This check is redundant, but back when we did it in the callback,
1258 * we might have not been able to look up the tor_tls_t if the code
1259 * was buggy. Fixing that. */
1260 if (!tls->wasV2Handshake) {
1261 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1262 " get set. Fixing that.");
1264 tls->wasV2Handshake = 1;
1265 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
1266 "for renegotiation.");
1267 } else {
1268 tls->wasV2Handshake = 0;
1270 #endif
1271 } else {
1272 #ifdef V2_HANDSHAKE_CLIENT
1273 /* If we got no ID cert, we're a v2 handshake. */
1274 X509 *cert = SSL_get_peer_certificate(tls->ssl);
1275 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
1276 int n_certs = sk_X509_num(chain);
1277 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
1278 tls->wasV2Handshake = 0;
1279 else {
1280 log_debug(LD_NET, "Server sent back a single certificate; looks like "
1281 "a v2 handshake on %p.", tls);
1282 tls->wasV2Handshake = 1;
1284 if (cert)
1285 X509_free(cert);
1286 #endif
1287 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1288 tls_log_errors(NULL, LOG_WARN, "re-setting ciphers");
1289 r = TOR_TLS_ERROR_MISC;
1293 return r;
1296 /** Client only: Renegotiate a TLS session. When finished, returns
1297 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1298 * TOR_TLS_WANTWRITE.
1301 tor_tls_renegotiate(tor_tls_t *tls)
1303 int r;
1304 tor_assert(tls);
1305 /* We could do server-initiated renegotiation too, but that would be tricky.
1306 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1307 tor_assert(!tls->isServer);
1308 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1309 int r = SSL_renegotiate(tls->ssl);
1310 if (r <= 0) {
1311 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1313 tls->state = TOR_TLS_ST_RENEGOTIATE;
1315 r = SSL_do_handshake(tls->ssl);
1316 if (r == 1) {
1317 tls->state = TOR_TLS_ST_OPEN;
1318 return TOR_TLS_DONE;
1319 } else
1320 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1323 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1324 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1325 * or TOR_TLS_WANTWRITE.
1328 tor_tls_shutdown(tor_tls_t *tls)
1330 int r, err;
1331 char buf[128];
1332 tor_assert(tls);
1333 tor_assert(tls->ssl);
1335 while (1) {
1336 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1337 /* If we've already called shutdown once to send a close message,
1338 * we read until the other side has closed too.
1340 do {
1341 r = SSL_read(tls->ssl, buf, 128);
1342 } while (r>0);
1343 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1344 LOG_INFO);
1345 if (err == _TOR_TLS_ZERORETURN) {
1346 tls->state = TOR_TLS_ST_GOTCLOSE;
1347 /* fall through... */
1348 } else {
1349 return err;
1353 r = SSL_shutdown(tls->ssl);
1354 if (r == 1) {
1355 /* If shutdown returns 1, the connection is entirely closed. */
1356 tls->state = TOR_TLS_ST_CLOSED;
1357 return TOR_TLS_DONE;
1359 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1360 LOG_INFO);
1361 if (err == _TOR_TLS_SYSCALL) {
1362 /* The underlying TCP connection closed while we were shutting down. */
1363 tls->state = TOR_TLS_ST_CLOSED;
1364 return TOR_TLS_DONE;
1365 } else if (err == _TOR_TLS_ZERORETURN) {
1366 /* The TLS connection says that it sent a shutdown record, but
1367 * isn't done shutting down yet. Make sure that this hasn't
1368 * happened before, then go back to the start of the function
1369 * and try to read.
1371 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1372 tls->state == TOR_TLS_ST_SENTCLOSE) {
1373 log(LOG_WARN, LD_NET,
1374 "TLS returned \"half-closed\" value while already half-closed");
1375 return TOR_TLS_ERROR_MISC;
1377 tls->state = TOR_TLS_ST_SENTCLOSE;
1378 /* fall through ... */
1379 } else {
1380 return err;
1382 } /* end loop */
1385 /** Return true iff this TLS connection is authenticated.
1388 tor_tls_peer_has_cert(tor_tls_t *tls)
1390 X509 *cert;
1391 cert = SSL_get_peer_certificate(tls->ssl);
1392 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1393 if (!cert)
1394 return 0;
1395 X509_free(cert);
1396 return 1;
1399 /** Warn that a certificate lifetime extends through a certain range. */
1400 static void
1401 log_cert_lifetime(X509 *cert, const char *problem)
1403 BIO *bio = NULL;
1404 BUF_MEM *buf;
1405 char *s1=NULL, *s2=NULL;
1406 char mytime[33];
1407 time_t now = time(NULL);
1408 struct tm tm;
1410 if (problem)
1411 log_warn(LD_GENERAL,
1412 "Certificate %s: is your system clock set incorrectly?",
1413 problem);
1415 if (!(bio = BIO_new(BIO_s_mem()))) {
1416 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1418 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1419 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1420 goto end;
1422 BIO_get_mem_ptr(bio, &buf);
1423 s1 = tor_strndup(buf->data, buf->length);
1425 (void)BIO_reset(bio);
1426 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1427 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1428 goto end;
1430 BIO_get_mem_ptr(bio, &buf);
1431 s2 = tor_strndup(buf->data, buf->length);
1433 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1435 log_warn(LD_GENERAL,
1436 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1437 s1,s2,mytime);
1439 end:
1440 /* Not expected to get invoked */
1441 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1442 if (bio)
1443 BIO_free(bio);
1444 if (s1)
1445 tor_free(s1);
1446 if (s2)
1447 tor_free(s2);
1450 /** Helper function: try to extract a link certificate and an identity
1451 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1452 * *<b>id_cert_out</b> respectively. Log all messages at level
1453 * <b>severity</b>.
1455 * Note that a reference is added to cert_out, so it needs to be
1456 * freed. id_cert_out doesn't. */
1457 static void
1458 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1459 X509 **cert_out, X509 **id_cert_out)
1461 X509 *cert = NULL, *id_cert = NULL;
1462 STACK_OF(X509) *chain = NULL;
1463 int num_in_chain, i;
1464 *cert_out = *id_cert_out = NULL;
1466 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1467 return;
1468 *cert_out = cert;
1469 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1470 return;
1471 num_in_chain = sk_X509_num(chain);
1472 /* 1 means we're receiving (server-side), and it's just the id_cert.
1473 * 2 means we're connecting (client-side), and it's both the link
1474 * cert and the id_cert.
1476 if (num_in_chain < 1) {
1477 log_fn(severity,LD_PROTOCOL,
1478 "Unexpected number of certificates in chain (%d)",
1479 num_in_chain);
1480 return;
1482 for (i=0; i<num_in_chain; ++i) {
1483 id_cert = sk_X509_value(chain, i);
1484 if (X509_cmp(id_cert, cert) != 0)
1485 break;
1487 *id_cert_out = id_cert;
1490 /** If the provided tls connection is authenticated and has a
1491 * certificate chain that is currently valid and signed, then set
1492 * *<b>identity_key</b> to the identity certificate's key and return
1493 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1496 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1498 X509 *cert = NULL, *id_cert = NULL;
1499 EVP_PKEY *id_pkey = NULL;
1500 RSA *rsa;
1501 int r = -1;
1503 *identity_key = NULL;
1505 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1506 if (!cert)
1507 goto done;
1508 if (!id_cert) {
1509 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1510 goto done;
1512 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1513 X509_verify(cert, id_pkey) <= 0) {
1514 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1515 tls_log_errors(tls, severity,"verifying certificate");
1516 goto done;
1519 rsa = EVP_PKEY_get1_RSA(id_pkey);
1520 if (!rsa)
1521 goto done;
1522 *identity_key = _crypto_new_pk_env_rsa(rsa);
1524 r = 0;
1526 done:
1527 if (cert)
1528 X509_free(cert);
1529 if (id_pkey)
1530 EVP_PKEY_free(id_pkey);
1532 /* This should never get invoked, but let's make sure in case OpenSSL
1533 * acts unexpectedly. */
1534 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1536 return r;
1539 /** Check whether the certificate set on the connection <b>tls</b> is
1540 * expired or not-yet-valid, give or take <b>tolerance</b>
1541 * seconds. Return 0 for valid, -1 for failure.
1543 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1546 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1548 time_t now, t;
1549 X509 *cert;
1550 int r = -1;
1552 now = time(NULL);
1554 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1555 goto done;
1557 t = now + tolerance;
1558 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1559 log_cert_lifetime(cert, "not yet valid");
1560 goto done;
1562 t = now - tolerance;
1563 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1564 log_cert_lifetime(cert, "already expired");
1565 goto done;
1568 r = 0;
1569 done:
1570 if (cert)
1571 X509_free(cert);
1572 /* Not expected to get invoked */
1573 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1575 return r;
1578 /** Return the number of bytes available for reading from <b>tls</b>.
1581 tor_tls_get_pending_bytes(tor_tls_t *tls)
1583 tor_assert(tls);
1584 return SSL_pending(tls->ssl);
1587 /** If <b>tls</b> requires that the next write be of a particular size,
1588 * return that size. Otherwise, return 0. */
1589 size_t
1590 tor_tls_get_forced_write_size(tor_tls_t *tls)
1592 return tls->wantwrite_n;
1595 /** Sets n_read and n_written to the number of bytes read and written,
1596 * respectively, on the raw socket used by <b>tls</b> since the last time this
1597 * function was called on <b>tls</b>. */
1598 void
1599 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1601 BIO *wbio, *tmpbio;
1602 unsigned long r, w;
1603 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1604 /* We want the number of bytes actually for real written. Unfortunately,
1605 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1606 * which makes the answer turn out wrong. Let's cope with that. Note
1607 * that this approach will fail if we ever replace tls->ssl's BIOs with
1608 * buffering bios for reasons of our own. As an alternative, we could
1609 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1610 * that would be tempting fate. */
1611 wbio = SSL_get_wbio(tls->ssl);
1612 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1613 wbio = tmpbio;
1614 w = BIO_number_written(wbio);
1616 /* We are ok with letting these unsigned ints go "negative" here:
1617 * If we wrapped around, this should still give us the right answer, unless
1618 * we wrapped around by more than ULONG_MAX since the last time we called
1619 * this function.
1621 *n_read = (size_t)(r - tls->last_read_count);
1622 *n_written = (size_t)(w - tls->last_write_count);
1623 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1624 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1625 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1626 r, tls->last_read_count, w, tls->last_write_count);
1628 tls->last_read_count = r;
1629 tls->last_write_count = w;
1632 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1633 * errors, log an error message. */
1634 void
1635 _check_no_tls_errors(const char *fname, int line)
1637 if (ERR_peek_error() == 0)
1638 return;
1639 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1640 tor_fix_source_file(fname), line);
1641 tls_log_errors(NULL, LOG_WARN, NULL);
1644 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1645 * TLS handshake. Output is undefined if the handshake isn't finished. */
1647 tor_tls_used_v1_handshake(tor_tls_t *tls)
1649 if (tls->isServer) {
1650 #ifdef V2_HANDSHAKE_SERVER
1651 return ! tls->wasV2Handshake;
1652 #endif
1653 } else {
1654 #ifdef V2_HANDSHAKE_CLIENT
1655 return ! tls->wasV2Handshake;
1656 #endif
1658 return 1;
1661 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1662 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1663 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1664 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1665 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1666 void
1667 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1668 size_t *rbuf_capacity, size_t *rbuf_bytes,
1669 size_t *wbuf_capacity, size_t *wbuf_bytes)
1671 if (tls->ssl->s3->rbuf.buf)
1672 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1673 else
1674 *rbuf_capacity = 0;
1675 if (tls->ssl->s3->wbuf.buf)
1676 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1677 else
1678 *wbuf_capacity = 0;
1679 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1680 *wbuf_bytes = tls->ssl->s3->wbuf.left;