Implement queue with O(1) operations, and correct some math.
[tor/rransom.git] / src / common / tortls.c
bloba518e83d203608af67af004b4f9ff83578752b7d
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, 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 /** Structure holding the TLS state for a single connection. */
57 typedef struct tor_tls_context_t {
58 int refcnt;
59 SSL_CTX *ctx;
60 X509 *my_cert;
61 X509 *my_id_cert;
62 crypto_pk_env_t *key;
63 } tor_tls_context_t;
65 /** Holds a SSL object and its associated data. Members are only
66 * accessed from within tortls.c.
68 struct tor_tls_t {
69 HT_ENTRY(tor_tls_t) node;
70 tor_tls_context_t *context; /** A link to the context object for this tls. */
71 SSL *ssl; /**< An OpenSSL SSL object. */
72 int socket; /**< The underlying file descriptor for this TLS connection. */
73 char *address; /**< An address to log when describing this connection. */
74 enum {
75 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
76 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
77 } state : 3; /**< The current SSL state, depending on which operations have
78 * completed successfully. */
79 unsigned int isServer:1; /**< True iff this is a server-side connection */
80 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
81 * this connection used the updated version
82 * of the connection protocol (client sends
83 * different cipher list, server sends only
84 * one certificate). */
85 /** True iff we should call negotiated_callback when we're done reading. */
86 unsigned int got_renegotiate:1;
87 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
88 * time. */
89 /** Last values retrieved from BIO_number_read()/write(); see
90 * tor_tls_get_n_raw_bytes() for usage.
92 unsigned long last_write_count;
93 unsigned long last_read_count;
94 /** If set, a callback to invoke whenever the client tries to renegotiate
95 * the handshake. */
96 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
97 /** Argument to pass to negotiated_callback. */
98 void *callback_arg;
101 #ifdef V2_HANDSHAKE_CLIENT
102 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
103 * in client mode into advertising the ciphers we want. See
104 * rectify_client_ciphers() for details. */
105 static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
106 /** A stack of SSL_CIPHER objects, some real, some fake.
107 * See rectify_client_ciphers() for details. */
108 static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
109 #endif
111 /** Helper: compare tor_tls_t objects by its SSL. */
112 static INLINE int
113 tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
115 return a->ssl == b->ssl;
118 /** Helper: return a hash value for a tor_tls_t by its SSL. */
119 static INLINE unsigned int
120 tor_tls_entry_hash(const tor_tls_t *a)
122 #if SIZEOF_INT == SIZEOF_VOID_P
123 return ((unsigned int)(uintptr_t)a->ssl);
124 #else
125 return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
126 #endif
129 /** Map from SSL* pointers to tor_tls_t objects using those pointers.
131 static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
133 HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
134 tor_tls_entries_eq)
135 HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
136 tor_tls_entries_eq, 0.6, malloc, realloc, free)
138 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
139 * pointer. */
140 static INLINE tor_tls_t *
141 tor_tls_get_by_ssl(const SSL *ssl)
143 tor_tls_t search, *result;
144 memset(&search, 0, sizeof(search));
145 search.ssl = (SSL*)ssl;
146 result = HT_FIND(tlsmap, &tlsmap_root, &search);
147 return result;
150 static void tor_tls_context_decref(tor_tls_context_t *ctx);
151 static void tor_tls_context_incref(tor_tls_context_t *ctx);
152 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
153 crypto_pk_env_t *rsa_sign,
154 const char *cname,
155 const char *cname_sign,
156 unsigned int lifetime);
158 /** Global tls context. We keep it here because nobody else needs to
159 * touch it. */
160 static tor_tls_context_t *global_tls_context = NULL;
161 /** True iff tor_tls_init() has been called. */
162 static int tls_library_is_initialized = 0;
164 /* Module-internal error codes. */
165 #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
166 #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
168 /** Log all pending tls errors at level <b>severity</b>. Use
169 * <b>doing</b> to describe our current activities.
171 static void
172 tls_log_errors(tor_tls_t *tls, int severity, const char *doing)
174 unsigned long err;
175 const char *msg, *lib, *func, *addr;
176 addr = tls ? tls->address : NULL;
177 while ((err = ERR_get_error()) != 0) {
178 msg = (const char*)ERR_reason_error_string(err);
179 lib = (const char*)ERR_lib_error_string(err);
180 func = (const char*)ERR_func_error_string(err);
181 if (!msg) msg = "(null)";
182 if (doing) {
183 log(severity, LD_NET, "TLS error while %s%s%s: %s (in %s:%s)",
184 doing, addr?" with ":"", addr?addr:"",
185 msg, lib, func);
186 } else {
187 log(severity, LD_NET, "TLS error%s%s: %s (in %s:%s)",
188 addr?" with ":"", addr?addr:"",
189 msg, lib, func);
194 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
195 * code. */
196 static int
197 tor_errno_to_tls_error(int e)
199 #if defined(MS_WINDOWS)
200 switch (e) {
201 case WSAECONNRESET: // most common
202 return TOR_TLS_ERROR_CONNRESET;
203 case WSAETIMEDOUT:
204 return TOR_TLS_ERROR_TIMEOUT;
205 case WSAENETUNREACH:
206 case WSAEHOSTUNREACH:
207 return TOR_TLS_ERROR_NO_ROUTE;
208 case WSAECONNREFUSED:
209 return TOR_TLS_ERROR_CONNREFUSED; // least common
210 default:
211 return TOR_TLS_ERROR_MISC;
213 #else
214 switch (e) {
215 case ECONNRESET: // most common
216 return TOR_TLS_ERROR_CONNRESET;
217 case ETIMEDOUT:
218 return TOR_TLS_ERROR_TIMEOUT;
219 case EHOSTUNREACH:
220 case ENETUNREACH:
221 return TOR_TLS_ERROR_NO_ROUTE;
222 case ECONNREFUSED:
223 return TOR_TLS_ERROR_CONNREFUSED; // least common
224 default:
225 return TOR_TLS_ERROR_MISC;
227 #endif
230 /** Given a TOR_TLS_* error code, return a string equivalent. */
231 const char *
232 tor_tls_err_to_string(int err)
234 if (err >= 0)
235 return "[Not an error.]";
236 switch (err) {
237 case TOR_TLS_ERROR_MISC: return "misc error";
238 case TOR_TLS_ERROR_IO: return "unexpected close";
239 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
240 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
241 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
242 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
243 case TOR_TLS_CLOSE: return "closed";
244 case TOR_TLS_WANTREAD: return "want to read";
245 case TOR_TLS_WANTWRITE: return "want to write";
246 default: return "(unknown error code)";
250 #define CATCH_SYSCALL 1
251 #define CATCH_ZERO 2
253 /** Given a TLS object and the result of an SSL_* call, use
254 * SSL_get_error to determine whether an error has occurred, and if so
255 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
256 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
257 * reporting syscall errors. If extra&CATCH_ZERO is true, return
258 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
260 * If an error has occurred, log it at level <b>severity</b> and describe the
261 * current action as <b>doing</b>.
263 static int
264 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
265 const char *doing, int severity)
267 int err = SSL_get_error(tls->ssl, r);
268 int tor_error = TOR_TLS_ERROR_MISC;
269 switch (err) {
270 case SSL_ERROR_NONE:
271 return TOR_TLS_DONE;
272 case SSL_ERROR_WANT_READ:
273 return TOR_TLS_WANTREAD;
274 case SSL_ERROR_WANT_WRITE:
275 return TOR_TLS_WANTWRITE;
276 case SSL_ERROR_SYSCALL:
277 if (extra&CATCH_SYSCALL)
278 return _TOR_TLS_SYSCALL;
279 if (r == 0) {
280 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
281 tor_error = TOR_TLS_ERROR_IO;
282 } else {
283 int e = tor_socket_errno(tls->socket);
284 log(severity, LD_NET,
285 "TLS error: <syscall error while %s> (errno=%d: %s)",
286 doing, e, tor_socket_strerror(e));
287 tor_error = tor_errno_to_tls_error(e);
289 tls_log_errors(tls, severity, doing);
290 return tor_error;
291 case SSL_ERROR_ZERO_RETURN:
292 if (extra&CATCH_ZERO)
293 return _TOR_TLS_ZERORETURN;
294 log(severity, LD_NET, "TLS connection closed while %s", doing);
295 tls_log_errors(tls, severity, doing);
296 return TOR_TLS_CLOSE;
297 default:
298 tls_log_errors(tls, severity, doing);
299 return TOR_TLS_ERROR_MISC;
303 /** Initialize OpenSSL, unless it has already been initialized.
305 static void
306 tor_tls_init(void)
308 if (!tls_library_is_initialized) {
309 SSL_library_init();
310 SSL_load_error_strings();
311 tls_library_is_initialized = 1;
315 /** Free all global TLS structures. */
316 void
317 tor_tls_free_all(void)
319 if (global_tls_context) {
320 tor_tls_context_decref(global_tls_context);
321 global_tls_context = NULL;
323 if (!HT_EMPTY(&tlsmap_root)) {
324 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
326 HT_CLEAR(tlsmap, &tlsmap_root);
327 #ifdef V2_HANDSHAKE_CLIENT
328 if (CLIENT_CIPHER_DUMMIES)
329 tor_free(CLIENT_CIPHER_DUMMIES);
330 if (CLIENT_CIPHER_STACK)
331 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
332 #endif
335 /** We need to give OpenSSL a callback to verify certificates. This is
336 * it: We always accept peer certs and complete the handshake. We
337 * don't validate them until later.
339 static int
340 always_accept_verify_cb(int preverify_ok,
341 X509_STORE_CTX *x509_ctx)
343 (void) preverify_ok;
344 (void) x509_ctx;
345 return 1;
348 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
349 static X509_NAME *
350 tor_x509_name_new(const char *cname)
352 int nid;
353 X509_NAME *name;
354 if (!(name = X509_NAME_new()))
355 return NULL;
356 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
357 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
358 (unsigned char*)cname, -1, -1, 0)))
359 goto error;
360 return name;
361 error:
362 X509_NAME_free(name);
363 return NULL;
366 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
367 * signed by the private key <b>rsa_sign</b>. The commonName of the
368 * certificate will be <b>cname</b>; the commonName of the issuer will be
369 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
370 * starting from now. Return a certificate on success, NULL on
371 * failure.
373 static X509 *
374 tor_tls_create_certificate(crypto_pk_env_t *rsa,
375 crypto_pk_env_t *rsa_sign,
376 const char *cname,
377 const char *cname_sign,
378 unsigned int cert_lifetime)
380 time_t start_time, end_time;
381 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
382 X509 *x509 = NULL;
383 X509_NAME *name = NULL, *name_issuer=NULL;
385 tor_tls_init();
387 start_time = time(NULL);
389 tor_assert(rsa);
390 tor_assert(cname);
391 tor_assert(rsa_sign);
392 tor_assert(cname_sign);
393 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
394 goto error;
395 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
396 goto error;
397 if (!(x509 = X509_new()))
398 goto error;
399 if (!(X509_set_version(x509, 2)))
400 goto error;
401 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
402 goto error;
404 if (!(name = tor_x509_name_new(cname)))
405 goto error;
406 if (!(X509_set_subject_name(x509, name)))
407 goto error;
408 if (!(name_issuer = tor_x509_name_new(cname_sign)))
409 goto error;
410 if (!(X509_set_issuer_name(x509, name_issuer)))
411 goto error;
413 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
414 goto error;
415 end_time = start_time + cert_lifetime;
416 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
417 goto error;
418 if (!X509_set_pubkey(x509, pkey))
419 goto error;
420 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
421 goto error;
423 goto done;
424 error:
425 if (x509) {
426 X509_free(x509);
427 x509 = NULL;
429 done:
430 tls_log_errors(NULL, LOG_WARN, "generating certificate");
431 if (sign_pkey)
432 EVP_PKEY_free(sign_pkey);
433 if (pkey)
434 EVP_PKEY_free(pkey);
435 if (name)
436 X509_NAME_free(name);
437 if (name_issuer)
438 X509_NAME_free(name_issuer);
439 return x509;
442 /** List of ciphers that servers should select from.*/
443 #define SERVER_CIPHER_LIST \
444 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
445 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
446 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
447 /* Note: for setting up your own private testing network with link crypto
448 * disabled, set the cipher lists to your cipher list to
449 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
450 * with any of the "real" Tors, though. */
452 #ifdef V2_HANDSHAKE_CLIENT
453 #define CIPHER(id, name) name ":"
454 #define XCIPHER(id, name)
455 /** List of ciphers that clients should advertise, omitting items that
456 * our OpenSSL doesn't know about. */
457 static const char CLIENT_CIPHER_LIST[] =
458 #include "./ciphers.inc"
460 #undef CIPHER
461 #undef XCIPHER
463 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
464 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
465 /** A list of all the ciphers that clients should advertise, including items
466 * that OpenSSL might not know about. */
467 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
468 #define CIPHER(id, name) { id, name },
469 #define XCIPHER(id, name) { id, #name },
470 #include "./ciphers.inc"
471 #undef CIPHER
472 #undef XCIPHER
475 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
476 static const int N_CLIENT_CIPHERS =
477 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
478 #endif
480 #ifndef V2_HANDSHAKE_CLIENT
481 #undef CLIENT_CIPHER_LIST
482 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
483 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
484 #endif
486 /** Remove a reference to <b>ctx</b>, and free it if it has no more
487 * references. */
488 static void
489 tor_tls_context_decref(tor_tls_context_t *ctx)
491 tor_assert(ctx);
492 if (--ctx->refcnt == 0) {
493 SSL_CTX_free(ctx->ctx);
494 X509_free(ctx->my_cert);
495 X509_free(ctx->my_id_cert);
496 crypto_free_pk_env(ctx->key);
497 tor_free(ctx);
501 /** Increase the reference count of <b>ctx</b>. */
502 static void
503 tor_tls_context_incref(tor_tls_context_t *ctx)
505 ++ctx->refcnt;
508 /** Create a new TLS context for use with Tor TLS handshakes.
509 * <b>identity</b> should be set to the identity key used to sign the
510 * certificate, and <b>nickname</b> set to the nickname to use.
512 * You can call this function multiple times. Each time you call it,
513 * it generates new certificates; all new connections will use
514 * the new SSL context.
517 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
519 crypto_pk_env_t *rsa = NULL;
520 EVP_PKEY *pkey = NULL;
521 tor_tls_context_t *result = NULL;
522 X509 *cert = NULL, *idcert = NULL;
523 char *nickname = NULL, *nn2 = NULL;
525 tor_tls_init();
526 nickname = crypto_random_hostname(8, 20, "www.", ".net");
527 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
529 /* Generate short-term RSA key. */
530 if (!(rsa = crypto_new_pk_env()))
531 goto error;
532 if (crypto_pk_generate_key(rsa)<0)
533 goto error;
534 /* Create certificate signed by identity key. */
535 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
536 key_lifetime);
537 /* Create self-signed certificate for identity key. */
538 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
539 IDENTITY_CERT_LIFETIME);
540 if (!cert || !idcert) {
541 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
542 goto error;
545 result = tor_malloc_zero(sizeof(tor_tls_context_t));
546 result->refcnt = 1;
547 result->my_cert = X509_dup(cert);
548 result->my_id_cert = X509_dup(idcert);
549 result->key = crypto_pk_dup_key(rsa);
551 #ifdef EVERYONE_HAS_AES
552 /* Tell OpenSSL to only use TLS1 */
553 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
554 goto error;
555 #else
556 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
557 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
558 goto error;
559 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
560 #endif
561 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
563 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
564 SSL_CTX_set_options(result->ctx,
565 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
566 #endif
567 /* Don't actually allow compression; it uses ram and time, but the data
568 * we transmit is all encrypted anyway. */
569 if (result->ctx->comp_methods)
570 result->ctx->comp_methods = NULL;
571 #ifdef SSL_MODE_RELEASE_BUFFERS
572 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
573 #endif
574 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
575 goto error;
576 X509_free(cert); /* We just added a reference to cert. */
577 cert=NULL;
578 if (idcert) {
579 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
580 tor_assert(s);
581 X509_STORE_add_cert(s, idcert);
582 X509_free(idcert); /* The context now owns the reference to idcert */
583 idcert = NULL;
585 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
586 tor_assert(rsa);
587 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
588 goto error;
589 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
590 goto error;
591 EVP_PKEY_free(pkey);
592 pkey = NULL;
593 if (!SSL_CTX_check_private_key(result->ctx))
594 goto error;
596 crypto_dh_env_t *dh = crypto_dh_new();
597 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
598 crypto_dh_free(dh);
600 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
601 always_accept_verify_cb);
602 /* let us realloc bufs that we're writing from */
603 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
604 /* Free the old context if one exists. */
605 if (global_tls_context) {
606 /* This is safe even if there are open connections: OpenSSL does
607 * reference counting with SSL and SSL_CTX objects. */
608 tor_tls_context_decref(global_tls_context);
610 global_tls_context = result;
611 if (rsa)
612 crypto_free_pk_env(rsa);
613 tor_free(nickname);
614 tor_free(nn2);
615 return 0;
617 error:
618 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
619 tor_free(nickname);
620 tor_free(nn2);
621 if (pkey)
622 EVP_PKEY_free(pkey);
623 if (rsa)
624 crypto_free_pk_env(rsa);
625 if (result)
626 tor_tls_context_decref(result);
627 if (cert)
628 X509_free(cert);
629 if (idcert)
630 X509_free(idcert);
631 return -1;
634 #ifdef V2_HANDSHAKE_SERVER
635 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
636 * a list that indicates that the client knows how to do the v2 TLS connection
637 * handshake. */
638 static int
639 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
641 int i;
642 SSL_SESSION *session;
643 /* If we reached this point, we just got a client hello. See if there is
644 * a cipher list. */
645 if (!(session = SSL_get_session((SSL *)ssl))) {
646 log_warn(LD_NET, "No session on TLS?");
647 return 0;
649 if (!session->ciphers) {
650 log_warn(LD_NET, "No ciphers on session");
651 return 0;
653 /* Now we need to see if there are any ciphers whose presence means we're
654 * dealing with an updated Tor. */
655 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
656 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
657 const char *ciphername = SSL_CIPHER_get_name(cipher);
658 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
659 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
660 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
661 strcmp(ciphername, "(NONE)")) {
662 /* XXXX should be ld_debug */
663 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
664 // return 1;
665 goto dump_list;
668 return 0;
669 dump_list:
671 smartlist_t *elts = smartlist_create();
672 char *s;
673 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
674 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
675 const char *ciphername = SSL_CIPHER_get_name(cipher);
676 smartlist_add(elts, (char*)ciphername);
678 s = smartlist_join_strings(elts, ":", 0, NULL);
679 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
680 address, s);
681 tor_free(s);
682 smartlist_free(elts);
684 return 1;
687 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
688 * changes state. We use this:
689 * <ul><li>To alter the state of the handshake partway through, so we
690 * do not send or request extra certificates in v2 handshakes.</li>
691 * <li>To detect renegotiation</li></ul>
693 static void
694 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
696 tor_tls_t *tls;
697 (void) val;
698 if (type != SSL_CB_ACCEPT_LOOP)
699 return;
700 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
701 return;
703 tls = tor_tls_get_by_ssl(ssl);
704 if (tls) {
705 /* Check whether we're watching for renegotiates. If so, this is one! */
706 if (tls->negotiated_callback)
707 tls->got_renegotiate = 1;
708 } else {
709 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
712 /* Now check the cipher list. */
713 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
714 /*XXXX_TLS keep this from happening more than once! */
716 /* Yes, we're casting away the const from ssl. This is very naughty of us.
717 * Let's hope openssl doesn't notice! */
719 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
720 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
721 /* Don't send a hello request. */
722 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
724 if (tls) {
725 tls->wasV2Handshake = 1;
726 } else {
727 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
731 #endif
733 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
734 * a list designed to mimic a common web browser. Some of the ciphers in the
735 * list won't actually be implemented by OpenSSL: that's okay so long as the
736 * server doesn't select them, and the server won't select anything besides
737 * what's in SERVER_CIPHER_LIST.
739 * [If the server <b>does</b> select a bogus cipher, we won't crash or
740 * anything; we'll just fail later when we try to look up the cipher in
741 * ssl->cipher_list_by_id.]
743 static void
744 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
746 #ifdef V2_HANDSHAKE_CLIENT
747 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
748 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
749 * we want.*/
750 int i = 0, j = 0;
752 /* First, create a dummy SSL_CIPHER for every cipher. */
753 CLIENT_CIPHER_DUMMIES =
754 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
755 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
756 CLIENT_CIPHER_DUMMIES[i].valid = 1;
757 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
758 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
761 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
762 tor_assert(CLIENT_CIPHER_STACK);
764 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
765 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
766 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
767 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
770 /* Then copy as many ciphers as we can from the good list, inserting
771 * dummies as needed. */
772 j=0;
773 for (i = 0; i < N_CLIENT_CIPHERS; ) {
774 SSL_CIPHER *cipher = NULL;
775 if (j < sk_SSL_CIPHER_num(*ciphers))
776 cipher = sk_SSL_CIPHER_value(*ciphers, j);
777 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
778 log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
779 ++j;
780 } else if (cipher &&
781 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
782 log_debug(LD_NET, "Found cipher %s", cipher->name);
783 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
784 ++j;
785 ++i;
786 } else {
787 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
788 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
789 ++i;
794 sk_SSL_CIPHER_free(*ciphers);
795 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
796 tor_assert(*ciphers);
798 #else
799 (void)ciphers;
800 #endif
803 /** Create a new TLS object from a file descriptor, and a flag to
804 * determine whether it is functioning as a server.
806 tor_tls_t *
807 tor_tls_new(int sock, int isServer)
809 BIO *bio = NULL;
810 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
812 tor_assert(global_tls_context); /* make sure somebody made it first */
813 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
814 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
815 tor_free(result);
816 return NULL;
819 #ifdef SSL_set_tlsext_host_name
820 /* Browsers use the TLS hostname extension, so we should too. */
822 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
823 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
824 tor_free(fake_hostname);
826 #endif
828 if (!SSL_set_cipher_list(result->ssl,
829 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
830 tls_log_errors(NULL, LOG_WARN, "setting ciphers");
831 SSL_free(result->ssl);
832 tor_free(result);
833 return NULL;
835 if (!isServer)
836 rectify_client_ciphers(&result->ssl->cipher_list);
837 result->socket = sock;
838 bio = BIO_new_socket(sock, BIO_NOCLOSE);
839 if (! bio) {
840 tls_log_errors(NULL, LOG_WARN, "opening BIO");
841 SSL_free(result->ssl);
842 tor_free(result);
843 return NULL;
845 HT_INSERT(tlsmap, &tlsmap_root, result);
846 SSL_set_bio(result->ssl, bio, bio);
847 tor_tls_context_incref(global_tls_context);
848 result->context = global_tls_context;
849 result->state = TOR_TLS_ST_HANDSHAKE;
850 result->isServer = isServer;
851 result->wantwrite_n = 0;
852 result->last_write_count = BIO_number_written(bio);
853 result->last_read_count = BIO_number_read(bio);
854 if (result->last_write_count || result->last_read_count) {
855 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
856 result->last_read_count, result->last_write_count);
858 #ifdef V2_HANDSHAKE_SERVER
859 if (isServer) {
860 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
862 #endif
863 /* Not expected to get called. */
864 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
865 return result;
868 /** Make future log messages about <b>tls</b> display the address
869 * <b>address</b>.
871 void
872 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
874 tor_assert(tls);
875 tor_free(tls->address);
876 tls->address = tor_strdup(address);
879 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
880 * next gets a client-side renegotiate in the middle of a read. Do not
881 * invoke this function until <em>after</em> initial handshaking is done!
883 void
884 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
885 void (*cb)(tor_tls_t *, void *arg),
886 void *arg)
888 tls->negotiated_callback = cb;
889 tls->callback_arg = arg;
890 tls->got_renegotiate = 0;
891 #ifdef V2_HANDSHAKE_SERVER
892 if (cb) {
893 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
894 } else {
895 SSL_set_info_callback(tls->ssl, NULL);
897 #endif
900 /** Return whether this tls initiated the connect (client) or
901 * received it (server). */
903 tor_tls_is_server(tor_tls_t *tls)
905 tor_assert(tls);
906 return tls->isServer;
909 /** Release resources associated with a TLS object. Does not close the
910 * underlying file descriptor.
912 void
913 tor_tls_free(tor_tls_t *tls)
915 tor_tls_t *removed;
916 tor_assert(tls && tls->ssl);
917 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
918 if (!removed) {
919 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
921 SSL_free(tls->ssl);
922 tls->ssl = NULL;
923 tls->negotiated_callback = NULL;
924 if (tls->context)
925 tor_tls_context_decref(tls->context);
926 tor_free(tls->address);
927 tor_free(tls);
930 /** Underlying function for TLS reading. Reads up to <b>len</b>
931 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
932 * number of characters read. On failure, returns TOR_TLS_ERROR,
933 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
936 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
938 int r, err;
939 tor_assert(tls);
940 tor_assert(tls->ssl);
941 tor_assert(tls->state == TOR_TLS_ST_OPEN);
942 tor_assert(len<INT_MAX);
943 r = SSL_read(tls->ssl, cp, (int)len);
944 if (r > 0) {
945 #ifdef V2_HANDSHAKE_SERVER
946 if (tls->got_renegotiate) {
947 /* Renegotiation happened! */
948 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
949 if (tls->negotiated_callback)
950 tls->negotiated_callback(tls, tls->callback_arg);
951 tls->got_renegotiate = 0;
953 #endif
954 return r;
956 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
957 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
958 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
959 tls->state = TOR_TLS_ST_CLOSED;
960 return TOR_TLS_CLOSE;
961 } else {
962 tor_assert(err != TOR_TLS_DONE);
963 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
964 return err;
968 /** Underlying function for TLS writing. Write up to <b>n</b>
969 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
970 * number of characters written. On failure, returns TOR_TLS_ERROR,
971 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
974 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
976 int r, err;
977 tor_assert(tls);
978 tor_assert(tls->ssl);
979 tor_assert(tls->state == TOR_TLS_ST_OPEN);
980 tor_assert(n < INT_MAX);
981 if (n == 0)
982 return 0;
983 if (tls->wantwrite_n) {
984 /* if WANTWRITE last time, we must use the _same_ n as before */
985 tor_assert(n >= tls->wantwrite_n);
986 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
987 (int)n, (int)tls->wantwrite_n);
988 n = tls->wantwrite_n;
989 tls->wantwrite_n = 0;
991 r = SSL_write(tls->ssl, cp, (int)n);
992 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
993 if (err == TOR_TLS_DONE) {
994 return r;
996 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
997 tls->wantwrite_n = n;
999 return err;
1002 /** Perform initial handshake on <b>tls</b>. When finished, returns
1003 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1004 * or TOR_TLS_WANTWRITE.
1007 tor_tls_handshake(tor_tls_t *tls)
1009 int r;
1010 tor_assert(tls);
1011 tor_assert(tls->ssl);
1012 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1013 check_no_tls_errors();
1014 if (tls->isServer) {
1015 r = SSL_accept(tls->ssl);
1016 } else {
1017 r = SSL_connect(tls->ssl);
1019 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
1020 if (ERR_peek_error() != 0) {
1021 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
1022 "handshaking");
1023 return TOR_TLS_ERROR_MISC;
1025 if (r == TOR_TLS_DONE) {
1026 tls->state = TOR_TLS_ST_OPEN;
1027 if (tls->isServer) {
1028 SSL_set_info_callback(tls->ssl, NULL);
1029 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1030 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1031 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
1032 #ifdef V2_HANDSHAKE_SERVER
1033 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
1034 /* This check is redundant, but back when we did it in the callback,
1035 * we might have not been able to look up the tor_tls_t if the code
1036 * was buggy. Fixing that. */
1037 if (!tls->wasV2Handshake) {
1038 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1039 " get set. Fixing that.");
1041 tls->wasV2Handshake = 1;
1042 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
1043 "for renegotiation.");
1044 } else {
1045 tls->wasV2Handshake = 0;
1047 #endif
1048 } else {
1049 #ifdef V2_HANDSHAKE_CLIENT
1050 /* If we got no ID cert, we're a v2 handshake. */
1051 X509 *cert = SSL_get_peer_certificate(tls->ssl);
1052 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
1053 int n_certs = sk_X509_num(chain);
1054 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
1055 tls->wasV2Handshake = 0;
1056 else {
1057 log_debug(LD_NET, "Server sent back a single certificate; looks like "
1058 "a v2 handshake on %p.", tls);
1059 tls->wasV2Handshake = 1;
1061 if (cert)
1062 X509_free(cert);
1063 #endif
1064 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1065 tls_log_errors(NULL, LOG_WARN, "re-setting ciphers");
1066 r = TOR_TLS_ERROR_MISC;
1070 return r;
1073 /** Client only: Renegotiate a TLS session. When finished, returns
1074 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1075 * TOR_TLS_WANTWRITE.
1078 tor_tls_renegotiate(tor_tls_t *tls)
1080 int r;
1081 tor_assert(tls);
1082 /* We could do server-initiated renegotiation too, but that would be tricky.
1083 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1084 tor_assert(!tls->isServer);
1085 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1086 int r = SSL_renegotiate(tls->ssl);
1087 if (r <= 0) {
1088 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1090 tls->state = TOR_TLS_ST_RENEGOTIATE;
1092 r = SSL_do_handshake(tls->ssl);
1093 if (r == 1) {
1094 tls->state = TOR_TLS_ST_OPEN;
1095 return TOR_TLS_DONE;
1096 } else
1097 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1100 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1101 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1102 * or TOR_TLS_WANTWRITE.
1105 tor_tls_shutdown(tor_tls_t *tls)
1107 int r, err;
1108 char buf[128];
1109 tor_assert(tls);
1110 tor_assert(tls->ssl);
1112 while (1) {
1113 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1114 /* If we've already called shutdown once to send a close message,
1115 * we read until the other side has closed too.
1117 do {
1118 r = SSL_read(tls->ssl, buf, 128);
1119 } while (r>0);
1120 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1121 LOG_INFO);
1122 if (err == _TOR_TLS_ZERORETURN) {
1123 tls->state = TOR_TLS_ST_GOTCLOSE;
1124 /* fall through... */
1125 } else {
1126 return err;
1130 r = SSL_shutdown(tls->ssl);
1131 if (r == 1) {
1132 /* If shutdown returns 1, the connection is entirely closed. */
1133 tls->state = TOR_TLS_ST_CLOSED;
1134 return TOR_TLS_DONE;
1136 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1137 LOG_INFO);
1138 if (err == _TOR_TLS_SYSCALL) {
1139 /* The underlying TCP connection closed while we were shutting down. */
1140 tls->state = TOR_TLS_ST_CLOSED;
1141 return TOR_TLS_DONE;
1142 } else if (err == _TOR_TLS_ZERORETURN) {
1143 /* The TLS connection says that it sent a shutdown record, but
1144 * isn't done shutting down yet. Make sure that this hasn't
1145 * happened before, then go back to the start of the function
1146 * and try to read.
1148 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1149 tls->state == TOR_TLS_ST_SENTCLOSE) {
1150 log(LOG_WARN, LD_NET,
1151 "TLS returned \"half-closed\" value while already half-closed");
1152 return TOR_TLS_ERROR_MISC;
1154 tls->state = TOR_TLS_ST_SENTCLOSE;
1155 /* fall through ... */
1156 } else {
1157 return err;
1159 } /* end loop */
1162 /** Return true iff this TLS connection is authenticated.
1165 tor_tls_peer_has_cert(tor_tls_t *tls)
1167 X509 *cert;
1168 cert = SSL_get_peer_certificate(tls->ssl);
1169 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1170 if (!cert)
1171 return 0;
1172 X509_free(cert);
1173 return 1;
1176 /** Warn that a certificate lifetime extends through a certain range. */
1177 static void
1178 log_cert_lifetime(X509 *cert, const char *problem)
1180 BIO *bio = NULL;
1181 BUF_MEM *buf;
1182 char *s1=NULL, *s2=NULL;
1183 char mytime[33];
1184 time_t now = time(NULL);
1185 struct tm tm;
1187 if (problem)
1188 log_warn(LD_GENERAL,
1189 "Certificate %s: is your system clock set incorrectly?",
1190 problem);
1192 if (!(bio = BIO_new(BIO_s_mem()))) {
1193 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1195 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1196 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1197 goto end;
1199 BIO_get_mem_ptr(bio, &buf);
1200 s1 = tor_strndup(buf->data, buf->length);
1202 (void)BIO_reset(bio);
1203 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1204 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1205 goto end;
1207 BIO_get_mem_ptr(bio, &buf);
1208 s2 = tor_strndup(buf->data, buf->length);
1210 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1212 log_warn(LD_GENERAL,
1213 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1214 s1,s2,mytime);
1216 end:
1217 /* Not expected to get invoked */
1218 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1219 if (bio)
1220 BIO_free(bio);
1221 if (s1)
1222 tor_free(s1);
1223 if (s2)
1224 tor_free(s2);
1227 /** Helper function: try to extract a link certificate and an identity
1228 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1229 * *<b>id_cert_out</b> respectively. Log all messages at level
1230 * <b>severity</b>.
1232 * Note that a reference is added to cert_out, so it needs to be
1233 * freed. id_cert_out doesn't. */
1234 static void
1235 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1236 X509 **cert_out, X509 **id_cert_out)
1238 X509 *cert = NULL, *id_cert = NULL;
1239 STACK_OF(X509) *chain = NULL;
1240 int num_in_chain, i;
1241 *cert_out = *id_cert_out = NULL;
1243 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1244 return;
1245 *cert_out = cert;
1246 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1247 return;
1248 num_in_chain = sk_X509_num(chain);
1249 /* 1 means we're receiving (server-side), and it's just the id_cert.
1250 * 2 means we're connecting (client-side), and it's both the link
1251 * cert and the id_cert.
1253 if (num_in_chain < 1) {
1254 log_fn(severity,LD_PROTOCOL,
1255 "Unexpected number of certificates in chain (%d)",
1256 num_in_chain);
1257 return;
1259 for (i=0; i<num_in_chain; ++i) {
1260 id_cert = sk_X509_value(chain, i);
1261 if (X509_cmp(id_cert, cert) != 0)
1262 break;
1264 *id_cert_out = id_cert;
1267 /** If the provided tls connection is authenticated and has a
1268 * certificate chain that is currently valid and signed, then set
1269 * *<b>identity_key</b> to the identity certificate's key and return
1270 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1273 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1275 X509 *cert = NULL, *id_cert = NULL;
1276 EVP_PKEY *id_pkey = NULL;
1277 RSA *rsa;
1278 int r = -1;
1280 *identity_key = NULL;
1282 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1283 if (!cert)
1284 goto done;
1285 if (!id_cert) {
1286 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1287 goto done;
1289 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1290 X509_verify(cert, id_pkey) <= 0) {
1291 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1292 tls_log_errors(tls, severity,"verifying certificate");
1293 goto done;
1296 rsa = EVP_PKEY_get1_RSA(id_pkey);
1297 if (!rsa)
1298 goto done;
1299 *identity_key = _crypto_new_pk_env_rsa(rsa);
1301 r = 0;
1303 done:
1304 if (cert)
1305 X509_free(cert);
1306 if (id_pkey)
1307 EVP_PKEY_free(id_pkey);
1309 /* This should never get invoked, but let's make sure in case OpenSSL
1310 * acts unexpectedly. */
1311 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1313 return r;
1316 /** Check whether the certificate set on the connection <b>tls</b> is
1317 * expired or not-yet-valid, give or take <b>tolerance</b>
1318 * seconds. Return 0 for valid, -1 for failure.
1320 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1323 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1325 time_t now, t;
1326 X509 *cert;
1327 int r = -1;
1329 now = time(NULL);
1331 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1332 goto done;
1334 t = now + tolerance;
1335 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1336 log_cert_lifetime(cert, "not yet valid");
1337 goto done;
1339 t = now - tolerance;
1340 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1341 log_cert_lifetime(cert, "already expired");
1342 goto done;
1345 r = 0;
1346 done:
1347 if (cert)
1348 X509_free(cert);
1349 /* Not expected to get invoked */
1350 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1352 return r;
1355 /** Return the number of bytes available for reading from <b>tls</b>.
1358 tor_tls_get_pending_bytes(tor_tls_t *tls)
1360 tor_assert(tls);
1361 return SSL_pending(tls->ssl);
1364 /** If <b>tls</b> requires that the next write be of a particular size,
1365 * return that size. Otherwise, return 0. */
1366 size_t
1367 tor_tls_get_forced_write_size(tor_tls_t *tls)
1369 return tls->wantwrite_n;
1372 /** Sets n_read and n_written to the number of bytes read and written,
1373 * respectively, on the raw socket used by <b>tls</b> since the last time this
1374 * function was called on <b>tls</b>. */
1375 void
1376 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1378 BIO *wbio, *tmpbio;
1379 unsigned long r, w;
1380 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1381 /* We want the number of bytes actually for real written. Unfortunately,
1382 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1383 * which makes the answer turn out wrong. Let's cope with that. Note
1384 * that this approach will fail if we ever replace tls->ssl's BIOs with
1385 * buffering bios for reasons of our own. As an alternative, we could
1386 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1387 * that would be tempting fate. */
1388 wbio = SSL_get_wbio(tls->ssl);
1389 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1390 wbio = tmpbio;
1391 w = BIO_number_written(wbio);
1393 /* We are ok with letting these unsigned ints go "negative" here:
1394 * If we wrapped around, this should still give us the right answer, unless
1395 * we wrapped around by more than ULONG_MAX since the last time we called
1396 * this function.
1398 *n_read = (size_t)(r - tls->last_read_count);
1399 *n_written = (size_t)(w - tls->last_write_count);
1400 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1401 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1402 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1403 r, tls->last_read_count, w, tls->last_write_count);
1405 tls->last_read_count = r;
1406 tls->last_write_count = w;
1409 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1410 * errors, log an error message. */
1411 void
1412 _check_no_tls_errors(const char *fname, int line)
1414 if (ERR_peek_error() == 0)
1415 return;
1416 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1417 tor_fix_source_file(fname), line);
1418 tls_log_errors(NULL, LOG_WARN, NULL);
1421 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1422 * TLS handshake. Output is undefined if the handshake isn't finished. */
1424 tor_tls_used_v1_handshake(tor_tls_t *tls)
1426 if (tls->isServer) {
1427 #ifdef V2_HANDSHAKE_SERVER
1428 return ! tls->wasV2Handshake;
1429 #endif
1430 } else {
1431 #ifdef V2_HANDSHAKE_CLIENT
1432 return ! tls->wasV2Handshake;
1433 #endif
1435 return 1;
1438 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1439 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1440 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1441 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1442 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1443 void
1444 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1445 int *rbuf_capacity, int *rbuf_bytes,
1446 int *wbuf_capacity, int *wbuf_bytes)
1448 if (tls->ssl->s3->rbuf.buf)
1449 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1450 else
1451 *rbuf_capacity = 0;
1452 if (tls->ssl->s3->wbuf.buf)
1453 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1454 else
1455 *wbuf_capacity = 0;
1456 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1457 *wbuf_bytes = tls->ssl->s3->wbuf.left;