If the user has an openssl that supports my "release buffer ram" patch, use it.
[tor.git] / src / common / tortls.c
blobb931176973a480bc6e6df738cf90ff7e236cf7cf
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char tortls_c_id[] =
7 "$Id$";
9 /**
10 * \file tortls.c
11 * \brief Wrapper functions to present a consistent interface to
12 * TLS, SSL, and X.509 functions from OpenSSL.
13 **/
15 /* (Unlike other tor functions, these
16 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
17 * functions and variables.)
20 #include "orconfig.h"
22 #include <assert.h>
23 #include <openssl/ssl.h>
24 #include <openssl/ssl3.h>
25 #include <openssl/err.h>
26 #include <openssl/tls1.h>
27 #include <openssl/asn1.h>
28 #include <openssl/bio.h>
29 #include <openssl/opensslv.h>
31 #if OPENSSL_VERSION_NUMBER < 0x00907000l
32 #error "We require openssl >= 0.9.7"
33 #endif
35 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
37 #include "crypto.h"
38 #include "tortls.h"
39 #include "util.h"
40 #include "log.h"
41 #include "container.h"
42 #include "ht.h"
43 #include <string.h>
45 /* Enable the "v2" TLS handshake.
47 #define V2_HANDSHAKE_SERVER
48 #define V2_HANDSHAKE_CLIENT
50 /* Copied from or.h */
51 #define LEGAL_NICKNAME_CHARACTERS \
52 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
54 /** How long do identity certificates live? (sec) */
55 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
57 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
59 /** Structure holding the TLS state for a single connection. */
60 typedef struct tor_tls_context_t {
61 int refcnt;
62 SSL_CTX *ctx;
63 X509 *my_cert;
64 X509 *my_id_cert;
65 crypto_pk_env_t *key;
66 } tor_tls_context_t;
68 /** Holds a SSL object and its associated data. Members are only
69 * accessed from within tortls.c.
71 struct tor_tls_t {
72 HT_ENTRY(tor_tls_t) node;
73 tor_tls_context_t *context; /** A link to the context object for this tls */
74 SSL *ssl; /**< An OpenSSL SSL object. */
75 int socket; /**< The underlying file descriptor for this TLS connection. */
76 char *address; /**< An address to log when describing this connectinon. */
77 enum {
78 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
79 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
80 } state : 3; /**< The current SSL state, depending on which operations have
81 * completed successfully. */
82 unsigned int isServer:1; /**< True iff this is a server-side connection */
83 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
84 * this connection used the updated version
85 * of the connection protocol (client sends
86 * different cipher list, server sends only
87 * one certificate). */
88 /** True iff we should call negotiated_callback when we're done reading. */
89 unsigned int got_renegotiate:1;
90 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
91 * time. */
92 /** Last values retrieved from BIO_number_read()/write(); see
93 * tor_tls_get_n_raw_bytes() for usage.
95 unsigned long last_write_count;
96 unsigned long last_read_count;
97 /** If set, a callback to invoke whenever the client tries to renegotiate
98 * the handshake. */
99 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
100 /** Argument to pass to negotiated_callback. */
101 void *callback_arg;
104 /** Helper: compare tor_tls_t objects by its SSL. */
105 static INLINE int
106 tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
108 return a->ssl == b->ssl;
111 /** Helper: return a hash value for a tor_tls_t by its SSL. */
112 static INLINE unsigned int
113 tor_tls_entry_hash(const tor_tls_t *a)
115 #if SIZEOF_INT == SIZEOF_VOID_P
116 return ((unsigned int)(uintptr_t)a->ssl);
117 #else
118 return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
119 #endif
122 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
124 static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
126 HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
127 tor_tls_entries_eq)
128 HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
129 tor_tls_entries_eq, 0.6, malloc, realloc, free)
131 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
132 * pointer. */
133 static INLINE tor_tls_t *
134 tor_tls_get_by_ssl(const SSL *ssl)
136 tor_tls_t search, *result;
137 memset(&search, 0, sizeof(search));
138 search.ssl = (SSL*)ssl;
139 result = HT_FIND(tlsmap, &tlsmap_root, &search);
140 return result;
143 static void tor_tls_context_decref(tor_tls_context_t *ctx);
144 static void tor_tls_context_incref(tor_tls_context_t *ctx);
145 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
146 crypto_pk_env_t *rsa_sign,
147 const char *cname,
148 const char *cname_sign,
149 unsigned int lifetime);
151 /** Global tls context. We keep it here because nobody else needs to
152 * touch it. */
153 static tor_tls_context_t *global_tls_context = NULL;
154 /** True iff tor_tls_init() has been called. */
155 static int tls_library_is_initialized = 0;
157 /* Module-internal error codes. */
158 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
159 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
161 /** Log all pending tls errors at level <b>severity</b>. Use
162 * <b>doing</b> to describe our current activities.
164 static void
165 tls_log_errors(tor_tls_t *tls, int severity, const char *doing)
167 unsigned long err;
168 const char *msg, *lib, *func, *addr;
169 addr = tls ? tls->address : NULL;
170 while ((err = ERR_get_error()) != 0) {
171 msg = (const char*)ERR_reason_error_string(err);
172 lib = (const char*)ERR_lib_error_string(err);
173 func = (const char*)ERR_func_error_string(err);
174 if (!msg) msg = "(null)";
175 if (doing) {
176 log(severity, LD_NET, "TLS error while %s%s%s: %s (in %s:%s)",
177 doing, addr?" with ":"", addr?addr:"",
178 msg, lib, func);
179 } else {
180 log(severity, LD_NET, "TLS error%s%s: %s (in %s:%s)",
181 addr?" with ":"", addr?addr:"",
182 msg, lib, func);
187 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
188 * code. */
189 static int
190 tor_errno_to_tls_error(int e)
192 #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
193 switch (e) {
194 case WSAECONNRESET: // most common
195 return TOR_TLS_ERROR_CONNRESET;
196 case WSAETIMEDOUT:
197 return TOR_TLS_ERROR_TIMEOUT;
198 case WSAENETUNREACH:
199 case WSAEHOSTUNREACH:
200 return TOR_TLS_ERROR_NO_ROUTE;
201 case WSAECONNREFUSED:
202 return TOR_TLS_ERROR_CONNREFUSED; // least common
203 default:
204 return TOR_TLS_ERROR_MISC;
206 #else
207 switch (e) {
208 case ECONNRESET: // most common
209 return TOR_TLS_ERROR_CONNRESET;
210 case ETIMEDOUT:
211 return TOR_TLS_ERROR_TIMEOUT;
212 case EHOSTUNREACH:
213 case ENETUNREACH:
214 return TOR_TLS_ERROR_NO_ROUTE;
215 case ECONNREFUSED:
216 return TOR_TLS_ERROR_CONNREFUSED; // least common
217 default:
218 return TOR_TLS_ERROR_MISC;
220 #endif
223 /** Given a TOR_TLS_* error code, return a string equivalent. */
224 const char *
225 tor_tls_err_to_string(int err)
227 if (err >= 0)
228 return "[Not an error.]";
229 switch (err) {
230 case TOR_TLS_ERROR_MISC: return "misc error";
231 case TOR_TLS_ERROR_IO: return "unexpected close";
232 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
233 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
234 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
235 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
236 case TOR_TLS_CLOSE: return "closed";
237 case TOR_TLS_WANTREAD: return "want to read";
238 case TOR_TLS_WANTWRITE: return "want to write";
239 default: return "(unknown error code)";
243 #define CATCH_SYSCALL 1
244 #define CATCH_ZERO 2
246 /** Given a TLS object and the result of an SSL_* call, use
247 * SSL_get_error to determine whether an error has occurred, and if so
248 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
249 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
250 * reporting syscall errors. If extra&CATCH_ZERO is true, return
251 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
253 * If an error has occurred, log it at level <b>severity</b> and describe the
254 * current action as <b>doing</b>.
256 static int
257 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
258 const char *doing, int severity)
260 int err = SSL_get_error(tls->ssl, r);
261 int tor_error = TOR_TLS_ERROR_MISC;
262 switch (err) {
263 case SSL_ERROR_NONE:
264 return TOR_TLS_DONE;
265 case SSL_ERROR_WANT_READ:
266 return TOR_TLS_WANTREAD;
267 case SSL_ERROR_WANT_WRITE:
268 return TOR_TLS_WANTWRITE;
269 case SSL_ERROR_SYSCALL:
270 if (extra&CATCH_SYSCALL)
271 return _TOR_TLS_SYSCALL;
272 if (r == 0) {
273 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
274 tor_error = TOR_TLS_ERROR_IO;
275 } else {
276 int e = tor_socket_errno(tls->socket);
277 log(severity, LD_NET,
278 "TLS error: <syscall error while %s> (errno=%d: %s)",
279 doing, e, tor_socket_strerror(e));
280 tor_error = tor_errno_to_tls_error(e);
282 tls_log_errors(tls, severity, doing);
283 return tor_error;
284 case SSL_ERROR_ZERO_RETURN:
285 if (extra&CATCH_ZERO)
286 return _TOR_TLS_ZERORETURN;
287 log(severity, LD_NET, "TLS connection closed while %s", doing);
288 tls_log_errors(tls, severity, doing);
289 return TOR_TLS_CLOSE;
290 default:
291 tls_log_errors(tls, severity, doing);
292 return TOR_TLS_ERROR_MISC;
296 /** Initialize OpenSSL, unless it has already been initialized.
298 static void
299 tor_tls_init(void)
301 if (!tls_library_is_initialized) {
302 SSL_library_init();
303 SSL_load_error_strings();
304 crypto_global_init(-1);
305 tls_library_is_initialized = 1;
309 /** Free all global TLS structures. */
310 void
311 tor_tls_free_all(void)
313 if (global_tls_context) {
314 tor_tls_context_decref(global_tls_context);
315 global_tls_context = NULL;
317 if (!HT_EMPTY(&tlsmap_root)) {
318 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
320 HT_CLEAR(tlsmap, &tlsmap_root);
323 /** We need to give OpenSSL a callback to verify certificates. This is
324 * it: We always accept peer certs and complete the handshake. We
325 * don't validate them until later.
327 static int
328 always_accept_verify_cb(int preverify_ok,
329 X509_STORE_CTX *x509_ctx)
331 (void) preverify_ok;
332 (void) x509_ctx;
333 return 1;
336 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
337 static X509_NAME *
338 tor_x509_name_new(const char *cname)
340 int nid;
341 X509_NAME *name;
342 if (!(name = X509_NAME_new()))
343 return NULL;
344 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
345 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
346 (unsigned char*)cname, -1, -1, 0)))
347 goto error;
348 return name;
349 error:
350 X509_NAME_free(name);
351 return NULL;
354 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
355 * signed by the private key <b>rsa_sign</b>. The commonName of the
356 * certificate will be <b>cname</b>; the commonName of the issuer will be
357 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
358 * starting from now. Return a certificate on success, NULL on
359 * failure.
361 static X509 *
362 tor_tls_create_certificate(crypto_pk_env_t *rsa,
363 crypto_pk_env_t *rsa_sign,
364 const char *cname,
365 const char *cname_sign,
366 unsigned int cert_lifetime)
368 time_t start_time, end_time;
369 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
370 X509 *x509 = NULL;
371 X509_NAME *name = NULL, *name_issuer=NULL;
373 tor_tls_init();
375 start_time = time(NULL);
377 tor_assert(rsa);
378 tor_assert(cname);
379 tor_assert(rsa_sign);
380 tor_assert(cname_sign);
381 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
382 goto error;
383 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
384 goto error;
385 if (!(x509 = X509_new()))
386 goto error;
387 if (!(X509_set_version(x509, 2)))
388 goto error;
389 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
390 goto error;
392 if (!(name = tor_x509_name_new(cname)))
393 goto error;
394 if (!(X509_set_subject_name(x509, name)))
395 goto error;
396 if (!(name_issuer = tor_x509_name_new(cname_sign)))
397 goto error;
398 if (!(X509_set_issuer_name(x509, name_issuer)))
399 goto error;
401 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
402 goto error;
403 end_time = start_time + cert_lifetime;
404 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
405 goto error;
406 if (!X509_set_pubkey(x509, pkey))
407 goto error;
408 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
409 goto error;
411 goto done;
412 error:
413 if (x509) {
414 X509_free(x509);
415 x509 = NULL;
417 done:
418 tls_log_errors(NULL, LOG_WARN, "generating certificate");
419 if (sign_pkey)
420 EVP_PKEY_free(sign_pkey);
421 if (pkey)
422 EVP_PKEY_free(pkey);
423 if (name)
424 X509_NAME_free(name);
425 if (name_issuer)
426 X509_NAME_free(name_issuer);
427 return x509;
430 #define SERVER_CIPHER_LIST \
431 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
432 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
433 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
434 /* Note: for setting up your own private testing network with link crypto
435 * disabled, set the cipher lists to your cipher list to
436 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
437 * with any of the "real" Tors, though. */
439 #if OPENSSL_VERSION_NUMBER >= 0x00908020l
440 #define CLIENT_CIPHER_LIST \
441 (TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ":" \
442 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":" \
443 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
444 TLS1_TXT_DHE_DSS_WITH_AES_256_SHA ":" \
445 TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA ":" \
446 TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA ":" \
447 TLS1_TXT_RSA_WITH_AES_256_SHA ":" \
448 TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA ":" \
449 TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ":" \
450 TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA ":" \
451 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":" \
452 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
453 TLS1_TXT_DHE_DSS_WITH_AES_128_SHA ":" \
454 TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA":" \
455 TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA":" \
456 TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA ":" \
457 TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA ":" \
458 SSL3_TXT_RSA_RC4_128_MD5 ":" \
459 SSL3_TXT_RSA_RC4_128_SHA ":" \
460 TLS1_TXT_RSA_WITH_AES_128_SHA ":" \
461 TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA ":" \
462 TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":" \
463 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
464 SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA ":" \
465 TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA ":" \
466 TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA ":" \
467 /*SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA ":"*/ \
468 SSL3_TXT_RSA_DES_192_CBC3_SHA)
469 /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA is commented out because it doesn't
470 * really exist; if I understand correctly, it's a bit of silliness that
471 * netscape did on its own before any standard for what they wanted was
472 * formally approved. Nonetheless, Firefox still uses it, so we need to
473 * fake it at some point soon. XXXX021 -NM */
474 #else
475 /* Ug. We don't have as many ciphers with openssl 0.9.7 as we'd like. Fix
476 * this list into something that sucks less. */
477 #define CLIENT_CIPHER_LIST \
478 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
479 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
480 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
481 SSL3_TXT_RSA_RC4_128_SHA)
482 #endif
484 #ifndef V2_HANDSHAKE_CLIENT
485 #undef CLIENT_CIPHER_LIST
486 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
487 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
488 #endif
490 /** Remove a reference to <b>ctx</b>, and free it if it has no more
491 * references. */
492 static void
493 tor_tls_context_decref(tor_tls_context_t *ctx)
495 tor_assert(ctx);
496 if (--ctx->refcnt == 0) {
497 SSL_CTX_free(ctx->ctx);
498 X509_free(ctx->my_cert);
499 X509_free(ctx->my_id_cert);
500 crypto_free_pk_env(ctx->key);
501 tor_free(ctx);
505 /** Increase the reference count of <b>ctx</b>. */
506 static void
507 tor_tls_context_incref(tor_tls_context_t *ctx)
509 ++ctx->refcnt;
512 /** Create a new TLS context for use with Tor TLS handshakes.
513 * <b>identity</b> should be set to the identity key used to sign the
514 * certificate, and <b>nickname</b> set to the nickname to use.
516 * You can call this function multiple times. Each time you call it,
517 * it generates new certificates; all new connections will use
518 * the new SSL context.
521 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
523 crypto_pk_env_t *rsa = NULL;
524 crypto_dh_env_t *dh = NULL;
525 EVP_PKEY *pkey = NULL;
526 tor_tls_context_t *result = NULL;
527 X509 *cert = NULL, *idcert = NULL;
528 char *nickname = NULL, *nn2 = NULL;
530 tor_tls_init();
531 nickname = crypto_random_hostname(8, 20, "www.", ".net");
532 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
534 /* Generate short-term RSA key. */
535 if (!(rsa = crypto_new_pk_env()))
536 goto error;
537 if (crypto_pk_generate_key(rsa)<0)
538 goto error;
539 /* Create certificate signed by identity key. */
540 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
541 key_lifetime);
542 /* Create self-signed certificate for identity key. */
543 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
544 IDENTITY_CERT_LIFETIME);
545 if (!cert || !idcert) {
546 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
547 goto error;
550 result = tor_malloc_zero(sizeof(tor_tls_context_t));
551 result->refcnt = 1;
552 result->my_cert = X509_dup(cert);
553 result->my_id_cert = X509_dup(idcert);
554 result->key = crypto_pk_dup_key(rsa);
556 #ifdef EVERYONE_HAS_AES
557 /* Tell OpenSSL to only use TLS1 */
558 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
559 goto error;
560 #else
561 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
562 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
563 goto error;
564 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
565 #endif
566 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
567 #ifdef SSL_MODE_RELEASE_BUFFERS
568 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
569 #endif
570 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
571 goto error;
572 X509_free(cert); /* We just added a reference to cert. */
573 cert=NULL;
574 if (idcert) {
575 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
576 tor_assert(s);
577 X509_STORE_add_cert(s, idcert);
578 X509_free(idcert); /* The context now owns the reference to idcert */
579 idcert = NULL;
581 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
582 tor_assert(rsa);
583 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
584 goto error;
585 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
586 goto error;
587 EVP_PKEY_free(pkey);
588 pkey = NULL;
589 if (!SSL_CTX_check_private_key(result->ctx))
590 goto error;
591 dh = crypto_dh_new();
592 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
593 crypto_dh_free(dh);
594 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
595 always_accept_verify_cb);
596 /* let us realloc bufs that we're writing from */
597 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
598 /* Free the old context if one exists. */
599 if (global_tls_context) {
600 /* This is safe even if there are open connections: OpenSSL does
601 * reference counting with SSL and SSL_CTX objects. */
602 tor_tls_context_decref(global_tls_context);
604 global_tls_context = result;
605 if (rsa)
606 crypto_free_pk_env(rsa);
607 tor_free(nickname);
608 tor_free(nn2);
609 return 0;
611 error:
612 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
613 tor_free(nickname);
614 tor_free(nn2);
615 if (pkey)
616 EVP_PKEY_free(pkey);
617 if (rsa)
618 crypto_free_pk_env(rsa);
619 if (dh)
620 crypto_dh_free(dh);
621 if (result)
622 tor_tls_context_decref(result);
623 if (cert)
624 X509_free(cert);
625 if (idcert)
626 X509_free(idcert);
627 return -1;
630 #ifdef V2_HANDSHAKE_SERVER
631 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
632 * a list that indicates that the client knows how to do the v2 TLS connection
633 * handshake. */
634 static int
635 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
637 int i;
638 SSL_SESSION *session;
639 /* If we reached this point, we just got a client hello. See if there is
640 * a cipher list. */
641 if (!(session = SSL_get_session((SSL *)ssl))) {
642 log_warn(LD_NET, "No session on TLS?");
643 return 0;
645 if (!session->ciphers) {
646 log_warn(LD_NET, "No ciphers on session");
647 return 0;
649 /* Now we need to see if there are any ciphers whose presence means we're
650 * dealing with an updated Tor. */
651 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
652 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
653 const char *ciphername = SSL_CIPHER_get_name(cipher);
654 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
655 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
656 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
657 strcmp(ciphername, "(NONE)")) {
658 /* XXXX should be ld_debug */
659 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
660 // return 1;
661 goto dump_list;
664 return 0;
665 dump_list:
667 smartlist_t *elts = smartlist_create();
668 char *s;
669 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
670 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
671 const char *ciphername = SSL_CIPHER_get_name(cipher);
672 smartlist_add(elts, (char*)ciphername);
674 s = smartlist_join_strings(elts, ":", 0, NULL);
675 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
676 address, s);
677 tor_free(s);
678 smartlist_free(elts);
680 return 1;
683 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
684 * changes state. We use this:
685 * <ul><li>To alter the state of the handshake partway through, so we
686 * do not send or request extra certificates in v2 handshakes.</li>
687 * <li>To detect renegotiation</li></ul>
689 static void
690 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
692 tor_tls_t *tls;
693 (void) val;
694 if (type != SSL_CB_ACCEPT_LOOP)
695 return;
696 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
697 return;
699 tls = tor_tls_get_by_ssl(ssl);
700 if (tls) {
701 /* Check whether we're watching for renegotiates. If so, this is one! */
702 if (tls->negotiated_callback)
703 tls->got_renegotiate = 1;
704 } else {
705 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
708 /* Now check the cipher list. */
709 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
710 /*XXXX_TLS keep this from happening more than once! */
712 /* Yes, we're casting away the const from ssl. This is very naughty of us.
713 * Let's hope openssl doesn't notice! */
715 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
716 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
717 /* Don't send a hello request. */
718 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
720 if (tls) {
721 tls->wasV2Handshake = 1;
722 } else {
723 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
727 #endif
729 /** Create a new TLS object from a file descriptor, and a flag to
730 * determine whether it is functioning as a server.
732 tor_tls_t *
733 tor_tls_new(int sock, int isServer)
735 BIO *bio = NULL;
736 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
738 tor_assert(global_tls_context); /* make sure somebody made it first */
739 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
740 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
741 tor_free(result);
742 return NULL;
744 if (!SSL_set_cipher_list(result->ssl,
745 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
746 SSL_free(result->ssl);
747 tor_free(result);
748 return NULL;
750 result->socket = sock;
751 #ifdef USE_BSOCKETS
752 bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
753 #else
754 bio = BIO_new_socket(sock, BIO_NOCLOSE);
755 #endif
756 if (! bio) {
757 tls_log_errors(NULL, LOG_WARN, "opening BIO");
758 SSL_free(result->ssl);
759 tor_free(result);
760 return NULL;
762 HT_INSERT(tlsmap, &tlsmap_root, result);
763 SSL_set_bio(result->ssl, bio, bio);
764 tor_tls_context_incref(global_tls_context);
765 result->context = global_tls_context;
766 result->state = TOR_TLS_ST_HANDSHAKE;
767 result->isServer = isServer;
768 result->wantwrite_n = 0;
769 result->last_write_count = BIO_number_written(bio);
770 result->last_read_count = BIO_number_read(bio);
771 if (result->last_write_count || result->last_read_count) {
772 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
773 result->last_read_count, result->last_write_count);
775 #ifdef V2_HANDSHAKE_SERVER
776 if (isServer) {
777 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
779 #endif
780 /* Not expected to get called. */
781 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
782 return result;
785 /** Make future log messages about <b>tls</b> display the address
786 * <b>address</b>.
788 void
789 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
791 tor_assert(tls);
792 tor_free(tls->address);
793 tls->address = tor_strdup(address);
796 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
797 * next gets a client-side renegotiate in the middle of a read. Do not
798 * invoke this function untile <em>after</em> initial handshaking is done!
800 void
801 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
802 void (*cb)(tor_tls_t *, void *arg),
803 void *arg)
805 tls->negotiated_callback = cb;
806 tls->callback_arg = arg;
807 tls->got_renegotiate = 0;
808 #ifdef V2_HANDSHAKE_SERVER
809 if (cb) {
810 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
811 } else {
812 SSL_set_info_callback(tls->ssl, NULL);
814 #endif
817 /** Return whether this tls initiated the connect (client) or
818 * received it (server). */
820 tor_tls_is_server(tor_tls_t *tls)
822 tor_assert(tls);
823 return tls->isServer;
826 /** Release resources associated with a TLS object. Does not close the
827 * underlying file descriptor.
829 void
830 tor_tls_free(tor_tls_t *tls)
832 tor_tls_t *removed;
833 tor_assert(tls && tls->ssl);
834 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
835 if (!removed) {
836 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
838 SSL_free(tls->ssl);
839 tls->ssl = NULL;
840 tls->negotiated_callback = NULL;
841 if (tls->context)
842 tor_tls_context_decref(tls->context);
843 tor_free(tls->address);
844 tor_free(tls);
847 /** Underlying function for TLS reading. Reads up to <b>len</b>
848 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
849 * number of characters read. On failure, returns TOR_TLS_ERROR,
850 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
853 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
855 int r, err;
856 tor_assert(tls);
857 tor_assert(tls->ssl);
858 tor_assert(tls->state == TOR_TLS_ST_OPEN);
859 tor_assert(len<INT_MAX);
860 r = SSL_read(tls->ssl, cp, (int)len);
861 if (r > 0) {
862 #ifdef V2_HANDSHAKE_SERVER
863 if (tls->got_renegotiate) {
864 /* Renegotiation happened! */
865 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
866 if (tls->negotiated_callback)
867 tls->negotiated_callback(tls, tls->callback_arg);
868 tls->got_renegotiate = 0;
870 #endif
871 return r;
873 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
874 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
875 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
876 tls->state = TOR_TLS_ST_CLOSED;
877 return TOR_TLS_CLOSE;
878 } else {
879 tor_assert(err != TOR_TLS_DONE);
880 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
881 return err;
885 /** Underlying function for TLS writing. Write up to <b>n</b>
886 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
887 * number of characters written. On failure, returns TOR_TLS_ERROR,
888 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
891 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
893 int r, err;
894 tor_assert(tls);
895 tor_assert(tls->ssl);
896 tor_assert(tls->state == TOR_TLS_ST_OPEN);
897 tor_assert(n < INT_MAX);
898 if (n == 0)
899 return 0;
900 if (tls->wantwrite_n) {
901 /* if WANTWRITE last time, we must use the _same_ n as before */
902 tor_assert(n >= tls->wantwrite_n);
903 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
904 (int)n, (int)tls->wantwrite_n);
905 n = tls->wantwrite_n;
906 tls->wantwrite_n = 0;
908 r = SSL_write(tls->ssl, cp, (int)n);
909 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
910 if (err == TOR_TLS_DONE) {
911 return r;
913 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
914 tls->wantwrite_n = n;
916 return err;
919 /** Perform initial handshake on <b>tls</b>. When finished, returns
920 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
921 * or TOR_TLS_WANTWRITE.
924 tor_tls_handshake(tor_tls_t *tls)
926 int r;
927 tor_assert(tls);
928 tor_assert(tls->ssl);
929 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
930 check_no_tls_errors();
931 if (tls->isServer) {
932 r = SSL_accept(tls->ssl);
933 } else {
934 r = SSL_connect(tls->ssl);
936 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
937 if (ERR_peek_error() != 0) {
938 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
939 "handshaking");
940 return TOR_TLS_ERROR_MISC;
942 if (r == TOR_TLS_DONE) {
943 tls->state = TOR_TLS_ST_OPEN;
944 if (tls->isServer) {
945 SSL_set_info_callback(tls->ssl, NULL);
946 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
947 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
948 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
949 #ifdef V2_HANDSHAKE_SERVER
950 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
951 /* This check is redundant, but back when we did it in the callback,
952 * we might have not been able to look up the tor_tls_t if the code
953 * was buggy. Fixing that. */
954 if (!tls->wasV2Handshake) {
955 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
956 " get set. Fixing that.");
958 tls->wasV2Handshake = 1;
959 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
960 "for renegotiation.");
961 } else {
962 tls->wasV2Handshake = 0;
964 #endif
965 } else {
966 #ifdef V2_HANDSHAKE_CLIENT
967 /* If we got no ID cert, we're a v2 handshake. */
968 X509 *cert = SSL_get_peer_certificate(tls->ssl);
969 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
970 int n_certs = sk_X509_num(chain);
971 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
972 tls->wasV2Handshake = 0;
973 else {
974 log_debug(LD_NET, "Server sent back a single certificate; looks like "
975 "a v2 handshake on %p.", tls);
976 tls->wasV2Handshake = 1;
978 if (cert)
979 X509_free(cert);
980 #endif
981 SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
984 return r;
987 /** Client only: Renegotiate a TLS session. When finished, returns
988 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
989 * TOR_TLS_WANTWRITE.
992 tor_tls_renegotiate(tor_tls_t *tls)
994 int r;
995 tor_assert(tls);
996 /* We could do server-initiated renegotiation too, but that would be tricky.
997 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
998 tor_assert(!tls->isServer);
999 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1000 int r = SSL_renegotiate(tls->ssl);
1001 if (r <= 0) {
1002 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1004 tls->state = TOR_TLS_ST_RENEGOTIATE;
1006 r = SSL_do_handshake(tls->ssl);
1007 if (r == 1) {
1008 tls->state = TOR_TLS_ST_OPEN;
1009 return TOR_TLS_DONE;
1010 } else
1011 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1014 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1015 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1016 * or TOR_TLS_WANTWRITE.
1019 tor_tls_shutdown(tor_tls_t *tls)
1021 int r, err;
1022 char buf[128];
1023 tor_assert(tls);
1024 tor_assert(tls->ssl);
1026 while (1) {
1027 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1028 /* If we've already called shutdown once to send a close message,
1029 * we read until the other side has closed too.
1031 do {
1032 r = SSL_read(tls->ssl, buf, 128);
1033 } while (r>0);
1034 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1035 LOG_INFO);
1036 if (err == _TOR_TLS_ZERORETURN) {
1037 tls->state = TOR_TLS_ST_GOTCLOSE;
1038 /* fall through... */
1039 } else {
1040 return err;
1044 r = SSL_shutdown(tls->ssl);
1045 if (r == 1) {
1046 /* If shutdown returns 1, the connection is entirely closed. */
1047 tls->state = TOR_TLS_ST_CLOSED;
1048 return TOR_TLS_DONE;
1050 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1051 LOG_INFO);
1052 if (err == _TOR_TLS_SYSCALL) {
1053 /* The underlying TCP connection closed while we were shutting down. */
1054 tls->state = TOR_TLS_ST_CLOSED;
1055 return TOR_TLS_DONE;
1056 } else if (err == _TOR_TLS_ZERORETURN) {
1057 /* The TLS connection says that it sent a shutdown record, but
1058 * isn't done shutting down yet. Make sure that this hasn't
1059 * happened before, then go back to the start of the function
1060 * and try to read.
1062 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1063 tls->state == TOR_TLS_ST_SENTCLOSE) {
1064 log(LOG_WARN, LD_NET,
1065 "TLS returned \"half-closed\" value while already half-closed");
1066 return TOR_TLS_ERROR_MISC;
1068 tls->state = TOR_TLS_ST_SENTCLOSE;
1069 /* fall through ... */
1070 } else {
1071 return err;
1073 } /* end loop */
1076 /** Return true iff this TLS connection is authenticated.
1079 tor_tls_peer_has_cert(tor_tls_t *tls)
1081 X509 *cert;
1082 cert = SSL_get_peer_certificate(tls->ssl);
1083 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1084 if (!cert)
1085 return 0;
1086 X509_free(cert);
1087 return 1;
1090 /** Warn that a certificate lifetime extends through a certain range. */
1091 static void
1092 log_cert_lifetime(X509 *cert, const char *problem)
1094 BIO *bio = NULL;
1095 BUF_MEM *buf;
1096 char *s1=NULL, *s2=NULL;
1097 char mytime[33];
1098 time_t now = time(NULL);
1099 struct tm tm;
1101 if (problem)
1102 log_warn(LD_GENERAL,
1103 "Certificate %s: is your system clock set incorrectly?",
1104 problem);
1106 if (!(bio = BIO_new(BIO_s_mem()))) {
1107 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1109 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1110 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1111 goto end;
1113 BIO_get_mem_ptr(bio, &buf);
1114 s1 = tor_strndup(buf->data, buf->length);
1116 (void)BIO_reset(bio);
1117 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1118 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1119 goto end;
1121 BIO_get_mem_ptr(bio, &buf);
1122 s2 = tor_strndup(buf->data, buf->length);
1124 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1126 log_warn(LD_GENERAL,
1127 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1128 s1,s2,mytime);
1130 end:
1131 /* Not expected to get invoked */
1132 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1133 if (bio)
1134 BIO_free(bio);
1135 if (s1)
1136 tor_free(s1);
1137 if (s2)
1138 tor_free(s2);
1141 /** Helper function: try to extract a link certificate and an identity
1142 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1143 * *<b>id_cert_out</b> respectively. Log all messages at level
1144 * <b>severity</b>.
1146 * Note that a reference is added to cert_out, so it needs to be
1147 * freed. id_cert_out doesn't. */
1148 static void
1149 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1150 X509 **cert_out, X509 **id_cert_out)
1152 X509 *cert = NULL, *id_cert = NULL;
1153 STACK_OF(X509) *chain = NULL;
1154 int num_in_chain, i;
1155 *cert_out = *id_cert_out = NULL;
1157 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1158 return;
1159 *cert_out = cert;
1160 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1161 return;
1162 num_in_chain = sk_X509_num(chain);
1163 /* 1 means we're receiving (server-side), and it's just the id_cert.
1164 * 2 means we're connecting (client-side), and it's both the link
1165 * cert and the id_cert.
1167 if (num_in_chain < 1) {
1168 log_fn(severity,LD_PROTOCOL,
1169 "Unexpected number of certificates in chain (%d)",
1170 num_in_chain);
1171 return;
1173 for (i=0; i<num_in_chain; ++i) {
1174 id_cert = sk_X509_value(chain, i);
1175 if (X509_cmp(id_cert, cert) != 0)
1176 break;
1178 *id_cert_out = id_cert;
1181 /** If the provided tls connection is authenticated and has a
1182 * certificate chain that is currently valid and signed, then set
1183 * *<b>identity_key</b> to the identity certificate's key and return
1184 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1187 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1189 X509 *cert = NULL, *id_cert = NULL;
1190 EVP_PKEY *id_pkey = NULL;
1191 RSA *rsa;
1192 int r = -1;
1194 *identity_key = NULL;
1196 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1197 if (!cert)
1198 goto done;
1199 if (!id_cert) {
1200 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1201 goto done;
1203 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1204 X509_verify(cert, id_pkey) <= 0) {
1205 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1206 tls_log_errors(tls, severity,"verifying certificate");
1207 goto done;
1210 rsa = EVP_PKEY_get1_RSA(id_pkey);
1211 if (!rsa)
1212 goto done;
1213 *identity_key = _crypto_new_pk_env_rsa(rsa);
1215 r = 0;
1217 done:
1218 if (cert)
1219 X509_free(cert);
1220 if (id_pkey)
1221 EVP_PKEY_free(id_pkey);
1223 /* This should never get invoked, but let's make sure in case OpenSSL
1224 * acts unexpectedly. */
1225 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1227 return r;
1230 /** Check whether the certificate set on the connection <b>tls</b> is
1231 * expired or not-yet-valid, give or take <b>tolerance</b>
1232 * seconds. Return 0 for valid, -1 for failure.
1234 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1237 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1239 time_t now, t;
1240 X509 *cert;
1241 int r = -1;
1243 now = time(NULL);
1245 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1246 goto done;
1248 t = now + tolerance;
1249 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1250 log_cert_lifetime(cert, "not yet valid");
1251 goto done;
1253 t = now - tolerance;
1254 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1255 log_cert_lifetime(cert, "already expired");
1256 goto done;
1259 r = 0;
1260 done:
1261 if (cert)
1262 X509_free(cert);
1263 /* Not expected to get invoked */
1264 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1266 return r;
1269 /** Return the number of bytes available for reading from <b>tls</b>.
1272 tor_tls_get_pending_bytes(tor_tls_t *tls)
1274 tor_assert(tls);
1275 return SSL_pending(tls->ssl);
1278 /** If <b>tls</b> requires that the next write be of a particular size,
1279 * return that size. Otherwise, return 0. */
1280 size_t
1281 tor_tls_get_forced_write_size(tor_tls_t *tls)
1283 return tls->wantwrite_n;
1286 /** Sets n_read and n_written to the number of bytes read and written,
1287 * respectively, on the raw socket used by <b>tls</b> since the last time this
1288 * function was called on <b>tls</b>. */
1289 void
1290 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1292 BIO *wbio, *tmpbio;
1293 unsigned long r, w;
1294 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1295 /* We want the number of bytes actually for real written. Unfortunately,
1296 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1297 * which makes the answer turn out wrong. Let's cope with that. Note
1298 * that this approach will fail if we ever replace tls->ssl's BIOs with
1299 * buffering bios for reasons of our own. As an alternative, we could
1300 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1301 * that would be tempting fate. */
1302 wbio = SSL_get_wbio(tls->ssl);
1303 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1304 wbio = tmpbio;
1305 w = BIO_number_written(wbio);
1307 /* We are ok with letting these unsigned ints go "negative" here:
1308 * If we wrapped around, this should still give us the right answer, unless
1309 * we wrapped around by more than ULONG_MAX since the last time we called
1310 * this function.
1312 *n_read = (size_t)(r - tls->last_read_count);
1313 *n_written = (size_t)(w - tls->last_write_count);
1314 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1315 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1316 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1317 r, tls->last_read_count, w, tls->last_write_count);
1319 tls->last_read_count = r;
1320 tls->last_write_count = w;
1323 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1324 * errors, log an error message. */
1325 void
1326 _check_no_tls_errors(const char *fname, int line)
1328 if (ERR_peek_error() == 0)
1329 return;
1330 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1331 tor_fix_source_file(fname), line);
1332 tls_log_errors(NULL, LOG_WARN, NULL);
1335 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1336 * TLS handshake. Output is undefined if the handshake isn't finished. */
1338 tor_tls_used_v1_handshake(tor_tls_t *tls)
1340 if (tls->isServer) {
1341 #ifdef V2_HANDSHAKE_SERVER
1342 return ! tls->wasV2Handshake;
1343 #endif
1344 } else {
1345 #ifdef V2_HANDSHAKE_CLIENT
1346 return ! tls->wasV2Handshake;
1347 #endif
1349 return 1;
1352 /** DOCDOC */
1353 void
1354 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1355 int *rbuf_capacity, int *rbuf_bytes,
1356 int *wbuf_capacity, int *wbuf_bytes)
1358 if (tls->ssl->s3->rbuf.buf)
1359 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1360 else
1361 *rbuf_capacity = 0;
1362 if (tls->ssl->s3->wbuf.buf)
1363 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1364 else
1365 *wbuf_capacity = 0;
1366 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1367 *wbuf_bytes = tls->ssl->s3->wbuf.left;