Make our replacement INT32_MAX always signed
[tor/rransom.git] / src / common / tortls.c
blob1d597e295288503dc9590ff03968e16a599ef86d
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);
188 /** Global tls context. We keep it here because nobody else needs to
189 * touch it. */
190 static tor_tls_context_t *global_tls_context = NULL;
191 /** True iff tor_tls_init() has been called. */
192 static int tls_library_is_initialized = 0;
194 /* Module-internal error codes. */
195 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
196 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
198 /** Log all pending tls errors at level <b>severity</b>. Use
199 * <b>doing</b> to describe our current activities.
201 static void
202 tls_log_errors(tor_tls_t *tls, int severity, const char *doing)
204 unsigned long err;
205 const char *msg, *lib, *func, *addr;
206 addr = tls ? tls->address : NULL;
207 while ((err = ERR_get_error()) != 0) {
208 msg = (const char*)ERR_reason_error_string(err);
209 lib = (const char*)ERR_lib_error_string(err);
210 func = (const char*)ERR_func_error_string(err);
211 if (!msg) msg = "(null)";
212 if (!lib) lib = "(null)";
213 if (!func) func = "(null)";
214 if (doing) {
215 log(severity, LD_NET, "TLS error while %s%s%s: %s (in %s:%s)",
216 doing, addr?" with ":"", addr?addr:"",
217 msg, lib, func);
218 } else {
219 log(severity, LD_NET, "TLS error%s%s: %s (in %s:%s)",
220 addr?" with ":"", addr?addr:"",
221 msg, lib, func);
226 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
227 * code. */
228 static int
229 tor_errno_to_tls_error(int e)
231 #if defined(MS_WINDOWS)
232 switch (e) {
233 case WSAECONNRESET: // most common
234 return TOR_TLS_ERROR_CONNRESET;
235 case WSAETIMEDOUT:
236 return TOR_TLS_ERROR_TIMEOUT;
237 case WSAENETUNREACH:
238 case WSAEHOSTUNREACH:
239 return TOR_TLS_ERROR_NO_ROUTE;
240 case WSAECONNREFUSED:
241 return TOR_TLS_ERROR_CONNREFUSED; // least common
242 default:
243 return TOR_TLS_ERROR_MISC;
245 #else
246 switch (e) {
247 case ECONNRESET: // most common
248 return TOR_TLS_ERROR_CONNRESET;
249 case ETIMEDOUT:
250 return TOR_TLS_ERROR_TIMEOUT;
251 case EHOSTUNREACH:
252 case ENETUNREACH:
253 return TOR_TLS_ERROR_NO_ROUTE;
254 case ECONNREFUSED:
255 return TOR_TLS_ERROR_CONNREFUSED; // least common
256 default:
257 return TOR_TLS_ERROR_MISC;
259 #endif
262 /** Given a TOR_TLS_* error code, return a string equivalent. */
263 const char *
264 tor_tls_err_to_string(int err)
266 if (err >= 0)
267 return "[Not an error.]";
268 switch (err) {
269 case TOR_TLS_ERROR_MISC: return "misc error";
270 case TOR_TLS_ERROR_IO: return "unexpected close";
271 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
272 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
273 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
274 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
275 case TOR_TLS_CLOSE: return "closed";
276 case TOR_TLS_WANTREAD: return "want to read";
277 case TOR_TLS_WANTWRITE: return "want to write";
278 default: return "(unknown error code)";
282 #define CATCH_SYSCALL 1
283 #define CATCH_ZERO 2
285 /** Given a TLS object and the result of an SSL_* call, use
286 * SSL_get_error to determine whether an error has occurred, and if so
287 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
288 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
289 * reporting syscall errors. If extra&CATCH_ZERO is true, return
290 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
292 * If an error has occurred, log it at level <b>severity</b> and describe the
293 * current action as <b>doing</b>.
295 static int
296 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
297 const char *doing, int severity)
299 int err = SSL_get_error(tls->ssl, r);
300 int tor_error = TOR_TLS_ERROR_MISC;
301 switch (err) {
302 case SSL_ERROR_NONE:
303 return TOR_TLS_DONE;
304 case SSL_ERROR_WANT_READ:
305 return TOR_TLS_WANTREAD;
306 case SSL_ERROR_WANT_WRITE:
307 return TOR_TLS_WANTWRITE;
308 case SSL_ERROR_SYSCALL:
309 if (extra&CATCH_SYSCALL)
310 return _TOR_TLS_SYSCALL;
311 if (r == 0) {
312 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
313 tor_error = TOR_TLS_ERROR_IO;
314 } else {
315 int e = tor_socket_errno(tls->socket);
316 log(severity, LD_NET,
317 "TLS error: <syscall error while %s> (errno=%d: %s)",
318 doing, e, tor_socket_strerror(e));
319 tor_error = tor_errno_to_tls_error(e);
321 tls_log_errors(tls, severity, doing);
322 return tor_error;
323 case SSL_ERROR_ZERO_RETURN:
324 if (extra&CATCH_ZERO)
325 return _TOR_TLS_ZERORETURN;
326 log(severity, LD_NET, "TLS connection closed while %s", doing);
327 tls_log_errors(tls, severity, doing);
328 return TOR_TLS_CLOSE;
329 default:
330 tls_log_errors(tls, severity, doing);
331 return TOR_TLS_ERROR_MISC;
335 /** Initialize OpenSSL, unless it has already been initialized.
337 static void
338 tor_tls_init(void)
340 if (!tls_library_is_initialized) {
341 long version;
342 SSL_library_init();
343 SSL_load_error_strings();
344 crypto_global_init(-1);
346 version = SSLeay();
348 /* OpenSSL 0.9.8l introdeced SSL3_FLAGS_ALLOW_UNSAGE_LEGACY_RENEGOTIATION
349 * here, but without thinking too hard about it: it turns out that the
350 * flag in question needed to be set at the last minute, and that it
351 * conflicted with an existing flag number that had already been added
352 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
353 * the flag with an option and (it seems) broke anything that used
354 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
355 * and we mustn't use the SSL3_FLAGS option with anything besides
356 * OpenSSL 0.9.8l.
358 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
359 * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
360 * set option 0x00040000L everywhere.
362 * No, we can't simply detect whether the flag or the option is present
363 * in the headers at build-time: some vendors (notably Apple) like to
364 * leave their headers out of sync with their libraries.
366 * Yes, it _is_ almost as if the OpenSSL developers decided that no
367 * program should be allowed to use renegotiation its first passed an
368 * test of intelligence and determination.
370 if (version >= 0x009080c0L && version < 0x009080d0L) {
371 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
372 "I will try SSL3_FLAGS to enable renegotation.",
373 SSLeay_version(SSLEAY_VERSION));
374 use_unsafe_renegotiation_flag = 1;
375 use_unsafe_renegotiation_op = 1;
376 } else if (version >= 0x009080d0L) {
377 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
378 "I will try SSL_OP to enable renegotiation",
379 SSLeay_version(SSLEAY_VERSION));
380 use_unsafe_renegotiation_op = 1;
381 } else if (version < 0x009080c0L) {
382 log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
383 "0.9.8l, but some vendors have backported 0.9.8l's "
384 "renegotiation code to earlier versions, and some have "
385 "backported the code from 0.9.8m or 0.9.8n. I'll set both "
386 "SSL3_FLAGS and SSL_OP just to be safe.",
387 SSLeay_version(SSLEAY_VERSION), version);
388 use_unsafe_renegotiation_flag = 1;
389 use_unsafe_renegotiation_op = 1;
390 } else {
391 log_info(LD_GENERAL, "OpenSSL %s has version %lx",
392 SSLeay_version(SSLEAY_VERSION), version);
395 tls_library_is_initialized = 1;
399 /** Free all global TLS structures. */
400 void
401 tor_tls_free_all(void)
403 if (global_tls_context) {
404 tor_tls_context_decref(global_tls_context);
405 global_tls_context = NULL;
407 if (!HT_EMPTY(&tlsmap_root)) {
408 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
410 HT_CLEAR(tlsmap, &tlsmap_root);
411 #ifdef V2_HANDSHAKE_CLIENT
412 if (CLIENT_CIPHER_DUMMIES)
413 tor_free(CLIENT_CIPHER_DUMMIES);
414 if (CLIENT_CIPHER_STACK)
415 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
416 #endif
419 /** We need to give OpenSSL a callback to verify certificates. This is
420 * it: We always accept peer certs and complete the handshake. We
421 * don't validate them until later.
423 static int
424 always_accept_verify_cb(int preverify_ok,
425 X509_STORE_CTX *x509_ctx)
427 (void) preverify_ok;
428 (void) x509_ctx;
429 return 1;
432 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
433 static X509_NAME *
434 tor_x509_name_new(const char *cname)
436 int nid;
437 X509_NAME *name;
438 if (!(name = X509_NAME_new()))
439 return NULL;
440 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
441 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
442 (unsigned char*)cname, -1, -1, 0)))
443 goto error;
444 return name;
445 error:
446 X509_NAME_free(name);
447 return NULL;
450 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
451 * signed by the private key <b>rsa_sign</b>. The commonName of the
452 * certificate will be <b>cname</b>; the commonName of the issuer will be
453 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
454 * starting from now. Return a certificate on success, NULL on
455 * failure.
457 static X509 *
458 tor_tls_create_certificate(crypto_pk_env_t *rsa,
459 crypto_pk_env_t *rsa_sign,
460 const char *cname,
461 const char *cname_sign,
462 unsigned int cert_lifetime)
464 time_t start_time, end_time;
465 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
466 X509 *x509 = NULL;
467 X509_NAME *name = NULL, *name_issuer=NULL;
469 tor_tls_init();
471 start_time = time(NULL);
473 tor_assert(rsa);
474 tor_assert(cname);
475 tor_assert(rsa_sign);
476 tor_assert(cname_sign);
477 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
478 goto error;
479 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
480 goto error;
481 if (!(x509 = X509_new()))
482 goto error;
483 if (!(X509_set_version(x509, 2)))
484 goto error;
485 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
486 goto error;
488 if (!(name = tor_x509_name_new(cname)))
489 goto error;
490 if (!(X509_set_subject_name(x509, name)))
491 goto error;
492 if (!(name_issuer = tor_x509_name_new(cname_sign)))
493 goto error;
494 if (!(X509_set_issuer_name(x509, name_issuer)))
495 goto error;
497 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
498 goto error;
499 end_time = start_time + cert_lifetime;
500 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
501 goto error;
502 if (!X509_set_pubkey(x509, pkey))
503 goto error;
504 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
505 goto error;
507 goto done;
508 error:
509 if (x509) {
510 X509_free(x509);
511 x509 = NULL;
513 done:
514 tls_log_errors(NULL, LOG_WARN, "generating certificate");
515 if (sign_pkey)
516 EVP_PKEY_free(sign_pkey);
517 if (pkey)
518 EVP_PKEY_free(pkey);
519 if (name)
520 X509_NAME_free(name);
521 if (name_issuer)
522 X509_NAME_free(name_issuer);
523 return x509;
526 /** List of ciphers that servers should select from.*/
527 #define SERVER_CIPHER_LIST \
528 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
529 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
530 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
531 /* Note: for setting up your own private testing network with link crypto
532 * disabled, set the cipher lists to your cipher list to
533 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
534 * with any of the "real" Tors, though. */
536 #ifdef V2_HANDSHAKE_CLIENT
537 #define CIPHER(id, name) name ":"
538 #define XCIPHER(id, name)
539 /** List of ciphers that clients should advertise, omitting items that
540 * our OpenSSL doesn't know about. */
541 static const char CLIENT_CIPHER_LIST[] =
542 #include "./ciphers.inc"
544 #undef CIPHER
545 #undef XCIPHER
547 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
548 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
549 /** A list of all the ciphers that clients should advertise, including items
550 * that OpenSSL might not know about. */
551 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
552 #define CIPHER(id, name) { id, name },
553 #define XCIPHER(id, name) { id, #name },
554 #include "./ciphers.inc"
555 #undef CIPHER
556 #undef XCIPHER
559 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
560 static const int N_CLIENT_CIPHERS =
561 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
562 #endif
564 #ifndef V2_HANDSHAKE_CLIENT
565 #undef CLIENT_CIPHER_LIST
566 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
567 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
568 #endif
570 /** Remove a reference to <b>ctx</b>, and free it if it has no more
571 * references. */
572 static void
573 tor_tls_context_decref(tor_tls_context_t *ctx)
575 tor_assert(ctx);
576 if (--ctx->refcnt == 0) {
577 SSL_CTX_free(ctx->ctx);
578 X509_free(ctx->my_cert);
579 X509_free(ctx->my_id_cert);
580 crypto_free_pk_env(ctx->key);
581 tor_free(ctx);
585 /** Increase the reference count of <b>ctx</b>. */
586 static void
587 tor_tls_context_incref(tor_tls_context_t *ctx)
589 ++ctx->refcnt;
592 /** Create a new TLS context for use with Tor TLS handshakes.
593 * <b>identity</b> should be set to the identity key used to sign the
594 * certificate, and <b>nickname</b> set to the nickname to use.
596 * You can call this function multiple times. Each time you call it,
597 * it generates new certificates; all new connections will use
598 * the new SSL context.
601 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
603 crypto_pk_env_t *rsa = NULL;
604 EVP_PKEY *pkey = NULL;
605 tor_tls_context_t *result = NULL;
606 X509 *cert = NULL, *idcert = NULL;
607 char *nickname = NULL, *nn2 = NULL;
609 tor_tls_init();
610 nickname = crypto_random_hostname(8, 20, "www.", ".net");
611 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
613 /* Generate short-term RSA key. */
614 if (!(rsa = crypto_new_pk_env()))
615 goto error;
616 if (crypto_pk_generate_key(rsa)<0)
617 goto error;
618 /* Create certificate signed by identity key. */
619 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
620 key_lifetime);
621 /* Create self-signed certificate for identity key. */
622 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
623 IDENTITY_CERT_LIFETIME);
624 if (!cert || !idcert) {
625 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
626 goto error;
629 result = tor_malloc_zero(sizeof(tor_tls_context_t));
630 result->refcnt = 1;
631 result->my_cert = X509_dup(cert);
632 result->my_id_cert = X509_dup(idcert);
633 result->key = crypto_pk_dup_key(rsa);
635 #ifdef EVERYONE_HAS_AES
636 /* Tell OpenSSL to only use TLS1 */
637 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
638 goto error;
639 #else
640 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
641 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
642 goto error;
643 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
644 #endif
645 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
647 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
648 SSL_CTX_set_options(result->ctx,
649 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
650 #endif
651 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
652 * as authenticating any earlier-received data.
654 if (use_unsafe_renegotiation_op) {
655 SSL_CTX_set_options(result->ctx,
656 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
658 /* Don't actually allow compression; it uses ram and time, but the data
659 * we transmit is all encrypted anyway. */
660 if (result->ctx->comp_methods)
661 result->ctx->comp_methods = NULL;
662 #ifdef SSL_MODE_RELEASE_BUFFERS
663 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
664 #endif
665 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
666 goto error;
667 X509_free(cert); /* We just added a reference to cert. */
668 cert=NULL;
669 if (idcert) {
670 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
671 tor_assert(s);
672 X509_STORE_add_cert(s, idcert);
673 X509_free(idcert); /* The context now owns the reference to idcert */
674 idcert = NULL;
676 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
677 tor_assert(rsa);
678 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
679 goto error;
680 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
681 goto error;
682 EVP_PKEY_free(pkey);
683 pkey = NULL;
684 if (!SSL_CTX_check_private_key(result->ctx))
685 goto error;
687 crypto_dh_env_t *dh = crypto_dh_new();
688 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
689 crypto_dh_free(dh);
691 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
692 always_accept_verify_cb);
693 /* let us realloc bufs that we're writing from */
694 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
695 /* Free the old context if one exists. */
696 if (global_tls_context) {
697 /* This is safe even if there are open connections: OpenSSL does
698 * reference counting with SSL and SSL_CTX objects. */
699 tor_tls_context_decref(global_tls_context);
701 global_tls_context = result;
702 if (rsa)
703 crypto_free_pk_env(rsa);
704 tor_free(nickname);
705 tor_free(nn2);
706 return 0;
708 error:
709 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
710 tor_free(nickname);
711 tor_free(nn2);
712 if (pkey)
713 EVP_PKEY_free(pkey);
714 if (rsa)
715 crypto_free_pk_env(rsa);
716 if (result)
717 tor_tls_context_decref(result);
718 if (cert)
719 X509_free(cert);
720 if (idcert)
721 X509_free(idcert);
722 return -1;
725 #ifdef V2_HANDSHAKE_SERVER
726 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
727 * a list that indicates that the client knows how to do the v2 TLS connection
728 * handshake. */
729 static int
730 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
732 int i;
733 SSL_SESSION *session;
734 /* If we reached this point, we just got a client hello. See if there is
735 * a cipher list. */
736 if (!(session = SSL_get_session((SSL *)ssl))) {
737 log_warn(LD_NET, "No session on TLS?");
738 return 0;
740 if (!session->ciphers) {
741 log_warn(LD_NET, "No ciphers on session");
742 return 0;
744 /* Now we need to see if there are any ciphers whose presence means we're
745 * dealing with an updated Tor. */
746 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
747 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
748 const char *ciphername = SSL_CIPHER_get_name(cipher);
749 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
750 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
751 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
752 strcmp(ciphername, "(NONE)")) {
753 /* XXXX should be ld_debug */
754 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
755 // return 1;
756 goto dump_list;
759 return 0;
760 dump_list:
762 smartlist_t *elts = smartlist_create();
763 char *s;
764 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
765 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
766 const char *ciphername = SSL_CIPHER_get_name(cipher);
767 smartlist_add(elts, (char*)ciphername);
769 s = smartlist_join_strings(elts, ":", 0, NULL);
770 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
771 address, s);
772 tor_free(s);
773 smartlist_free(elts);
775 return 1;
778 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
779 * changes state. We use this:
780 * <ul><li>To alter the state of the handshake partway through, so we
781 * do not send or request extra certificates in v2 handshakes.</li>
782 * <li>To detect renegotiation</li></ul>
784 static void
785 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
787 tor_tls_t *tls;
788 (void) val;
789 if (type != SSL_CB_ACCEPT_LOOP)
790 return;
791 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
792 return;
794 tls = tor_tls_get_by_ssl(ssl);
795 if (tls) {
796 /* Check whether we're watching for renegotiates. If so, this is one! */
797 if (tls->negotiated_callback)
798 tls->got_renegotiate = 1;
799 } else {
800 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
803 /* Now check the cipher list. */
804 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
805 /*XXXX_TLS keep this from happening more than once! */
807 /* Yes, we're casting away the const from ssl. This is very naughty of us.
808 * Let's hope openssl doesn't notice! */
810 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
811 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
812 /* Don't send a hello request. */
813 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
815 if (tls) {
816 tls->wasV2Handshake = 1;
817 } else {
818 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
822 #endif
824 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
825 * a list designed to mimic a common web browser. Some of the ciphers in the
826 * list won't actually be implemented by OpenSSL: that's okay so long as the
827 * server doesn't select them, and the server won't select anything besides
828 * what's in SERVER_CIPHER_LIST.
830 * [If the server <b>does</b> select a bogus cipher, we won't crash or
831 * anything; we'll just fail later when we try to look up the cipher in
832 * ssl->cipher_list_by_id.]
834 static void
835 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
837 #ifdef V2_HANDSHAKE_CLIENT
838 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
839 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
840 * we want.*/
841 int i = 0, j = 0;
843 /* First, create a dummy SSL_CIPHER for every cipher. */
844 CLIENT_CIPHER_DUMMIES =
845 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
846 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
847 CLIENT_CIPHER_DUMMIES[i].valid = 1;
848 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
849 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
852 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
853 tor_assert(CLIENT_CIPHER_STACK);
855 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
856 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
857 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
858 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
861 /* Then copy as many ciphers as we can from the good list, inserting
862 * dummies as needed. */
863 j=0;
864 for (i = 0; i < N_CLIENT_CIPHERS; ) {
865 SSL_CIPHER *cipher = NULL;
866 if (j < sk_SSL_CIPHER_num(*ciphers))
867 cipher = sk_SSL_CIPHER_value(*ciphers, j);
868 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
869 log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
870 ++j;
871 } else if (cipher &&
872 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
873 log_debug(LD_NET, "Found cipher %s", cipher->name);
874 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
875 ++j;
876 ++i;
877 } else {
878 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
879 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
880 ++i;
885 sk_SSL_CIPHER_free(*ciphers);
886 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
887 tor_assert(*ciphers);
889 #else
890 (void)ciphers;
891 #endif
894 /** Create a new TLS object from a file descriptor, and a flag to
895 * determine whether it is functioning as a server.
897 tor_tls_t *
898 tor_tls_new(int sock, int isServer)
900 BIO *bio = NULL;
901 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
903 tor_assert(global_tls_context); /* make sure somebody made it first */
904 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
905 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
906 tor_free(result);
907 return NULL;
910 #ifdef SSL_set_tlsext_host_name
911 /* Browsers use the TLS hostname extension, so we should too. */
912 if (!isServer) {
913 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
914 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
915 tor_free(fake_hostname);
917 #endif
919 if (!SSL_set_cipher_list(result->ssl,
920 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
921 tls_log_errors(NULL, LOG_WARN, "setting ciphers");
922 #ifdef SSL_set_tlsext_host_name
923 SSL_set_tlsext_host_name(result->ssl, NULL);
924 #endif
925 SSL_free(result->ssl);
926 tor_free(result);
927 return NULL;
929 if (!isServer)
930 rectify_client_ciphers(&result->ssl->cipher_list);
931 result->socket = sock;
932 bio = BIO_new_socket(sock, BIO_NOCLOSE);
933 if (! bio) {
934 tls_log_errors(NULL, LOG_WARN, "opening BIO");
935 #ifdef SSL_set_tlsext_host_name
936 SSL_set_tlsext_host_name(result->ssl, NULL);
937 #endif
938 SSL_free(result->ssl);
939 tor_free(result);
940 return NULL;
942 HT_INSERT(tlsmap, &tlsmap_root, result);
943 SSL_set_bio(result->ssl, bio, bio);
944 tor_tls_context_incref(global_tls_context);
945 result->context = global_tls_context;
946 result->state = TOR_TLS_ST_HANDSHAKE;
947 result->isServer = isServer;
948 result->wantwrite_n = 0;
949 result->last_write_count = BIO_number_written(bio);
950 result->last_read_count = BIO_number_read(bio);
951 if (result->last_write_count || result->last_read_count) {
952 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
953 result->last_read_count, result->last_write_count);
955 #ifdef V2_HANDSHAKE_SERVER
956 if (isServer) {
957 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
959 #endif
961 /* Not expected to get called. */
962 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
963 return result;
966 /** Make future log messages about <b>tls</b> display the address
967 * <b>address</b>.
969 void
970 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
972 tor_assert(tls);
973 tor_free(tls->address);
974 tls->address = tor_strdup(address);
977 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
978 * next gets a client-side renegotiate in the middle of a read. Do not
979 * invoke this function until <em>after</em> initial handshaking is done!
981 void
982 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
983 void (*cb)(tor_tls_t *, void *arg),
984 void *arg)
986 tls->negotiated_callback = cb;
987 tls->callback_arg = arg;
988 tls->got_renegotiate = 0;
989 #ifdef V2_HANDSHAKE_SERVER
990 if (cb) {
991 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
992 } else {
993 SSL_set_info_callback(tls->ssl, NULL);
995 #endif
998 /** If this version of openssl requires it, turn on renegotiation on
999 * <b>tls</b>.
1001 static void
1002 tor_tls_unblock_renegotiation(tor_tls_t *tls)
1004 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1005 * as authenticating any earlier-received data. */
1006 if (use_unsafe_renegotiation_flag) {
1007 tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1009 if (use_unsafe_renegotiation_op) {
1010 SSL_set_options(tls->ssl,
1011 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1015 /** If this version of openssl supports it, turn off renegotiation on
1016 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1017 * to use belt-and-suspenders here.)
1019 void
1020 tor_tls_block_renegotiation(tor_tls_t *tls)
1022 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1025 /** Return whether this tls initiated the connect (client) or
1026 * received it (server). */
1028 tor_tls_is_server(tor_tls_t *tls)
1030 tor_assert(tls);
1031 return tls->isServer;
1034 /** Release resources associated with a TLS object. Does not close the
1035 * underlying file descriptor.
1037 void
1038 tor_tls_free(tor_tls_t *tls)
1040 tor_tls_t *removed;
1041 tor_assert(tls && tls->ssl);
1042 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
1043 if (!removed) {
1044 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
1046 #ifdef SSL_set_tlsext_host_name
1047 SSL_set_tlsext_host_name(tls->ssl, NULL);
1048 #endif
1049 SSL_free(tls->ssl);
1050 tls->ssl = NULL;
1051 tls->negotiated_callback = NULL;
1052 if (tls->context)
1053 tor_tls_context_decref(tls->context);
1054 tor_free(tls->address);
1055 tor_free(tls);
1058 /** Underlying function for TLS reading. Reads up to <b>len</b>
1059 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1060 * number of characters read. On failure, returns TOR_TLS_ERROR,
1061 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1064 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
1066 int r, err;
1067 tor_assert(tls);
1068 tor_assert(tls->ssl);
1069 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1070 tor_assert(len<INT_MAX);
1071 r = SSL_read(tls->ssl, cp, (int)len);
1072 if (r > 0) {
1073 #ifdef V2_HANDSHAKE_SERVER
1074 if (tls->got_renegotiate) {
1075 /* Renegotiation happened! */
1076 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1077 if (tls->negotiated_callback)
1078 tls->negotiated_callback(tls, tls->callback_arg);
1079 tls->got_renegotiate = 0;
1081 #endif
1082 return r;
1084 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
1085 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
1086 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1087 tls->state = TOR_TLS_ST_CLOSED;
1088 return TOR_TLS_CLOSE;
1089 } else {
1090 tor_assert(err != TOR_TLS_DONE);
1091 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1092 return err;
1096 /** Underlying function for TLS writing. Write up to <b>n</b>
1097 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1098 * number of characters written. On failure, returns TOR_TLS_ERROR,
1099 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1102 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1104 int r, err;
1105 tor_assert(tls);
1106 tor_assert(tls->ssl);
1107 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1108 tor_assert(n < INT_MAX);
1109 if (n == 0)
1110 return 0;
1111 if (tls->wantwrite_n) {
1112 /* if WANTWRITE last time, we must use the _same_ n as before */
1113 tor_assert(n >= tls->wantwrite_n);
1114 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1115 (int)n, (int)tls->wantwrite_n);
1116 n = tls->wantwrite_n;
1117 tls->wantwrite_n = 0;
1119 r = SSL_write(tls->ssl, cp, (int)n);
1120 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
1121 if (err == TOR_TLS_DONE) {
1122 return r;
1124 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1125 tls->wantwrite_n = n;
1127 return err;
1130 /** Perform initial handshake on <b>tls</b>. When finished, returns
1131 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1132 * or TOR_TLS_WANTWRITE.
1135 tor_tls_handshake(tor_tls_t *tls)
1137 int r;
1138 tor_assert(tls);
1139 tor_assert(tls->ssl);
1140 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1141 check_no_tls_errors();
1142 if (tls->isServer) {
1143 r = SSL_accept(tls->ssl);
1144 } else {
1145 r = SSL_connect(tls->ssl);
1147 /* We need to call this here and not earlier, since OpenSSL has a penchant
1148 * for clearing its flags when you say accept or connect. */
1149 tor_tls_unblock_renegotiation(tls);
1150 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
1151 if (ERR_peek_error() != 0) {
1152 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
1153 "handshaking");
1154 return TOR_TLS_ERROR_MISC;
1156 if (r == TOR_TLS_DONE) {
1157 tls->state = TOR_TLS_ST_OPEN;
1158 if (tls->isServer) {
1159 SSL_set_info_callback(tls->ssl, NULL);
1160 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1161 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1162 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
1163 #ifdef V2_HANDSHAKE_SERVER
1164 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
1165 /* This check is redundant, but back when we did it in the callback,
1166 * we might have not been able to look up the tor_tls_t if the code
1167 * was buggy. Fixing that. */
1168 if (!tls->wasV2Handshake) {
1169 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1170 " get set. Fixing that.");
1172 tls->wasV2Handshake = 1;
1173 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
1174 "for renegotiation.");
1175 } else {
1176 tls->wasV2Handshake = 0;
1178 #endif
1179 } else {
1180 #ifdef V2_HANDSHAKE_CLIENT
1181 /* If we got no ID cert, we're a v2 handshake. */
1182 X509 *cert = SSL_get_peer_certificate(tls->ssl);
1183 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
1184 int n_certs = sk_X509_num(chain);
1185 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
1186 tls->wasV2Handshake = 0;
1187 else {
1188 log_debug(LD_NET, "Server sent back a single certificate; looks like "
1189 "a v2 handshake on %p.", tls);
1190 tls->wasV2Handshake = 1;
1192 if (cert)
1193 X509_free(cert);
1194 #endif
1195 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1196 tls_log_errors(NULL, LOG_WARN, "re-setting ciphers");
1197 r = TOR_TLS_ERROR_MISC;
1201 return r;
1204 /** Client only: Renegotiate a TLS session. When finished, returns
1205 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1206 * TOR_TLS_WANTWRITE.
1209 tor_tls_renegotiate(tor_tls_t *tls)
1211 int r;
1212 tor_assert(tls);
1213 /* We could do server-initiated renegotiation too, but that would be tricky.
1214 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1215 tor_assert(!tls->isServer);
1216 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1217 int r = SSL_renegotiate(tls->ssl);
1218 if (r <= 0) {
1219 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1221 tls->state = TOR_TLS_ST_RENEGOTIATE;
1223 r = SSL_do_handshake(tls->ssl);
1224 if (r == 1) {
1225 tls->state = TOR_TLS_ST_OPEN;
1226 return TOR_TLS_DONE;
1227 } else
1228 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1231 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1232 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1233 * or TOR_TLS_WANTWRITE.
1236 tor_tls_shutdown(tor_tls_t *tls)
1238 int r, err;
1239 char buf[128];
1240 tor_assert(tls);
1241 tor_assert(tls->ssl);
1243 while (1) {
1244 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1245 /* If we've already called shutdown once to send a close message,
1246 * we read until the other side has closed too.
1248 do {
1249 r = SSL_read(tls->ssl, buf, 128);
1250 } while (r>0);
1251 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1252 LOG_INFO);
1253 if (err == _TOR_TLS_ZERORETURN) {
1254 tls->state = TOR_TLS_ST_GOTCLOSE;
1255 /* fall through... */
1256 } else {
1257 return err;
1261 r = SSL_shutdown(tls->ssl);
1262 if (r == 1) {
1263 /* If shutdown returns 1, the connection is entirely closed. */
1264 tls->state = TOR_TLS_ST_CLOSED;
1265 return TOR_TLS_DONE;
1267 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1268 LOG_INFO);
1269 if (err == _TOR_TLS_SYSCALL) {
1270 /* The underlying TCP connection closed while we were shutting down. */
1271 tls->state = TOR_TLS_ST_CLOSED;
1272 return TOR_TLS_DONE;
1273 } else if (err == _TOR_TLS_ZERORETURN) {
1274 /* The TLS connection says that it sent a shutdown record, but
1275 * isn't done shutting down yet. Make sure that this hasn't
1276 * happened before, then go back to the start of the function
1277 * and try to read.
1279 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1280 tls->state == TOR_TLS_ST_SENTCLOSE) {
1281 log(LOG_WARN, LD_NET,
1282 "TLS returned \"half-closed\" value while already half-closed");
1283 return TOR_TLS_ERROR_MISC;
1285 tls->state = TOR_TLS_ST_SENTCLOSE;
1286 /* fall through ... */
1287 } else {
1288 return err;
1290 } /* end loop */
1293 /** Return true iff this TLS connection is authenticated.
1296 tor_tls_peer_has_cert(tor_tls_t *tls)
1298 X509 *cert;
1299 cert = SSL_get_peer_certificate(tls->ssl);
1300 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1301 if (!cert)
1302 return 0;
1303 X509_free(cert);
1304 return 1;
1307 /** Warn that a certificate lifetime extends through a certain range. */
1308 static void
1309 log_cert_lifetime(X509 *cert, const char *problem)
1311 BIO *bio = NULL;
1312 BUF_MEM *buf;
1313 char *s1=NULL, *s2=NULL;
1314 char mytime[33];
1315 time_t now = time(NULL);
1316 struct tm tm;
1318 if (problem)
1319 log_warn(LD_GENERAL,
1320 "Certificate %s: is your system clock set incorrectly?",
1321 problem);
1323 if (!(bio = BIO_new(BIO_s_mem()))) {
1324 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1326 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1327 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1328 goto end;
1330 BIO_get_mem_ptr(bio, &buf);
1331 s1 = tor_strndup(buf->data, buf->length);
1333 (void)BIO_reset(bio);
1334 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1335 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1336 goto end;
1338 BIO_get_mem_ptr(bio, &buf);
1339 s2 = tor_strndup(buf->data, buf->length);
1341 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1343 log_warn(LD_GENERAL,
1344 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1345 s1,s2,mytime);
1347 end:
1348 /* Not expected to get invoked */
1349 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1350 if (bio)
1351 BIO_free(bio);
1352 if (s1)
1353 tor_free(s1);
1354 if (s2)
1355 tor_free(s2);
1358 /** Helper function: try to extract a link certificate and an identity
1359 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1360 * *<b>id_cert_out</b> respectively. Log all messages at level
1361 * <b>severity</b>.
1363 * Note that a reference is added to cert_out, so it needs to be
1364 * freed. id_cert_out doesn't. */
1365 static void
1366 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1367 X509 **cert_out, X509 **id_cert_out)
1369 X509 *cert = NULL, *id_cert = NULL;
1370 STACK_OF(X509) *chain = NULL;
1371 int num_in_chain, i;
1372 *cert_out = *id_cert_out = NULL;
1374 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1375 return;
1376 *cert_out = cert;
1377 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1378 return;
1379 num_in_chain = sk_X509_num(chain);
1380 /* 1 means we're receiving (server-side), and it's just the id_cert.
1381 * 2 means we're connecting (client-side), and it's both the link
1382 * cert and the id_cert.
1384 if (num_in_chain < 1) {
1385 log_fn(severity,LD_PROTOCOL,
1386 "Unexpected number of certificates in chain (%d)",
1387 num_in_chain);
1388 return;
1390 for (i=0; i<num_in_chain; ++i) {
1391 id_cert = sk_X509_value(chain, i);
1392 if (X509_cmp(id_cert, cert) != 0)
1393 break;
1395 *id_cert_out = id_cert;
1398 /** If the provided tls connection is authenticated and has a
1399 * certificate chain that is currently valid and signed, then set
1400 * *<b>identity_key</b> to the identity certificate's key and return
1401 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1404 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1406 X509 *cert = NULL, *id_cert = NULL;
1407 EVP_PKEY *id_pkey = NULL;
1408 RSA *rsa;
1409 int r = -1;
1411 *identity_key = NULL;
1413 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1414 if (!cert)
1415 goto done;
1416 if (!id_cert) {
1417 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1418 goto done;
1420 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1421 X509_verify(cert, id_pkey) <= 0) {
1422 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1423 tls_log_errors(tls, severity,"verifying certificate");
1424 goto done;
1427 rsa = EVP_PKEY_get1_RSA(id_pkey);
1428 if (!rsa)
1429 goto done;
1430 *identity_key = _crypto_new_pk_env_rsa(rsa);
1432 r = 0;
1434 done:
1435 if (cert)
1436 X509_free(cert);
1437 if (id_pkey)
1438 EVP_PKEY_free(id_pkey);
1440 /* This should never get invoked, but let's make sure in case OpenSSL
1441 * acts unexpectedly. */
1442 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1444 return r;
1447 /** Check whether the certificate set on the connection <b>tls</b> is
1448 * expired or not-yet-valid, give or take <b>tolerance</b>
1449 * seconds. Return 0 for valid, -1 for failure.
1451 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1454 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1456 time_t now, t;
1457 X509 *cert;
1458 int r = -1;
1460 now = time(NULL);
1462 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1463 goto done;
1465 t = now + tolerance;
1466 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1467 log_cert_lifetime(cert, "not yet valid");
1468 goto done;
1470 t = now - tolerance;
1471 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1472 log_cert_lifetime(cert, "already expired");
1473 goto done;
1476 r = 0;
1477 done:
1478 if (cert)
1479 X509_free(cert);
1480 /* Not expected to get invoked */
1481 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1483 return r;
1486 /** Return the number of bytes available for reading from <b>tls</b>.
1489 tor_tls_get_pending_bytes(tor_tls_t *tls)
1491 tor_assert(tls);
1492 return SSL_pending(tls->ssl);
1495 /** If <b>tls</b> requires that the next write be of a particular size,
1496 * return that size. Otherwise, return 0. */
1497 size_t
1498 tor_tls_get_forced_write_size(tor_tls_t *tls)
1500 return tls->wantwrite_n;
1503 /** Sets n_read and n_written to the number of bytes read and written,
1504 * respectively, on the raw socket used by <b>tls</b> since the last time this
1505 * function was called on <b>tls</b>. */
1506 void
1507 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1509 BIO *wbio, *tmpbio;
1510 unsigned long r, w;
1511 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1512 /* We want the number of bytes actually for real written. Unfortunately,
1513 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1514 * which makes the answer turn out wrong. Let's cope with that. Note
1515 * that this approach will fail if we ever replace tls->ssl's BIOs with
1516 * buffering bios for reasons of our own. As an alternative, we could
1517 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1518 * that would be tempting fate. */
1519 wbio = SSL_get_wbio(tls->ssl);
1520 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1521 wbio = tmpbio;
1522 w = BIO_number_written(wbio);
1524 /* We are ok with letting these unsigned ints go "negative" here:
1525 * If we wrapped around, this should still give us the right answer, unless
1526 * we wrapped around by more than ULONG_MAX since the last time we called
1527 * this function.
1529 *n_read = (size_t)(r - tls->last_read_count);
1530 *n_written = (size_t)(w - tls->last_write_count);
1531 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1532 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1533 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1534 r, tls->last_read_count, w, tls->last_write_count);
1536 tls->last_read_count = r;
1537 tls->last_write_count = w;
1540 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1541 * errors, log an error message. */
1542 void
1543 _check_no_tls_errors(const char *fname, int line)
1545 if (ERR_peek_error() == 0)
1546 return;
1547 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1548 tor_fix_source_file(fname), line);
1549 tls_log_errors(NULL, LOG_WARN, NULL);
1552 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1553 * TLS handshake. Output is undefined if the handshake isn't finished. */
1555 tor_tls_used_v1_handshake(tor_tls_t *tls)
1557 if (tls->isServer) {
1558 #ifdef V2_HANDSHAKE_SERVER
1559 return ! tls->wasV2Handshake;
1560 #endif
1561 } else {
1562 #ifdef V2_HANDSHAKE_CLIENT
1563 return ! tls->wasV2Handshake;
1564 #endif
1566 return 1;
1569 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1570 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1571 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1572 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1573 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1574 void
1575 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1576 size_t *rbuf_capacity, size_t *rbuf_bytes,
1577 size_t *wbuf_capacity, size_t *wbuf_bytes)
1579 if (tls->ssl->s3->rbuf.buf)
1580 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1581 else
1582 *rbuf_capacity = 0;
1583 if (tls->ssl->s3->wbuf.buf)
1584 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1585 else
1586 *wbuf_capacity = 0;
1587 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1588 *wbuf_bytes = tls->ssl->s3->wbuf.left;