Fix compile warnings on Snow Leopard
[tor/rransom.git] / src / common / tortls.c
blobaeb0ca0800fd2538beb55f9932296db55c1a7eae
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 crypto_global_init(-1);
312 tls_library_is_initialized = 1;
316 /** Free all global TLS structures. */
317 void
318 tor_tls_free_all(void)
320 if (global_tls_context) {
321 tor_tls_context_decref(global_tls_context);
322 global_tls_context = NULL;
324 if (!HT_EMPTY(&tlsmap_root)) {
325 log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
327 HT_CLEAR(tlsmap, &tlsmap_root);
328 #ifdef V2_HANDSHAKE_CLIENT
329 if (CLIENT_CIPHER_DUMMIES)
330 tor_free(CLIENT_CIPHER_DUMMIES);
331 if (CLIENT_CIPHER_STACK)
332 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
333 #endif
336 /** We need to give OpenSSL a callback to verify certificates. This is
337 * it: We always accept peer certs and complete the handshake. We
338 * don't validate them until later.
340 static int
341 always_accept_verify_cb(int preverify_ok,
342 X509_STORE_CTX *x509_ctx)
344 (void) preverify_ok;
345 (void) x509_ctx;
346 return 1;
349 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
350 static X509_NAME *
351 tor_x509_name_new(const char *cname)
353 int nid;
354 X509_NAME *name;
355 if (!(name = X509_NAME_new()))
356 return NULL;
357 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
358 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
359 (unsigned char*)cname, -1, -1, 0)))
360 goto error;
361 return name;
362 error:
363 X509_NAME_free(name);
364 return NULL;
367 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
368 * signed by the private key <b>rsa_sign</b>. The commonName of the
369 * certificate will be <b>cname</b>; the commonName of the issuer will be
370 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
371 * starting from now. Return a certificate on success, NULL on
372 * failure.
374 static X509 *
375 tor_tls_create_certificate(crypto_pk_env_t *rsa,
376 crypto_pk_env_t *rsa_sign,
377 const char *cname,
378 const char *cname_sign,
379 unsigned int cert_lifetime)
381 time_t start_time, end_time;
382 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
383 X509 *x509 = NULL;
384 X509_NAME *name = NULL, *name_issuer=NULL;
386 tor_tls_init();
388 start_time = time(NULL);
390 tor_assert(rsa);
391 tor_assert(cname);
392 tor_assert(rsa_sign);
393 tor_assert(cname_sign);
394 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
395 goto error;
396 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
397 goto error;
398 if (!(x509 = X509_new()))
399 goto error;
400 if (!(X509_set_version(x509, 2)))
401 goto error;
402 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
403 goto error;
405 if (!(name = tor_x509_name_new(cname)))
406 goto error;
407 if (!(X509_set_subject_name(x509, name)))
408 goto error;
409 if (!(name_issuer = tor_x509_name_new(cname_sign)))
410 goto error;
411 if (!(X509_set_issuer_name(x509, name_issuer)))
412 goto error;
414 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
415 goto error;
416 end_time = start_time + cert_lifetime;
417 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
418 goto error;
419 if (!X509_set_pubkey(x509, pkey))
420 goto error;
421 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
422 goto error;
424 goto done;
425 error:
426 if (x509) {
427 X509_free(x509);
428 x509 = NULL;
430 done:
431 tls_log_errors(NULL, LOG_WARN, "generating certificate");
432 if (sign_pkey)
433 EVP_PKEY_free(sign_pkey);
434 if (pkey)
435 EVP_PKEY_free(pkey);
436 if (name)
437 X509_NAME_free(name);
438 if (name_issuer)
439 X509_NAME_free(name_issuer);
440 return x509;
443 /** List of ciphers that servers should select from.*/
444 #define SERVER_CIPHER_LIST \
445 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
446 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
447 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
448 /* Note: for setting up your own private testing network with link crypto
449 * disabled, set the cipher lists to your cipher list to
450 * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
451 * with any of the "real" Tors, though. */
453 #ifdef V2_HANDSHAKE_CLIENT
454 #define CIPHER(id, name) name ":"
455 #define XCIPHER(id, name)
456 /** List of ciphers that clients should advertise, omitting items that
457 * our OpenSSL doesn't know about. */
458 static const char CLIENT_CIPHER_LIST[] =
459 #include "./ciphers.inc"
461 #undef CIPHER
462 #undef XCIPHER
464 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
465 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
466 /** A list of all the ciphers that clients should advertise, including items
467 * that OpenSSL might not know about. */
468 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
469 #define CIPHER(id, name) { id, name },
470 #define XCIPHER(id, name) { id, #name },
471 #include "./ciphers.inc"
472 #undef CIPHER
473 #undef XCIPHER
476 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
477 static const int N_CLIENT_CIPHERS =
478 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
479 #endif
481 #ifndef V2_HANDSHAKE_CLIENT
482 #undef CLIENT_CIPHER_LIST
483 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
484 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
485 #endif
487 /** Remove a reference to <b>ctx</b>, and free it if it has no more
488 * references. */
489 static void
490 tor_tls_context_decref(tor_tls_context_t *ctx)
492 tor_assert(ctx);
493 if (--ctx->refcnt == 0) {
494 SSL_CTX_free(ctx->ctx);
495 X509_free(ctx->my_cert);
496 X509_free(ctx->my_id_cert);
497 crypto_free_pk_env(ctx->key);
498 tor_free(ctx);
502 /** Increase the reference count of <b>ctx</b>. */
503 static void
504 tor_tls_context_incref(tor_tls_context_t *ctx)
506 ++ctx->refcnt;
509 /** Create a new TLS context for use with Tor TLS handshakes.
510 * <b>identity</b> should be set to the identity key used to sign the
511 * certificate, and <b>nickname</b> set to the nickname to use.
513 * You can call this function multiple times. Each time you call it,
514 * it generates new certificates; all new connections will use
515 * the new SSL context.
518 tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
520 crypto_pk_env_t *rsa = NULL;
521 EVP_PKEY *pkey = NULL;
522 tor_tls_context_t *result = NULL;
523 X509 *cert = NULL, *idcert = NULL;
524 char *nickname = NULL, *nn2 = NULL;
526 tor_tls_init();
527 nickname = crypto_random_hostname(8, 20, "www.", ".net");
528 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
530 /* Generate short-term RSA key. */
531 if (!(rsa = crypto_new_pk_env()))
532 goto error;
533 if (crypto_pk_generate_key(rsa)<0)
534 goto error;
535 /* Create certificate signed by identity key. */
536 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
537 key_lifetime);
538 /* Create self-signed certificate for identity key. */
539 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
540 IDENTITY_CERT_LIFETIME);
541 if (!cert || !idcert) {
542 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
543 goto error;
546 result = tor_malloc_zero(sizeof(tor_tls_context_t));
547 result->refcnt = 1;
548 result->my_cert = X509_dup(cert);
549 result->my_id_cert = X509_dup(idcert);
550 result->key = crypto_pk_dup_key(rsa);
552 #ifdef EVERYONE_HAS_AES
553 /* Tell OpenSSL to only use TLS1 */
554 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
555 goto error;
556 #else
557 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
558 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
559 goto error;
560 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
561 #endif
562 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
564 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
565 SSL_CTX_set_options(result->ctx,
566 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
567 #endif
568 /* Don't actually allow compression; it uses ram and time, but the data
569 * we transmit is all encrypted anyway. */
570 if (result->ctx->comp_methods)
571 result->ctx->comp_methods = NULL;
572 #ifdef SSL_MODE_RELEASE_BUFFERS
573 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
574 #endif
575 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
576 goto error;
577 X509_free(cert); /* We just added a reference to cert. */
578 cert=NULL;
579 if (idcert) {
580 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
581 tor_assert(s);
582 X509_STORE_add_cert(s, idcert);
583 X509_free(idcert); /* The context now owns the reference to idcert */
584 idcert = NULL;
586 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
587 tor_assert(rsa);
588 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
589 goto error;
590 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
591 goto error;
592 EVP_PKEY_free(pkey);
593 pkey = NULL;
594 if (!SSL_CTX_check_private_key(result->ctx))
595 goto error;
597 crypto_dh_env_t *dh = crypto_dh_new();
598 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
599 crypto_dh_free(dh);
601 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
602 always_accept_verify_cb);
603 /* let us realloc bufs that we're writing from */
604 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
605 /* Free the old context if one exists. */
606 if (global_tls_context) {
607 /* This is safe even if there are open connections: OpenSSL does
608 * reference counting with SSL and SSL_CTX objects. */
609 tor_tls_context_decref(global_tls_context);
611 global_tls_context = result;
612 if (rsa)
613 crypto_free_pk_env(rsa);
614 tor_free(nickname);
615 tor_free(nn2);
616 return 0;
618 error:
619 tls_log_errors(NULL, LOG_WARN, "creating TLS context");
620 tor_free(nickname);
621 tor_free(nn2);
622 if (pkey)
623 EVP_PKEY_free(pkey);
624 if (rsa)
625 crypto_free_pk_env(rsa);
626 if (result)
627 tor_tls_context_decref(result);
628 if (cert)
629 X509_free(cert);
630 if (idcert)
631 X509_free(idcert);
632 return -1;
635 #ifdef V2_HANDSHAKE_SERVER
636 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
637 * a list that indicates that the client knows how to do the v2 TLS connection
638 * handshake. */
639 static int
640 tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
642 int i;
643 SSL_SESSION *session;
644 /* If we reached this point, we just got a client hello. See if there is
645 * a cipher list. */
646 if (!(session = SSL_get_session((SSL *)ssl))) {
647 log_warn(LD_NET, "No session on TLS?");
648 return 0;
650 if (!session->ciphers) {
651 log_warn(LD_NET, "No ciphers on session");
652 return 0;
654 /* Now we need to see if there are any ciphers whose presence means we're
655 * dealing with an updated Tor. */
656 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
657 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
658 const char *ciphername = SSL_CIPHER_get_name(cipher);
659 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
660 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
661 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
662 strcmp(ciphername, "(NONE)")) {
663 /* XXXX should be ld_debug */
664 log_info(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
665 // return 1;
666 goto dump_list;
669 return 0;
670 dump_list:
672 smartlist_t *elts = smartlist_create();
673 char *s;
674 for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
675 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
676 const char *ciphername = SSL_CIPHER_get_name(cipher);
677 smartlist_add(elts, (char*)ciphername);
679 s = smartlist_join_strings(elts, ":", 0, NULL);
680 log_info(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
681 address, s);
682 tor_free(s);
683 smartlist_free(elts);
685 return 1;
688 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
689 * changes state. We use this:
690 * <ul><li>To alter the state of the handshake partway through, so we
691 * do not send or request extra certificates in v2 handshakes.</li>
692 * <li>To detect renegotiation</li></ul>
694 static void
695 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
697 tor_tls_t *tls;
698 (void) val;
699 if (type != SSL_CB_ACCEPT_LOOP)
700 return;
701 if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
702 return;
704 tls = tor_tls_get_by_ssl(ssl);
705 if (tls) {
706 /* Check whether we're watching for renegotiates. If so, this is one! */
707 if (tls->negotiated_callback)
708 tls->got_renegotiate = 1;
709 } else {
710 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
713 /* Now check the cipher list. */
714 if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
715 /*XXXX_TLS keep this from happening more than once! */
717 /* Yes, we're casting away the const from ssl. This is very naughty of us.
718 * Let's hope openssl doesn't notice! */
720 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
721 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
722 /* Don't send a hello request. */
723 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
725 if (tls) {
726 tls->wasV2Handshake = 1;
727 } else {
728 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
732 #endif
734 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
735 * a list designed to mimic a common web browser. Some of the ciphers in the
736 * list won't actually be implemented by OpenSSL: that's okay so long as the
737 * server doesn't select them, and the server won't select anything besides
738 * what's in SERVER_CIPHER_LIST.
740 * [If the server <b>does</b> select a bogus cipher, we won't crash or
741 * anything; we'll just fail later when we try to look up the cipher in
742 * ssl->cipher_list_by_id.]
744 static void
745 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
747 #ifdef V2_HANDSHAKE_CLIENT
748 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
749 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
750 * we want.*/
751 int i = 0, j = 0;
753 /* First, create a dummy SSL_CIPHER for every cipher. */
754 CLIENT_CIPHER_DUMMIES =
755 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
756 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
757 CLIENT_CIPHER_DUMMIES[i].valid = 1;
758 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
759 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
762 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
763 tor_assert(CLIENT_CIPHER_STACK);
765 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
766 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
767 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
768 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
771 /* Then copy as many ciphers as we can from the good list, inserting
772 * dummies as needed. */
773 j=0;
774 for (i = 0; i < N_CLIENT_CIPHERS; ) {
775 SSL_CIPHER *cipher = NULL;
776 if (j < sk_SSL_CIPHER_num(*ciphers))
777 cipher = sk_SSL_CIPHER_value(*ciphers, j);
778 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
779 log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
780 ++j;
781 } else if (cipher &&
782 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
783 log_debug(LD_NET, "Found cipher %s", cipher->name);
784 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
785 ++j;
786 ++i;
787 } else {
788 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
789 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
790 ++i;
795 sk_SSL_CIPHER_free(*ciphers);
796 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
797 tor_assert(*ciphers);
799 #else
800 (void)ciphers;
801 #endif
804 /** Create a new TLS object from a file descriptor, and a flag to
805 * determine whether it is functioning as a server.
807 tor_tls_t *
808 tor_tls_new(int sock, int isServer)
810 BIO *bio = NULL;
811 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
813 tor_assert(global_tls_context); /* make sure somebody made it first */
814 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
815 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
816 tor_free(result);
817 return NULL;
820 #ifdef SSL_set_tlsext_host_name
821 /* Browsers use the TLS hostname extension, so we should too. */
823 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
824 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
825 tor_free(fake_hostname);
827 #endif
829 if (!SSL_set_cipher_list(result->ssl,
830 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
831 tls_log_errors(NULL, LOG_WARN, "setting ciphers");
832 SSL_free(result->ssl);
833 tor_free(result);
834 return NULL;
836 if (!isServer)
837 rectify_client_ciphers(&result->ssl->cipher_list);
838 result->socket = sock;
839 bio = BIO_new_socket(sock, BIO_NOCLOSE);
840 if (! bio) {
841 tls_log_errors(NULL, LOG_WARN, "opening BIO");
842 SSL_free(result->ssl);
843 tor_free(result);
844 return NULL;
846 HT_INSERT(tlsmap, &tlsmap_root, result);
847 SSL_set_bio(result->ssl, bio, bio);
848 tor_tls_context_incref(global_tls_context);
849 result->context = global_tls_context;
850 result->state = TOR_TLS_ST_HANDSHAKE;
851 result->isServer = isServer;
852 result->wantwrite_n = 0;
853 result->last_write_count = BIO_number_written(bio);
854 result->last_read_count = BIO_number_read(bio);
855 if (result->last_write_count || result->last_read_count) {
856 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
857 result->last_read_count, result->last_write_count);
859 #ifdef V2_HANDSHAKE_SERVER
860 if (isServer) {
861 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
863 #endif
864 /* Not expected to get called. */
865 tls_log_errors(NULL, LOG_WARN, "generating TLS context");
866 return result;
869 /** Make future log messages about <b>tls</b> display the address
870 * <b>address</b>.
872 void
873 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
875 tor_assert(tls);
876 tor_free(tls->address);
877 tls->address = tor_strdup(address);
880 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
881 * next gets a client-side renegotiate in the middle of a read. Do not
882 * invoke this function until <em>after</em> initial handshaking is done!
884 void
885 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
886 void (*cb)(tor_tls_t *, void *arg),
887 void *arg)
889 tls->negotiated_callback = cb;
890 tls->callback_arg = arg;
891 tls->got_renegotiate = 0;
892 #ifdef V2_HANDSHAKE_SERVER
893 if (cb) {
894 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
895 } else {
896 SSL_set_info_callback(tls->ssl, NULL);
898 #endif
901 /** Return whether this tls initiated the connect (client) or
902 * received it (server). */
904 tor_tls_is_server(tor_tls_t *tls)
906 tor_assert(tls);
907 return tls->isServer;
910 /** Release resources associated with a TLS object. Does not close the
911 * underlying file descriptor.
913 void
914 tor_tls_free(tor_tls_t *tls)
916 tor_tls_t *removed;
917 tor_assert(tls && tls->ssl);
918 removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
919 if (!removed) {
920 log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
922 SSL_free(tls->ssl);
923 tls->ssl = NULL;
924 tls->negotiated_callback = NULL;
925 if (tls->context)
926 tor_tls_context_decref(tls->context);
927 tor_free(tls->address);
928 tor_free(tls);
931 /** Underlying function for TLS reading. Reads up to <b>len</b>
932 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
933 * number of characters read. On failure, returns TOR_TLS_ERROR,
934 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
937 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
939 int r, err;
940 tor_assert(tls);
941 tor_assert(tls->ssl);
942 tor_assert(tls->state == TOR_TLS_ST_OPEN);
943 tor_assert(len<INT_MAX);
944 r = SSL_read(tls->ssl, cp, (int)len);
945 if (r > 0) {
946 #ifdef V2_HANDSHAKE_SERVER
947 if (tls->got_renegotiate) {
948 /* Renegotiation happened! */
949 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
950 if (tls->negotiated_callback)
951 tls->negotiated_callback(tls, tls->callback_arg);
952 tls->got_renegotiate = 0;
954 #endif
955 return r;
957 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
958 if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
959 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
960 tls->state = TOR_TLS_ST_CLOSED;
961 return TOR_TLS_CLOSE;
962 } else {
963 tor_assert(err != TOR_TLS_DONE);
964 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
965 return err;
969 /** Underlying function for TLS writing. Write up to <b>n</b>
970 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
971 * number of characters written. On failure, returns TOR_TLS_ERROR,
972 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
975 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
977 int r, err;
978 tor_assert(tls);
979 tor_assert(tls->ssl);
980 tor_assert(tls->state == TOR_TLS_ST_OPEN);
981 tor_assert(n < INT_MAX);
982 if (n == 0)
983 return 0;
984 if (tls->wantwrite_n) {
985 /* if WANTWRITE last time, we must use the _same_ n as before */
986 tor_assert(n >= tls->wantwrite_n);
987 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
988 (int)n, (int)tls->wantwrite_n);
989 n = tls->wantwrite_n;
990 tls->wantwrite_n = 0;
992 r = SSL_write(tls->ssl, cp, (int)n);
993 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
994 if (err == TOR_TLS_DONE) {
995 return r;
997 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
998 tls->wantwrite_n = n;
1000 return err;
1003 /** Perform initial handshake on <b>tls</b>. When finished, returns
1004 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1005 * or TOR_TLS_WANTWRITE.
1008 tor_tls_handshake(tor_tls_t *tls)
1010 int r;
1011 tor_assert(tls);
1012 tor_assert(tls->ssl);
1013 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1014 check_no_tls_errors();
1015 if (tls->isServer) {
1016 r = SSL_accept(tls->ssl);
1017 } else {
1018 r = SSL_connect(tls->ssl);
1020 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
1021 if (ERR_peek_error() != 0) {
1022 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN,
1023 "handshaking");
1024 return TOR_TLS_ERROR_MISC;
1026 if (r == TOR_TLS_DONE) {
1027 tls->state = TOR_TLS_ST_OPEN;
1028 if (tls->isServer) {
1029 SSL_set_info_callback(tls->ssl, NULL);
1030 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1031 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
1032 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
1033 #ifdef V2_HANDSHAKE_SERVER
1034 if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
1035 /* This check is redundant, but back when we did it in the callback,
1036 * we might have not been able to look up the tor_tls_t if the code
1037 * was buggy. Fixing that. */
1038 if (!tls->wasV2Handshake) {
1039 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1040 " get set. Fixing that.");
1042 tls->wasV2Handshake = 1;
1043 log_debug(LD_NET, "Completed V2 TLS handshake with client; waiting "
1044 "for renegotiation.");
1045 } else {
1046 tls->wasV2Handshake = 0;
1048 #endif
1049 } else {
1050 #ifdef V2_HANDSHAKE_CLIENT
1051 /* If we got no ID cert, we're a v2 handshake. */
1052 X509 *cert = SSL_get_peer_certificate(tls->ssl);
1053 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
1054 int n_certs = sk_X509_num(chain);
1055 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
1056 tls->wasV2Handshake = 0;
1057 else {
1058 log_debug(LD_NET, "Server sent back a single certificate; looks like "
1059 "a v2 handshake on %p.", tls);
1060 tls->wasV2Handshake = 1;
1062 if (cert)
1063 X509_free(cert);
1064 #endif
1065 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1066 tls_log_errors(NULL, LOG_WARN, "re-setting ciphers");
1067 r = TOR_TLS_ERROR_MISC;
1071 return r;
1074 /** Client only: Renegotiate a TLS session. When finished, returns
1075 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
1076 * TOR_TLS_WANTWRITE.
1079 tor_tls_renegotiate(tor_tls_t *tls)
1081 int r;
1082 tor_assert(tls);
1083 /* We could do server-initiated renegotiation too, but that would be tricky.
1084 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
1085 tor_assert(!tls->isServer);
1086 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
1087 int r = SSL_renegotiate(tls->ssl);
1088 if (r <= 0) {
1089 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN);
1091 tls->state = TOR_TLS_ST_RENEGOTIATE;
1093 r = SSL_do_handshake(tls->ssl);
1094 if (r == 1) {
1095 tls->state = TOR_TLS_ST_OPEN;
1096 return TOR_TLS_DONE;
1097 } else
1098 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO);
1101 /** Shut down an open tls connection <b>tls</b>. When finished, returns
1102 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1103 * or TOR_TLS_WANTWRITE.
1106 tor_tls_shutdown(tor_tls_t *tls)
1108 int r, err;
1109 char buf[128];
1110 tor_assert(tls);
1111 tor_assert(tls->ssl);
1113 while (1) {
1114 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
1115 /* If we've already called shutdown once to send a close message,
1116 * we read until the other side has closed too.
1118 do {
1119 r = SSL_read(tls->ssl, buf, 128);
1120 } while (r>0);
1121 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
1122 LOG_INFO);
1123 if (err == _TOR_TLS_ZERORETURN) {
1124 tls->state = TOR_TLS_ST_GOTCLOSE;
1125 /* fall through... */
1126 } else {
1127 return err;
1131 r = SSL_shutdown(tls->ssl);
1132 if (r == 1) {
1133 /* If shutdown returns 1, the connection is entirely closed. */
1134 tls->state = TOR_TLS_ST_CLOSED;
1135 return TOR_TLS_DONE;
1137 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
1138 LOG_INFO);
1139 if (err == _TOR_TLS_SYSCALL) {
1140 /* The underlying TCP connection closed while we were shutting down. */
1141 tls->state = TOR_TLS_ST_CLOSED;
1142 return TOR_TLS_DONE;
1143 } else if (err == _TOR_TLS_ZERORETURN) {
1144 /* The TLS connection says that it sent a shutdown record, but
1145 * isn't done shutting down yet. Make sure that this hasn't
1146 * happened before, then go back to the start of the function
1147 * and try to read.
1149 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
1150 tls->state == TOR_TLS_ST_SENTCLOSE) {
1151 log(LOG_WARN, LD_NET,
1152 "TLS returned \"half-closed\" value while already half-closed");
1153 return TOR_TLS_ERROR_MISC;
1155 tls->state = TOR_TLS_ST_SENTCLOSE;
1156 /* fall through ... */
1157 } else {
1158 return err;
1160 } /* end loop */
1163 /** Return true iff this TLS connection is authenticated.
1166 tor_tls_peer_has_cert(tor_tls_t *tls)
1168 X509 *cert;
1169 cert = SSL_get_peer_certificate(tls->ssl);
1170 tls_log_errors(tls, LOG_WARN, "getting peer certificate");
1171 if (!cert)
1172 return 0;
1173 X509_free(cert);
1174 return 1;
1177 /** Warn that a certificate lifetime extends through a certain range. */
1178 static void
1179 log_cert_lifetime(X509 *cert, const char *problem)
1181 BIO *bio = NULL;
1182 BUF_MEM *buf;
1183 char *s1=NULL, *s2=NULL;
1184 char mytime[33];
1185 time_t now = time(NULL);
1186 struct tm tm;
1188 if (problem)
1189 log_warn(LD_GENERAL,
1190 "Certificate %s: is your system clock set incorrectly?",
1191 problem);
1193 if (!(bio = BIO_new(BIO_s_mem()))) {
1194 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
1196 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
1197 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1198 goto end;
1200 BIO_get_mem_ptr(bio, &buf);
1201 s1 = tor_strndup(buf->data, buf->length);
1203 (void)BIO_reset(bio);
1204 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
1205 tls_log_errors(NULL, LOG_WARN, "printing certificate lifetime");
1206 goto end;
1208 BIO_get_mem_ptr(bio, &buf);
1209 s2 = tor_strndup(buf->data, buf->length);
1211 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
1213 log_warn(LD_GENERAL,
1214 "(certificate lifetime runs from %s through %s. Your time is %s.)",
1215 s1,s2,mytime);
1217 end:
1218 /* Not expected to get invoked */
1219 tls_log_errors(NULL, LOG_WARN, "getting certificate lifetime");
1220 if (bio)
1221 BIO_free(bio);
1222 if (s1)
1223 tor_free(s1);
1224 if (s2)
1225 tor_free(s2);
1228 /** Helper function: try to extract a link certificate and an identity
1229 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1230 * *<b>id_cert_out</b> respectively. Log all messages at level
1231 * <b>severity</b>.
1233 * Note that a reference is added to cert_out, so it needs to be
1234 * freed. id_cert_out doesn't. */
1235 static void
1236 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
1237 X509 **cert_out, X509 **id_cert_out)
1239 X509 *cert = NULL, *id_cert = NULL;
1240 STACK_OF(X509) *chain = NULL;
1241 int num_in_chain, i;
1242 *cert_out = *id_cert_out = NULL;
1244 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1245 return;
1246 *cert_out = cert;
1247 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1248 return;
1249 num_in_chain = sk_X509_num(chain);
1250 /* 1 means we're receiving (server-side), and it's just the id_cert.
1251 * 2 means we're connecting (client-side), and it's both the link
1252 * cert and the id_cert.
1254 if (num_in_chain < 1) {
1255 log_fn(severity,LD_PROTOCOL,
1256 "Unexpected number of certificates in chain (%d)",
1257 num_in_chain);
1258 return;
1260 for (i=0; i<num_in_chain; ++i) {
1261 id_cert = sk_X509_value(chain, i);
1262 if (X509_cmp(id_cert, cert) != 0)
1263 break;
1265 *id_cert_out = id_cert;
1268 /** If the provided tls connection is authenticated and has a
1269 * certificate chain that is currently valid and signed, then set
1270 * *<b>identity_key</b> to the identity certificate's key and return
1271 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
1274 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
1276 X509 *cert = NULL, *id_cert = NULL;
1277 EVP_PKEY *id_pkey = NULL;
1278 RSA *rsa;
1279 int r = -1;
1281 *identity_key = NULL;
1283 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
1284 if (!cert)
1285 goto done;
1286 if (!id_cert) {
1287 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
1288 goto done;
1290 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
1291 X509_verify(cert, id_pkey) <= 0) {
1292 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
1293 tls_log_errors(tls, severity,"verifying certificate");
1294 goto done;
1297 rsa = EVP_PKEY_get1_RSA(id_pkey);
1298 if (!rsa)
1299 goto done;
1300 *identity_key = _crypto_new_pk_env_rsa(rsa);
1302 r = 0;
1304 done:
1305 if (cert)
1306 X509_free(cert);
1307 if (id_pkey)
1308 EVP_PKEY_free(id_pkey);
1310 /* This should never get invoked, but let's make sure in case OpenSSL
1311 * acts unexpectedly. */
1312 tls_log_errors(tls, LOG_WARN, "finishing tor_tls_verify");
1314 return r;
1317 /** Check whether the certificate set on the connection <b>tls</b> is
1318 * expired or not-yet-valid, give or take <b>tolerance</b>
1319 * seconds. Return 0 for valid, -1 for failure.
1321 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
1324 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
1326 time_t now, t;
1327 X509 *cert;
1328 int r = -1;
1330 now = time(NULL);
1332 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1333 goto done;
1335 t = now + tolerance;
1336 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
1337 log_cert_lifetime(cert, "not yet valid");
1338 goto done;
1340 t = now - tolerance;
1341 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
1342 log_cert_lifetime(cert, "already expired");
1343 goto done;
1346 r = 0;
1347 done:
1348 if (cert)
1349 X509_free(cert);
1350 /* Not expected to get invoked */
1351 tls_log_errors(tls, LOG_WARN, "checking certificate lifetime");
1353 return r;
1356 /** Return the number of bytes available for reading from <b>tls</b>.
1359 tor_tls_get_pending_bytes(tor_tls_t *tls)
1361 tor_assert(tls);
1362 return SSL_pending(tls->ssl);
1365 /** If <b>tls</b> requires that the next write be of a particular size,
1366 * return that size. Otherwise, return 0. */
1367 size_t
1368 tor_tls_get_forced_write_size(tor_tls_t *tls)
1370 return tls->wantwrite_n;
1373 /** Sets n_read and n_written to the number of bytes read and written,
1374 * respectively, on the raw socket used by <b>tls</b> since the last time this
1375 * function was called on <b>tls</b>. */
1376 void
1377 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1379 BIO *wbio, *tmpbio;
1380 unsigned long r, w;
1381 r = BIO_number_read(SSL_get_rbio(tls->ssl));
1382 /* We want the number of bytes actually for real written. Unfortunately,
1383 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1384 * which makes the answer turn out wrong. Let's cope with that. Note
1385 * that this approach will fail if we ever replace tls->ssl's BIOs with
1386 * buffering bios for reasons of our own. As an alternative, we could
1387 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1388 * that would be tempting fate. */
1389 wbio = SSL_get_wbio(tls->ssl);
1390 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1391 wbio = tmpbio;
1392 w = BIO_number_written(wbio);
1394 /* We are ok with letting these unsigned ints go "negative" here:
1395 * If we wrapped around, this should still give us the right answer, unless
1396 * we wrapped around by more than ULONG_MAX since the last time we called
1397 * this function.
1399 *n_read = (size_t)(r - tls->last_read_count);
1400 *n_written = (size_t)(w - tls->last_write_count);
1401 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1402 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1403 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1404 r, tls->last_read_count, w, tls->last_write_count);
1406 tls->last_read_count = r;
1407 tls->last_write_count = w;
1410 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1411 * errors, log an error message. */
1412 void
1413 _check_no_tls_errors(const char *fname, int line)
1415 if (ERR_peek_error() == 0)
1416 return;
1417 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1418 tor_fix_source_file(fname), line);
1419 tls_log_errors(NULL, LOG_WARN, NULL);
1422 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1423 * TLS handshake. Output is undefined if the handshake isn't finished. */
1425 tor_tls_used_v1_handshake(tor_tls_t *tls)
1427 if (tls->isServer) {
1428 #ifdef V2_HANDSHAKE_SERVER
1429 return ! tls->wasV2Handshake;
1430 #endif
1431 } else {
1432 #ifdef V2_HANDSHAKE_CLIENT
1433 return ! tls->wasV2Handshake;
1434 #endif
1436 return 1;
1439 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1440 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1441 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1442 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1443 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
1444 void
1445 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1446 size_t *rbuf_capacity, size_t *rbuf_bytes,
1447 size_t *wbuf_capacity, size_t *wbuf_bytes)
1449 if (tls->ssl->s3->rbuf.buf)
1450 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1451 else
1452 *rbuf_capacity = 0;
1453 if (tls->ssl->s3->wbuf.buf)
1454 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1455 else
1456 *wbuf_capacity = 0;
1457 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1458 *wbuf_bytes = tls->ssl->s3->wbuf.left;