Use -Wno-system-headers on openbsd to resolve 2nd case of bug1848
[tor/rransom.git] / src / common / tortls.c
blob25f21a98920bc6c6844f161762eeb2692409d4b2
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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 #include <openssl/ssl.h>
21 #include <openssl/ssl3.h>
22 #include <openssl/err.h>
23 #include <openssl/tls1.h>
24 #include <openssl/asn1.h>
25 #include <openssl/bio.h>
26 #include <openssl/opensslv.h>
28 #if OPENSSL_VERSION_NUMBER < 0x00907000l
29 #error "We require OpenSSL >= 0.9.7"
30 #endif
32 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
34 #include "crypto.h"
35 #include "tortls.h"
36 #include "util.h"
37 #include "log.h"
38 #include "container.h"
39 #include "ht.h"
40 #include <string.h>
42 /* Enable the "v2" TLS handshake.
44 #define V2_HANDSHAKE_SERVER
45 #define V2_HANDSHAKE_CLIENT
47 /* Copied from or.h */
48 #define LEGAL_NICKNAME_CHARACTERS \
49 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
51 /** How long do identity certificates live? (sec) */
52 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
54 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
56 /* We redefine these so that we can run correctly even if the vendor gives us
57 * a version of OpenSSL that does not match its header files. (Apple: I am
58 * looking at you.)
60 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
61 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
62 #endif
63 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
64 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
65 #endif
67 /** Does the run-time openssl version look like we need
68 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
69 static int use_unsafe_renegotiation_op = 0;
70 /** Does the run-time openssl version look like we need
71 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
72 static int use_unsafe_renegotiation_flag = 0;
74 /** Structure holding the TLS state for a single connection. */
75 typedef struct tor_tls_context_t {
76 int refcnt;
77 SSL_CTX *ctx;
78 X509 *my_cert;
79 X509 *my_id_cert;
80 crypto_pk_env_t *key;
81 } tor_tls_context_t;
83 /** Holds a SSL object and its associated data. Members are only
84 * accessed from within tortls.c.
86 struct tor_tls_t {
87 HT_ENTRY(tor_tls_t) node;
88 tor_tls_context_t *context; /** A link to the context object for this tls. */
89 SSL *ssl; /**< An OpenSSL SSL object. */
90 int socket; /**< The underlying file descriptor for this TLS connection. */
91 char *address; /**< An address to log when describing this connection. */
92 enum {
93 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
94 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
95 } state : 3; /**< The current SSL state, depending on which operations have
96 * completed successfully. */
97 unsigned int isServer:1; /**< True iff this is a server-side connection */
98 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
99 * this connection used the updated version
100 * of the connection protocol (client sends
101 * different cipher list, server sends only
102 * one certificate). */
103 /** True iff we should call negotiated_callback when we're done reading. */
104 unsigned int got_renegotiate:1;
105 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
106 * time. */
107 /** Last values retrieved from BIO_number_read()/write(); see
108 * tor_tls_get_n_raw_bytes() for usage.
110 unsigned long last_write_count;
111 unsigned long last_read_count;
112 /** If set, a callback to invoke whenever the client tries to renegotiate
113 * the handshake. */
114 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
115 /** Argument to pass to negotiated_callback. */
116 void *callback_arg;
119 #ifdef V2_HANDSHAKE_CLIENT
120 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
121 * in client mode into advertising the ciphers we want. See
122 * rectify_client_ciphers() for details. */
123 static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
124 /** A stack of SSL_CIPHER objects, some real, some fake.
125 * See rectify_client_ciphers() for details. */
126 static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
127 #endif
129 /** Helper: compare tor_tls_t objects by its SSL. */
130 static INLINE int
131 tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
133 return a->ssl == b->ssl;
136 /** Helper: return a hash value for a tor_tls_t by its SSL. */
137 static INLINE unsigned int
138 tor_tls_entry_hash(const tor_tls_t *a)
140 #if SIZEOF_INT == SIZEOF_VOID_P
141 return ((unsigned int)(uintptr_t)a->ssl);
142 #else
143 return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
144 #endif
147 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
149 static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
151 HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
152 tor_tls_entries_eq)
153 HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
154 tor_tls_entries_eq, 0.6, malloc, realloc, free)
156 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
157 * pointer. */
158 static INLINE tor_tls_t *
159 tor_tls_get_by_ssl(const SSL *ssl)
161 tor_tls_t search, *result;
162 memset(&search, 0, sizeof(search));
163 search.ssl = (SSL*)ssl;
164 result = HT_FIND(tlsmap, &tlsmap_root, &search);
165 return result;
168 static void tor_tls_context_decref(tor_tls_context_t *ctx);
169 static void tor_tls_context_incref(tor_tls_context_t *ctx);
170 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
171 crypto_pk_env_t *rsa_sign,
172 const char *cname,
173 const char *cname_sign,
174 unsigned int lifetime);
175 static void tor_tls_unblock_renegotiation(tor_tls_t *tls);
177 /** Global tls context. We keep it here because nobody else needs to
178 * touch it. */
179 static tor_tls_context_t *global_tls_context = NULL;
180 /** True iff tor_tls_init() has been called. */
181 static int tls_library_is_initialized = 0;
183 /* Module-internal error codes. */
184 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
185 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
187 /** Log all pending tls errors at level <b>severity</b>. Use
188 * <b>doing</b> to describe our current activities.
190 static void
191 tls_log_errors(tor_tls_t *tls, int severity, const char *doing)
193 unsigned long err;
194 const char *msg, *lib, *func, *addr;
195 addr = tls ? tls->address : NULL;
196 while ((err = ERR_get_error()) != 0) {
197 msg = (const char*)ERR_reason_error_string(err);
198 lib = (const char*)ERR_lib_error_string(err);
199 func = (const char*)ERR_func_error_string(err);
200 if (!msg) msg = "(null)";
201 if (!lib) lib = "(null)";
202 if (!func) func = "(null)";
203 if (doing) {
204 log(severity, LD_NET, "TLS error while %s%s%s: %s (in %s:%s)",
205 doing, addr?" with ":"", addr?addr:"",
206 msg, lib, func);
207 } else {
208 log(severity, LD_NET, "TLS error%s%s: %s (in %s:%s)",
209 addr?" with ":"", addr?addr:"",
210 msg, lib, func);
215 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
216 * code. */
217 static int
218 tor_errno_to_tls_error(int e)
220 #if defined(MS_WINDOWS)
221 switch (e) {
222 case WSAECONNRESET: // most common
223 return TOR_TLS_ERROR_CONNRESET;
224 case WSAETIMEDOUT:
225 return TOR_TLS_ERROR_TIMEOUT;
226 case WSAENETUNREACH:
227 case WSAEHOSTUNREACH:
228 return TOR_TLS_ERROR_NO_ROUTE;
229 case WSAECONNREFUSED:
230 return TOR_TLS_ERROR_CONNREFUSED; // least common
231 default:
232 return TOR_TLS_ERROR_MISC;
234 #else
235 switch (e) {
236 case ECONNRESET: // most common
237 return TOR_TLS_ERROR_CONNRESET;
238 case ETIMEDOUT:
239 return TOR_TLS_ERROR_TIMEOUT;
240 case EHOSTUNREACH:
241 case ENETUNREACH:
242 return TOR_TLS_ERROR_NO_ROUTE;
243 case ECONNREFUSED:
244 return TOR_TLS_ERROR_CONNREFUSED; // least common
245 default:
246 return TOR_TLS_ERROR_MISC;
248 #endif
251 /** Given a TOR_TLS_* error code, return a string equivalent. */
252 const char *
253 tor_tls_err_to_string(int err)
255 if (err >= 0)
256 return "[Not an error.]";
257 switch (err) {
258 case TOR_TLS_ERROR_MISC: return "misc error";
259 case TOR_TLS_ERROR_IO: return "unexpected close";
260 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
261 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
262 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
263 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
264 case TOR_TLS_CLOSE: return "closed";
265 case TOR_TLS_WANTREAD: return "want to read";
266 case TOR_TLS_WANTWRITE: return "want to write";
267 default: return "(unknown error code)";
271 #define CATCH_SYSCALL 1
272 #define CATCH_ZERO 2
274 /** Given a TLS object and the result of an SSL_* call, use
275 * SSL_get_error to determine whether an error has occurred, and if so
276 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
277 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
278 * reporting syscall errors. If extra&CATCH_ZERO is true, return
279 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
281 * If an error has occurred, log it at level <b>severity</b> and describe the
282 * current action as <b>doing</b>.
284 static int
285 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
286 const char *doing, int severity)
288 int err = SSL_get_error(tls->ssl, r);
289 int tor_error = TOR_TLS_ERROR_MISC;
290 switch (err) {
291 case SSL_ERROR_NONE:
292 return TOR_TLS_DONE;
293 case SSL_ERROR_WANT_READ:
294 return TOR_TLS_WANTREAD;
295 case SSL_ERROR_WANT_WRITE:
296 return TOR_TLS_WANTWRITE;
297 case SSL_ERROR_SYSCALL:
298 if (extra&CATCH_SYSCALL)
299 return _TOR_TLS_SYSCALL;
300 if (r == 0) {
301 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
302 tor_error = TOR_TLS_ERROR_IO;
303 } else {
304 int e = tor_socket_errno(tls->socket);
305 log(severity, LD_NET,
306 "TLS error: <syscall error while %s> (errno=%d: %s)",
307 doing, e, tor_socket_strerror(e));
308 tor_error = tor_errno_to_tls_error(e);
310 tls_log_errors(tls, severity, doing);
311 return tor_error;
312 case SSL_ERROR_ZERO_RETURN:
313 if (extra&CATCH_ZERO)
314 return _TOR_TLS_ZERORETURN;
315 log(severity, LD_NET, "TLS connection closed while %s", doing);
316 tls_log_errors(tls, severity, doing);
317 return TOR_TLS_CLOSE;
318 default:
319 tls_log_errors(tls, severity, doing);
320 return TOR_TLS_ERROR_MISC;
324 /** Initialize OpenSSL, unless it has already been initialized.
326 static void
327 tor_tls_init(void)
329 if (!tls_library_is_initialized) {
330 long version;
331 SSL_library_init();
332 SSL_load_error_strings();
333 crypto_global_init(-1);
335 version = SSLeay();
337 /* OpenSSL 0.9.8l introdeced SSL3_FLAGS_ALLOW_UNSAGE_LEGACY_RENEGOTIATION
338 * here, but without thinking too hard about it: it turns out that the
339 * flag in question needed to be set at the last minute, and that it
340 * conflicted with an existing flag number that had already been added
341 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
342 * the flag with an option and (it seems) broke anything that used
343 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
344 * and we mustn't use the SSL3_FLAGS option with anything besides
345 * OpenSSL 0.9.8l.
347 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
348 * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
349 * set option 0x00040000L everywhere.
351 * No, we can't simply detect whether the flag or the option is present
352 * in the headers at build-time: some vendors (notably Apple) like to
353 * leave their headers out of sync with their libraries.
355 * Yes, it _is_ almost as if the OpenSSL developers decided that no
356 * program should be allowed to use renegotiation its first passed an
357 * test of intelligence and determination.
359 if (version >= 0x009080c0L && version < 0x009080d0L) {
360 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
361 "I will try SSL3_FLAGS to enable renegotation.",
362 SSLeay_version(SSLEAY_VERSION));
363 use_unsafe_renegotiation_flag = 1;
364 use_unsafe_renegotiation_op = 1;
365 } else if (version >= 0x009080d0L) {
366 log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
367 "I will try SSL_OP to enable renegotiation",
368 SSLeay_version(SSLEAY_VERSION));
369 use_unsafe_renegotiation_op = 1;
370 } else if (version < 0x009080c0L) {
371 log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
372 "0.9.8l, but some vendors have backported 0.9.8l's "
373 "renegotiation code to earlier versions, and some have "
374 "backported the code from 0.9.8m or 0.9.8n. I'll set both "
375 "SSL3_FLAGS and SSL_OP just to be safe.",
376 SSLeay_version(SSLEAY_VERSION), version);
377 use_unsafe_renegotiation_flag = 1;
378 use_unsafe_renegotiation_op = 1;
379 } else {
380 log_info(LD_GENERAL, "OpenSSL %s has version %lx",
381 SSLeay_version(SSLEAY_VERSION), version);
384 tls_library_is_initialized = 1;
388 /** Free all global TLS structures. */
389 void
390 tor_tls_free_all(void)
392 if (global_tls_context) {
393 tor_tls_context_decref(global_tls_context);
394 global_tls_context = NULL;
396 if (!HT_EMPTY(&tlsmap_root)) {
397 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
399 HT_CLEAR(tlsmap, &tlsmap_root);
400 #ifdef V2_HANDSHAKE_CLIENT
401 if (CLIENT_CIPHER_DUMMIES)
402 tor_free(CLIENT_CIPHER_DUMMIES);
403 if (CLIENT_CIPHER_STACK)
404 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
405 #endif
408 /** We need to give OpenSSL a callback to verify certificates. This is
409 * it: We always accept peer certs and complete the handshake. We
410 * don't validate them until later.
412 static int
413 always_accept_verify_cb(int preverify_ok,
414 X509_STORE_CTX *x509_ctx)
416 (void) preverify_ok;
417 (void) x509_ctx;
418 return 1;
421 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
422 static X509_NAME *
423 tor_x509_name_new(const char *cname)
425 int nid;
426 X509_NAME *name;
427 if (!(name = X509_NAME_new()))
428 return NULL;
429 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
430 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
431 (unsigned char*)cname, -1, -1, 0)))
432 goto error;
433 return name;
434 error:
435 X509_NAME_free(name);
436 return NULL;
439 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
440 * signed by the private key <b>rsa_sign</b>. The commonName of the
441 * certificate will be <b>cname</b>; the commonName of the issuer will be
442 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
443 * starting from now. Return a certificate on success, NULL on
444 * failure.
446 static X509 *
447 tor_tls_create_certificate(crypto_pk_env_t *rsa,
448 crypto_pk_env_t *rsa_sign,
449 const char *cname,
450 const char *cname_sign,
451 unsigned int cert_lifetime)
453 time_t start_time, end_time;
454 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
455 X509 *x509 = NULL;
456 X509_NAME *name = NULL, *name_issuer=NULL;
458 tor_tls_init();
460 start_time = time(NULL);
462 tor_assert(rsa);
463 tor_assert(cname);
464 tor_assert(rsa_sign);
465 tor_assert(cname_sign);
466 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
467 goto error;
468 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
469 goto error;
470 if (!(x509 = X509_new()))
471 goto error;
472 if (!(X509_set_version(x509, 2)))
473 goto error;
474 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
475 goto error;
477 if (!(name = tor_x509_name_new(cname)))
478 goto error;
479 if (!(X509_set_subject_name(x509, name)))
480 goto error;
481 if (!(name_issuer = tor_x509_name_new(cname_sign)))
482 goto error;
483 if (!(X509_set_issuer_name(x509, name_issuer)))
484 goto error;
486 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
487 goto error;
488 end_time = start_time + cert_lifetime;
489 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
490 goto error;
491 if (!X509_set_pubkey(x509, pkey))
492 goto error;
493 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
494 goto error;
496 goto done;
497 error:
498 if (x509) {
499 X509_free(x509);
500 x509 = NULL;
502 done:
503 tls_log_errors(NULL, LOG_WARN, "generating certificate");
504 if (sign_pkey)
505 EVP_PKEY_free(sign_pkey);
506 if (pkey)
507 EVP_PKEY_free(pkey);
508 if (name)
509 X509_NAME_free(name);
510 if (name_issuer)
511 X509_NAME_free(name_issuer);
512 return x509;
515 /** List of ciphers that servers should select from.*/
516 #define SERVER_CIPHER_LIST \
517 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
518 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
519 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
520 /* Note: for setting up your own private testing network with link crypto
521 * disabled, set the cipher lists to your cipher list to
522 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
523 * with any of the "real" Tors, though. */
525 #ifdef V2_HANDSHAKE_CLIENT
526 #define CIPHER(id, name) name ":"
527 #define XCIPHER(id, name)
528 /** List of ciphers that clients should advertise, omitting items that
529 * our OpenSSL doesn't know about. */
530 static const char CLIENT_CIPHER_LIST[] =
531 #include "./ciphers.inc"
533 #undef CIPHER
534 #undef XCIPHER
536 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
537 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
538 /** A list of all the ciphers that clients should advertise, including items
539 * that OpenSSL might not know about. */
540 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
541 #define CIPHER(id, name) { id, name },
542 #define XCIPHER(id, name) { id, #name },
543 #include "./ciphers.inc"
544 #undef CIPHER
545 #undef XCIPHER
548 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
549 static const int N_CLIENT_CIPHERS =
550 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
551 #endif
553 #ifndef V2_HANDSHAKE_CLIENT
554 #undef CLIENT_CIPHER_LIST
555 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
556 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
557 #endif
559 /** Remove a reference to <b>ctx</b>, and free it if it has no more
560 * references. */
561 static void
562 tor_tls_context_decref(tor_tls_context_t *ctx)
564 tor_assert(ctx);
565 if (--ctx->refcnt == 0) {
566 SSL_CTX_free(ctx->ctx);
567 X509_free(ctx->my_cert);
568 X509_free(ctx->my_id_cert);
569 crypto_free_pk_env(ctx->key);
570 tor_free(ctx);
574 /** Increase the reference count of <b>ctx</b>. */
575 static void
576 tor_tls_context_incref(tor_tls_context_t *ctx)
578 ++ctx->refcnt;
581 /** Create a new TLS context for use with Tor TLS handshakes.
582 * <b>identity</b> should be set to the identity key used to sign the
583 * certificate, and <b>nickname</b> set to the nickname to use.
585 * You can call this function multiple times. Each time you call it,
586 * it generates new certificates; all new connections will use
587 * the new SSL context.
590 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
592 crypto_pk_env_t *rsa = NULL;
593 EVP_PKEY *pkey = NULL;
594 tor_tls_context_t *result = NULL;
595 X509 *cert = NULL, *idcert = NULL;
596 char *nickname = NULL, *nn2 = NULL;
598 tor_tls_init();
599 nickname = crypto_random_hostname(8, 20, "www.", ".net");
600 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
602 /* Generate short-term RSA key. */
603 if (!(rsa = crypto_new_pk_env()))
604 goto error;
605 if (crypto_pk_generate_key(rsa)<0)
606 goto error;
607 /* Create certificate signed by identity key. */
608 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
609 key_lifetime);
610 /* Create self-signed certificate for identity key. */
611 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
612 IDENTITY_CERT_LIFETIME);
613 if (!cert || !idcert) {
614 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
615 goto error;
618 result = tor_malloc_zero(sizeof(tor_tls_context_t));
619 result->refcnt = 1;
620 result->my_cert = X509_dup(cert);
621 result->my_id_cert = X509_dup(idcert);
622 result->key = crypto_pk_dup_key(rsa);
624 #ifdef EVERYONE_HAS_AES
625 /* Tell OpenSSL to only use TLS1 */
626 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
627 goto error;
628 #else
629 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
630 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
631 goto error;
632 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
633 #endif
634 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
636 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
637 SSL_CTX_set_options(result->ctx,
638 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
639 #endif
640 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
641 * as authenticating any earlier-received data.
643 if (use_unsafe_renegotiation_op) {
644 SSL_CTX_set_options(result->ctx,
645 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
647 /* Don't actually allow compression; it uses ram and time, but the data
648 * we transmit is all encrypted anyway. */
649 if (result->ctx->comp_methods)
650 result->ctx->comp_methods = NULL;
651 #ifdef SSL_MODE_RELEASE_BUFFERS
652 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
653 #endif
654 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
655 goto error;
656 X509_free(cert); /* We just added a reference to cert. */
657 cert=NULL;
658 if (idcert) {
659 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
660 tor_assert(s);
661 X509_STORE_add_cert(s, idcert);
662 X509_free(idcert); /* The context now owns the reference to idcert */
663 idcert = NULL;
665 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
666 tor_assert(rsa);
667 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
668 goto error;
669 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
670 goto error;
671 EVP_PKEY_free(pkey);
672 pkey = NULL;
673 if (!SSL_CTX_check_private_key(result->ctx))
674 goto error;
676 crypto_dh_env_t *dh = crypto_dh_new();
677 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
678 crypto_dh_free(dh);
680 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
681 always_accept_verify_cb);
682 /* let us realloc bufs that we're writing from */
683 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
684 /* Free the old context if one exists. */
685 if (global_tls_context) {
686 /* This is safe even if there are open connections: OpenSSL does
687 * reference counting with SSL and SSL_CTX objects. */
688 tor_tls_context_decref(global_tls_context);
690 global_tls_context = result;
691 if (rsa)
692 crypto_free_pk_env(rsa);
693 tor_free(nickname);
694 tor_free(nn2);
695 return 0;
697 error:
698 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
699 tor_free(nickname);
700 tor_free(nn2);
701 if (pkey)
702 EVP_PKEY_free(pkey);
703 if (rsa)
704 crypto_free_pk_env(rsa);
705 if (result)
706 tor_tls_context_decref(result);
707 if (cert)
708 X509_free(cert);
709 if (idcert)
710 X509_free(idcert);
711 return -1;
714 #ifdef V2_HANDSHAKE_SERVER
715 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
716 * a list that indicates that the client knows how to do the v2 TLS connection
717 * handshake. */
718 static int
719 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
721 int i;
722 SSL_SESSION *session;
723 /* If we reached this point, we just got a client hello. See if there is
724 * a cipher list. */
725 if (!(session = SSL_get_session((SSL *)ssl))) {
726 log_warn(LD_NET, "No session on TLS?");
727 return 0;
729 if (!session->ciphers) {
730 log_warn(LD_NET, "No ciphers on session");
731 return 0;
733 /* Now we need to see if there are any ciphers whose presence means we're
734 * dealing with an updated Tor. */
735 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
736 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
737 const char *ciphername = SSL_CIPHER_get_name(cipher);
738 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
739 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
740 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
741 strcmp(ciphername, "(NONE)")) {
742 /* XXXX should be ld_debug */
743 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
744 // return 1;
745 goto dump_list;
748 return 0;
749 dump_list:
751 smartlist_t *elts = smartlist_create();
752 char *s;
753 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
754 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
755 const char *ciphername = SSL_CIPHER_get_name(cipher);
756 smartlist_add(elts, (char*)ciphername);
758 s = smartlist_join_strings(elts, ":", 0, NULL);
759 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
760 address, s);
761 tor_free(s);
762 smartlist_free(elts);
764 return 1;
767 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
768 * changes state. We use this:
769 * <ul><li>To alter the state of the handshake partway through, so we
770 * do not send or request extra certificates in v2 handshakes.</li>
771 * <li>To detect renegotiation</li></ul>
773 static void
774 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
776 tor_tls_t *tls;
777 (void) val;
778 if (type != SSL_CB_ACCEPT_LOOP)
779 return;
780 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
781 return;
783 tls = tor_tls_get_by_ssl(ssl);
784 if (tls) {
785 /* Check whether we're watching for renegotiates. If so, this is one! */
786 if (tls->negotiated_callback)
787 tls->got_renegotiate = 1;
788 } else {
789 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
792 /* Now check the cipher list. */
793 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
794 /*XXXX_TLS keep this from happening more than once! */
796 /* Yes, we're casting away the const from ssl. This is very naughty of us.
797 * Let's hope openssl doesn't notice! */
799 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
800 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
801 /* Don't send a hello request. */
802 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
804 if (tls) {
805 tls->wasV2Handshake = 1;
806 } else {
807 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
811 #endif
813 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
814 * a list designed to mimic a common web browser. Some of the ciphers in the
815 * list won't actually be implemented by OpenSSL: that's okay so long as the
816 * server doesn't select them, and the server won't select anything besides
817 * what's in SERVER_CIPHER_LIST.
819 * [If the server <b>does</b> select a bogus cipher, we won't crash or
820 * anything; we'll just fail later when we try to look up the cipher in
821 * ssl->cipher_list_by_id.]
823 static void
824 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
826 #ifdef V2_HANDSHAKE_CLIENT
827 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
828 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
829 * we want.*/
830 int i = 0, j = 0;
832 /* First, create a dummy SSL_CIPHER for every cipher. */
833 CLIENT_CIPHER_DUMMIES =
834 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
835 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
836 CLIENT_CIPHER_DUMMIES[i].valid = 1;
837 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
838 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
841 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
842 tor_assert(CLIENT_CIPHER_STACK);
844 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
845 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
846 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
847 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
850 /* Then copy as many ciphers as we can from the good list, inserting
851 * dummies as needed. */
852 j=0;
853 for (i = 0; i < N_CLIENT_CIPHERS; ) {
854 SSL_CIPHER *cipher = NULL;
855 if (j < sk_SSL_CIPHER_num(*ciphers))
856 cipher = sk_SSL_CIPHER_value(*ciphers, j);
857 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
858 log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
859 ++j;
860 } else if (cipher &&
861 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
862 log_debug(LD_NET, "Found cipher %s", cipher->name);
863 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
864 ++j;
865 ++i;
866 } else {
867 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
868 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
869 ++i;
874 sk_SSL_CIPHER_free(*ciphers);
875 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
876 tor_assert(*ciphers);
878 #else
879 (void)ciphers;
880 #endif
883 /** Create a new TLS object from a file descriptor, and a flag to
884 * determine whether it is functioning as a server.
886 tor_tls_t *
887 tor_tls_new(int sock, int isServer)
889 BIO *bio = NULL;
890 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
892 tor_assert(global_tls_context); /* make sure somebody made it first */
893 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
894 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
895 tor_free(result);
896 return NULL;
899 #ifdef SSL_set_tlsext_host_name
900 /* Browsers use the TLS hostname extension, so we should too. */
902 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
903 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
904 tor_free(fake_hostname);
906 #endif
908 if (!SSL_set_cipher_list(result->ssl,
909 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
910 tls_log_errors(NULL, LOG_WARN, "setting ciphers");
911 #ifdef SSL_set_tlsext_host_name
912 SSL_set_tlsext_host_name(result->ssl, NULL);
913 #endif
914 SSL_free(result->ssl);
915 tor_free(result);
916 return NULL;
918 if (!isServer)
919 rectify_client_ciphers(&result->ssl->cipher_list);
920 result->socket = sock;
921 bio = BIO_new_socket(sock, BIO_NOCLOSE);
922 if (! bio) {
923 tls_log_errors(NULL, LOG_WARN, "opening BIO");
924 #ifdef SSL_set_tlsext_host_name
925 SSL_set_tlsext_host_name(result->ssl, NULL);
926 #endif
927 SSL_free(result->ssl);
928 tor_free(result);
929 return NULL;
931 HT_INSERT(tlsmap, &tlsmap_root, result);
932 SSL_set_bio(result->ssl, bio, bio);
933 tor_tls_context_incref(global_tls_context);
934 result->context = global_tls_context;
935 result->state = TOR_TLS_ST_HANDSHAKE;
936 result->isServer = isServer;
937 result->wantwrite_n = 0;
938 result->last_write_count = BIO_number_written(bio);
939 result->last_read_count = BIO_number_read(bio);
940 if (result->last_write_count || result->last_read_count) {
941 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
942 result->last_read_count, result->last_write_count);
944 #ifdef V2_HANDSHAKE_SERVER
945 if (isServer) {
946 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
948 #endif
950 /* Not expected to get called. */
951 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
952 return result;
955 /** Make future log messages about <b>tls</b> display the address
956 * <b>address</b>.
958 void
959 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
961 tor_assert(tls);
962 tor_free(tls->address);
963 tls->address = tor_strdup(address);
966 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
967 * next gets a client-side renegotiate in the middle of a read. Do not
968 * invoke this function until <em>after</em> initial handshaking is done!
970 void
971 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
972 void (*cb)(tor_tls_t *, void *arg),
973 void *arg)
975 tls->negotiated_callback = cb;
976 tls->callback_arg = arg;
977 tls->got_renegotiate = 0;
978 #ifdef V2_HANDSHAKE_SERVER
979 if (cb) {
980 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
981 } else {
982 SSL_set_info_callback(tls->ssl, NULL);
984 #endif
987 /** If this version of openssl requires it, turn on renegotiation on
988 * <b>tls</b>.
990 static void
991 tor_tls_unblock_renegotiation(tor_tls_t *tls)
993 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
994 * as authenticating any earlier-received data. */
995 if (use_unsafe_renegotiation_flag) {
996 tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
998 if (use_unsafe_renegotiation_op) {
999 SSL_set_options(tls->ssl,
1000 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1004 /** If this version of openssl supports it, turn off renegotiation on
1005 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1006 * to use belt-and-suspenders here.)
1008 void
1009 tor_tls_block_renegotiation(tor_tls_t *tls)
1011 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1014 /** Return whether this tls initiated the connect (client) or
1015 * received it (server). */
1017 tor_tls_is_server(tor_tls_t *tls)
1019 tor_assert(tls);
1020 return tls->isServer;
1023 /** Release resources associated with a TLS object. Does not close the
1024 * underlying file descriptor.
1026 void
1027 tor_tls_free(tor_tls_t *tls)
1029 tor_tls_t *removed;
1030 tor_assert(tls && tls->ssl);
1031 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
1032 if (!removed) {
1033 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
1035 #ifdef SSL_set_tlsext_host_name
1036 SSL_set_tlsext_host_name(tls->ssl, NULL);
1037 #endif
1038 SSL_free(tls->ssl);
1039 tls->ssl = NULL;
1040 tls->negotiated_callback = NULL;
1041 if (tls->context)
1042 tor_tls_context_decref(tls->context);
1043 tor_free(tls->address);
1044 tor_free(tls);
1047 /** Underlying function for TLS reading. Reads up to <b>len</b>
1048 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1049 * number of characters read. On failure, returns TOR_TLS_ERROR,
1050 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1053 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
1055 int r, err;
1056 tor_assert(tls);
1057 tor_assert(tls->ssl);
1058 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1059 tor_assert(len<INT_MAX);
1060 r = SSL_read(tls->ssl, cp, (int)len);
1061 if (r > 0) {
1062 #ifdef V2_HANDSHAKE_SERVER
1063 if (tls->got_renegotiate) {
1064 /* Renegotiation happened! */
1065 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1066 if (tls->negotiated_callback)
1067 tls->negotiated_callback(tls, tls->callback_arg);
1068 tls->got_renegotiate = 0;
1070 #endif
1071 return r;
1073 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
1074 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
1075 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1076 tls->state = TOR_TLS_ST_CLOSED;
1077 return TOR_TLS_CLOSE;
1078 } else {
1079 tor_assert(err != TOR_TLS_DONE);
1080 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1081 return err;
1085 /** Underlying function for TLS writing. Write up to <b>n</b>
1086 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1087 * number of characters written. On failure, returns TOR_TLS_ERROR,
1088 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1091 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1093 int r, err;
1094 tor_assert(tls);
1095 tor_assert(tls->ssl);
1096 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1097 tor_assert(n < INT_MAX);
1098 if (n == 0)
1099 return 0;
1100 if (tls->wantwrite_n) {
1101 /* if WANTWRITE last time, we must use the _same_ n as before */
1102 tor_assert(n >= tls->wantwrite_n);
1103 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1104 (int)n, (int)tls->wantwrite_n);
1105 n = tls->wantwrite_n;
1106 tls->wantwrite_n = 0;
1108 r = SSL_write(tls->ssl, cp, (int)n);
1109 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
1110 if (err == TOR_TLS_DONE) {
1111 return r;
1113 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1114 tls->wantwrite_n = n;
1116 return err;
1119 /** Perform initial handshake on <b>tls</b>. When finished, returns
1120 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1121 * or TOR_TLS_WANTWRITE.
1124 tor_tls_handshake(tor_tls_t *tls)
1126 int r;
1127 tor_assert(tls);
1128 tor_assert(tls->ssl);
1129 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1130 check_no_tls_errors();
1131 if (tls->isServer) {
1132 r = SSL_accept(tls->ssl);
1133 } else {
1134 r = SSL_connect(tls->ssl);
1136 /* We need to call this here and not earlier, since OpenSSL has a penchant
1137 * for clearing its flags when you say accept or connect. */
1138 tor_tls_unblock_renegotiation(tls);
1139 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
1140 if (ERR_peek_error() != 0) {
1141 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
1142 "handshaking");
1143 return TOR_TLS_ERROR_MISC;
1145 if (r == TOR_TLS_DONE) {
1146 tls->state = TOR_TLS_ST_OPEN;
1147 if (tls->isServer) {
1148 SSL_set_info_callback(tls->ssl, NULL);
1149 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1150 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1151 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
1152 #ifdef V2_HANDSHAKE_SERVER
1153 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
1154 /* This check is redundant, but back when we did it in the callback,
1155 * we might have not been able to look up the tor_tls_t if the code
1156 * was buggy. Fixing that. */
1157 if (!tls->wasV2Handshake) {
1158 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1159 " get set. Fixing that.");
1161 tls->wasV2Handshake = 1;
1162 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
1163 "for renegotiation.");
1164 } else {
1165 tls->wasV2Handshake = 0;
1167 #endif
1168 } else {
1169 #ifdef V2_HANDSHAKE_CLIENT
1170 /* If we got no ID cert, we're a v2 handshake. */
1171 X509 *cert = SSL_get_peer_certificate(tls->ssl);
1172 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
1173 int n_certs = sk_X509_num(chain);
1174 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
1175 tls->wasV2Handshake = 0;
1176 else {
1177 log_debug(LD_NET, "Server sent back a single certificate; looks like "
1178 "a v2 handshake on %p.", tls);
1179 tls->wasV2Handshake = 1;
1181 if (cert)
1182 X509_free(cert);
1183 #endif
1184 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1185 tls_log_errors(NULL, LOG_WARN, "re-setting ciphers");
1186 r = TOR_TLS_ERROR_MISC;
1190 return r;
1193 /** Client only: Renegotiate a TLS session. When finished, returns
1194 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1195 * TOR_TLS_WANTWRITE.
1198 tor_tls_renegotiate(tor_tls_t *tls)
1200 int r;
1201 tor_assert(tls);
1202 /* We could do server-initiated renegotiation too, but that would be tricky.
1203 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1204 tor_assert(!tls->isServer);
1205 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1206 int r = SSL_renegotiate(tls->ssl);
1207 if (r <= 0) {
1208 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1210 tls->state = TOR_TLS_ST_RENEGOTIATE;
1212 r = SSL_do_handshake(tls->ssl);
1213 if (r == 1) {
1214 tls->state = TOR_TLS_ST_OPEN;
1215 return TOR_TLS_DONE;
1216 } else
1217 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1220 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1221 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1222 * or TOR_TLS_WANTWRITE.
1225 tor_tls_shutdown(tor_tls_t *tls)
1227 int r, err;
1228 char buf[128];
1229 tor_assert(tls);
1230 tor_assert(tls->ssl);
1232 while (1) {
1233 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1234 /* If we've already called shutdown once to send a close message,
1235 * we read until the other side has closed too.
1237 do {
1238 r = SSL_read(tls->ssl, buf, 128);
1239 } while (r>0);
1240 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1241 LOG_INFO);
1242 if (err == _TOR_TLS_ZERORETURN) {
1243 tls->state = TOR_TLS_ST_GOTCLOSE;
1244 /* fall through... */
1245 } else {
1246 return err;
1250 r = SSL_shutdown(tls->ssl);
1251 if (r == 1) {
1252 /* If shutdown returns 1, the connection is entirely closed. */
1253 tls->state = TOR_TLS_ST_CLOSED;
1254 return TOR_TLS_DONE;
1256 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1257 LOG_INFO);
1258 if (err == _TOR_TLS_SYSCALL) {
1259 /* The underlying TCP connection closed while we were shutting down. */
1260 tls->state = TOR_TLS_ST_CLOSED;
1261 return TOR_TLS_DONE;
1262 } else if (err == _TOR_TLS_ZERORETURN) {
1263 /* The TLS connection says that it sent a shutdown record, but
1264 * isn't done shutting down yet. Make sure that this hasn't
1265 * happened before, then go back to the start of the function
1266 * and try to read.
1268 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1269 tls->state == TOR_TLS_ST_SENTCLOSE) {
1270 log(LOG_WARN, LD_NET,
1271 "TLS returned \"half-closed\" value while already half-closed");
1272 return TOR_TLS_ERROR_MISC;
1274 tls->state = TOR_TLS_ST_SENTCLOSE;
1275 /* fall through ... */
1276 } else {
1277 return err;
1279 } /* end loop */
1282 /** Return true iff this TLS connection is authenticated.
1285 tor_tls_peer_has_cert(tor_tls_t *tls)
1287 X509 *cert;
1288 cert = SSL_get_peer_certificate(tls->ssl);
1289 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1290 if (!cert)
1291 return 0;
1292 X509_free(cert);
1293 return 1;
1296 /** Warn that a certificate lifetime extends through a certain range. */
1297 static void
1298 log_cert_lifetime(X509 *cert, const char *problem)
1300 BIO *bio = NULL;
1301 BUF_MEM *buf;
1302 char *s1=NULL, *s2=NULL;
1303 char mytime[33];
1304 time_t now = time(NULL);
1305 struct tm tm;
1307 if (problem)
1308 log_warn(LD_GENERAL,
1309 "Certificate %s: is your system clock set incorrectly?",
1310 problem);
1312 if (!(bio = BIO_new(BIO_s_mem()))) {
1313 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1315 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1316 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1317 goto end;
1319 BIO_get_mem_ptr(bio, &buf);
1320 s1 = tor_strndup(buf->data, buf->length);
1322 (void)BIO_reset(bio);
1323 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1324 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1325 goto end;
1327 BIO_get_mem_ptr(bio, &buf);
1328 s2 = tor_strndup(buf->data, buf->length);
1330 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1332 log_warn(LD_GENERAL,
1333 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1334 s1,s2,mytime);
1336 end:
1337 /* Not expected to get invoked */
1338 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1339 if (bio)
1340 BIO_free(bio);
1341 if (s1)
1342 tor_free(s1);
1343 if (s2)
1344 tor_free(s2);
1347 /** Helper function: try to extract a link certificate and an identity
1348 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1349 * *<b>id_cert_out</b> respectively. Log all messages at level
1350 * <b>severity</b>.
1352 * Note that a reference is added to cert_out, so it needs to be
1353 * freed. id_cert_out doesn't. */
1354 static void
1355 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1356 X509 **cert_out, X509 **id_cert_out)
1358 X509 *cert = NULL, *id_cert = NULL;
1359 STACK_OF(X509) *chain = NULL;
1360 int num_in_chain, i;
1361 *cert_out = *id_cert_out = NULL;
1363 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1364 return;
1365 *cert_out = cert;
1366 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1367 return;
1368 num_in_chain = sk_X509_num(chain);
1369 /* 1 means we're receiving (server-side), and it's just the id_cert.
1370 * 2 means we're connecting (client-side), and it's both the link
1371 * cert and the id_cert.
1373 if (num_in_chain < 1) {
1374 log_fn(severity,LD_PROTOCOL,
1375 "Unexpected number of certificates in chain (%d)",
1376 num_in_chain);
1377 return;
1379 for (i=0; i<num_in_chain; ++i) {
1380 id_cert = sk_X509_value(chain, i);
1381 if (X509_cmp(id_cert, cert) != 0)
1382 break;
1384 *id_cert_out = id_cert;
1387 /** If the provided tls connection is authenticated and has a
1388 * certificate chain that is currently valid and signed, then set
1389 * *<b>identity_key</b> to the identity certificate's key and return
1390 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1393 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1395 X509 *cert = NULL, *id_cert = NULL;
1396 EVP_PKEY *id_pkey = NULL;
1397 RSA *rsa;
1398 int r = -1;
1400 *identity_key = NULL;
1402 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1403 if (!cert)
1404 goto done;
1405 if (!id_cert) {
1406 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1407 goto done;
1409 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1410 X509_verify(cert, id_pkey) <= 0) {
1411 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1412 tls_log_errors(tls, severity,"verifying certificate");
1413 goto done;
1416 rsa = EVP_PKEY_get1_RSA(id_pkey);
1417 if (!rsa)
1418 goto done;
1419 *identity_key = _crypto_new_pk_env_rsa(rsa);
1421 r = 0;
1423 done:
1424 if (cert)
1425 X509_free(cert);
1426 if (id_pkey)
1427 EVP_PKEY_free(id_pkey);
1429 /* This should never get invoked, but let's make sure in case OpenSSL
1430 * acts unexpectedly. */
1431 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1433 return r;
1436 /** Check whether the certificate set on the connection <b>tls</b> is
1437 * expired or not-yet-valid, give or take <b>tolerance</b>
1438 * seconds. Return 0 for valid, -1 for failure.
1440 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1443 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1445 time_t now, t;
1446 X509 *cert;
1447 int r = -1;
1449 now = time(NULL);
1451 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1452 goto done;
1454 t = now + tolerance;
1455 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1456 log_cert_lifetime(cert, "not yet valid");
1457 goto done;
1459 t = now - tolerance;
1460 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1461 log_cert_lifetime(cert, "already expired");
1462 goto done;
1465 r = 0;
1466 done:
1467 if (cert)
1468 X509_free(cert);
1469 /* Not expected to get invoked */
1470 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1472 return r;
1475 /** Return the number of bytes available for reading from <b>tls</b>.
1478 tor_tls_get_pending_bytes(tor_tls_t *tls)
1480 tor_assert(tls);
1481 return SSL_pending(tls->ssl);
1484 /** If <b>tls</b> requires that the next write be of a particular size,
1485 * return that size. Otherwise, return 0. */
1486 size_t
1487 tor_tls_get_forced_write_size(tor_tls_t *tls)
1489 return tls->wantwrite_n;
1492 /** Sets n_read and n_written to the number of bytes read and written,
1493 * respectively, on the raw socket used by <b>tls</b> since the last time this
1494 * function was called on <b>tls</b>. */
1495 void
1496 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1498 BIO *wbio, *tmpbio;
1499 unsigned long r, w;
1500 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1501 /* We want the number of bytes actually for real written. Unfortunately,
1502 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1503 * which makes the answer turn out wrong. Let's cope with that. Note
1504 * that this approach will fail if we ever replace tls->ssl's BIOs with
1505 * buffering bios for reasons of our own. As an alternative, we could
1506 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1507 * that would be tempting fate. */
1508 wbio = SSL_get_wbio(tls->ssl);
1509 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1510 wbio = tmpbio;
1511 w = BIO_number_written(wbio);
1513 /* We are ok with letting these unsigned ints go "negative" here:
1514 * If we wrapped around, this should still give us the right answer, unless
1515 * we wrapped around by more than ULONG_MAX since the last time we called
1516 * this function.
1518 *n_read = (size_t)(r - tls->last_read_count);
1519 *n_written = (size_t)(w - tls->last_write_count);
1520 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1521 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1522 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1523 r, tls->last_read_count, w, tls->last_write_count);
1525 tls->last_read_count = r;
1526 tls->last_write_count = w;
1529 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1530 * errors, log an error message. */
1531 void
1532 _check_no_tls_errors(const char *fname, int line)
1534 if (ERR_peek_error() == 0)
1535 return;
1536 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1537 tor_fix_source_file(fname), line);
1538 tls_log_errors(NULL, LOG_WARN, NULL);
1541 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1542 * TLS handshake. Output is undefined if the handshake isn't finished. */
1544 tor_tls_used_v1_handshake(tor_tls_t *tls)
1546 if (tls->isServer) {
1547 #ifdef V2_HANDSHAKE_SERVER
1548 return ! tls->wasV2Handshake;
1549 #endif
1550 } else {
1551 #ifdef V2_HANDSHAKE_CLIENT
1552 return ! tls->wasV2Handshake;
1553 #endif
1555 return 1;
1558 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1559 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1560 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1561 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1562 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1563 void
1564 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1565 size_t *rbuf_capacity, size_t *rbuf_bytes,
1566 size_t *wbuf_capacity, size_t *wbuf_bytes)
1568 if (tls->ssl->s3->rbuf.buf)
1569 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1570 else
1571 *rbuf_capacity = 0;
1572 if (tls->ssl->s3->wbuf.buf)
1573 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1574 else
1575 *wbuf_capacity = 0;
1576 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1577 *wbuf_bytes = tls->ssl->s3->wbuf.left;