Some anti-forensics paranoia...
[tor.git] / src / common / tortls.c
blob886ee0ddac1984efd96b19453f17e70588e2bfea
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, 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 #if defined (WINCE)
20 #include <WinSock2.h>
21 #endif
23 #include <assert.h>
24 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
25 #ifndef _WIN32_WINNT
26 #define _WIN32_WINNT 0x0501
27 #endif
28 #define WIN32_LEAN_AND_MEAN
29 #if defined(_MSC_VER) && (_MSC_VER < 1300)
30 #include <winsock.h>
31 #else
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 #endif
35 #endif
36 #include <openssl/ssl.h>
37 #include <openssl/ssl3.h>
38 #include <openssl/err.h>
39 #include <openssl/tls1.h>
40 #include <openssl/asn1.h>
41 #include <openssl/bio.h>
42 #include <openssl/opensslv.h>
44 #ifdef USE_BUFFEREVENTS
45 #include <event2/bufferevent_ssl.h>
46 #include <event2/buffer.h>
47 #include <event2/event.h>
48 #include "compat_libevent.h"
49 #endif
51 #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
52 #define TORTLS_PRIVATE
54 #include "crypto.h"
55 #include "tortls.h"
56 #include "util.h"
57 #include "torlog.h"
58 #include "container.h"
59 #include <string.h>
61 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
62 #error "We require OpenSSL >= 0.9.8"
63 #endif
65 /* Enable the "v2" TLS handshake.
67 #define V2_HANDSHAKE_SERVER
68 #define V2_HANDSHAKE_CLIENT
70 /* Copied from or.h */
71 #define LEGAL_NICKNAME_CHARACTERS \
72 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
74 /** How long do identity certificates live? (sec) */
75 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
77 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
79 #if (OPENSSL_VERSION_NUMBER < OPENSSL_V(0,9,8,'s') || \
80 (OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(0,9,9) && \
81 OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f')))
82 /* This is a version of OpenSSL before 0.9.8s/1.0.0f. It does not have
83 * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
84 * SSL3 safely at the same time.
86 #define DISABLE_SSL3_HANDSHAKE
87 #endif
89 /* We redefine these so that we can run correctly even if the vendor gives us
90 * a version of OpenSSL that does not match its header files. (Apple: I am
91 * looking at you.)
93 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
94 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
95 #endif
96 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
97 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
98 #endif
100 /** Does the run-time openssl version look like we need
101 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
102 static int use_unsafe_renegotiation_op = 0;
103 /** Does the run-time openssl version look like we need
104 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
105 static int use_unsafe_renegotiation_flag = 0;
107 /** Structure that we use for a single certificate. */
108 struct tor_cert_t {
109 X509 *cert;
110 uint8_t *encoded;
111 size_t encoded_len;
112 unsigned pkey_digests_set : 1;
113 digests_t cert_digests;
114 digests_t pkey_digests;
117 /** Holds a SSL_CTX object and related state used to configure TLS
118 * connections.
120 typedef struct tor_tls_context_t {
121 int refcnt;
122 SSL_CTX *ctx;
123 tor_cert_t *my_link_cert;
124 tor_cert_t *my_id_cert;
125 tor_cert_t *my_auth_cert;
126 crypto_pk_t *link_key;
127 crypto_pk_t *auth_key;
128 } tor_tls_context_t;
130 /** Return values for tor_tls_classify_client_ciphers.
132 * @{
134 /** An error occurred when examining the client ciphers */
135 #define CIPHERS_ERR -1
136 /** The client cipher list indicates that a v1 handshake was in use. */
137 #define CIPHERS_V1 1
138 /** The client cipher list indicates that the client is using the v2 or the
139 * v3 handshake, but that it is (probably!) lying about what ciphers it
140 * supports */
141 #define CIPHERS_V2 2
142 /** The client cipher list indicates that the client is using the v2 or the
143 * v3 handshake, and that it is telling the truth about what ciphers it
144 * supports */
145 #define CIPHERS_UNRESTRICTED 3
146 /** @} */
148 #define TOR_TLS_MAGIC 0x71571571
150 typedef enum {
151 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
152 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
153 TOR_TLS_ST_BUFFEREVENT
154 } tor_tls_state_t;
156 /** Holds a SSL object and its associated data. Members are only
157 * accessed from within tortls.c.
159 struct tor_tls_t {
160 uint32_t magic;
161 tor_tls_context_t *context; /** A link to the context object for this tls. */
162 SSL *ssl; /**< An OpenSSL SSL object. */
163 int socket; /**< The underlying file descriptor for this TLS connection. */
164 char *address; /**< An address to log when describing this connection. */
165 ENUM_BF(tor_tls_state_t) state : 3; /**< The current SSL state,
166 * depending on which operations
167 * have completed successfully. */
168 unsigned int isServer:1; /**< True iff this is a server-side connection */
169 unsigned int wasV2Handshake:1; /**< True iff the original handshake for
170 * this connection used the updated version
171 * of the connection protocol (client sends
172 * different cipher list, server sends only
173 * one certificate). */
174 /** True iff we should call negotiated_callback when we're done reading. */
175 unsigned int got_renegotiate:1;
176 /** Return value from tor_tls_classify_client_ciphers, or 0 if we haven't
177 * called that function yet. */
178 int8_t client_cipher_list_type;
179 /** Incremented every time we start the server side of a handshake. */
180 uint8_t server_handshake_count;
181 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
182 * time. */
183 /** Last values retrieved from BIO_number_read()/write(); see
184 * tor_tls_get_n_raw_bytes() for usage.
186 unsigned long last_write_count;
187 unsigned long last_read_count;
188 /** If set, a callback to invoke whenever the client tries to renegotiate
189 * the handshake. */
190 void (*negotiated_callback)(tor_tls_t *tls, void *arg);
191 /** Argument to pass to negotiated_callback. */
192 void *callback_arg;
195 #ifdef V2_HANDSHAKE_CLIENT
196 /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
197 * in client mode into advertising the ciphers we want. See
198 * rectify_client_ciphers() for details. */
199 static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
200 /** A stack of SSL_CIPHER objects, some real, some fake.
201 * See rectify_client_ciphers() for details. */
202 static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
203 #endif
205 /** The ex_data index in which we store a pointer to an SSL object's
206 * corresponding tor_tls_t object. */
207 static int tor_tls_object_ex_data_index = -1;
209 /** Helper: Allocate tor_tls_object_ex_data_index. */
210 static void
211 tor_tls_allocate_tor_tls_object_ex_data_index(void)
213 if (tor_tls_object_ex_data_index == -1) {
214 tor_tls_object_ex_data_index =
215 SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
216 tor_assert(tor_tls_object_ex_data_index != -1);
220 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
221 * pointer. */
222 static INLINE tor_tls_t *
223 tor_tls_get_by_ssl(const SSL *ssl)
225 tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
226 if (result)
227 tor_assert(result->magic == TOR_TLS_MAGIC);
228 return result;
231 static void tor_tls_context_decref(tor_tls_context_t *ctx);
232 static void tor_tls_context_incref(tor_tls_context_t *ctx);
233 static X509* tor_tls_create_certificate(crypto_pk_t *rsa,
234 crypto_pk_t *rsa_sign,
235 const char *cname,
236 const char *cname_sign,
237 unsigned int cert_lifetime);
239 static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
240 crypto_pk_t *identity,
241 unsigned int key_lifetime,
242 unsigned int flags,
243 int is_client);
244 static tor_tls_context_t *tor_tls_context_new(crypto_pk_t *identity,
245 unsigned int key_lifetime,
246 unsigned int flags,
247 int is_client);
248 static int check_cert_lifetime_internal(int severity, const X509 *cert,
249 int past_tolerance, int future_tolerance);
251 /** Global TLS contexts. We keep them here because nobody else needs
252 * to touch them.
254 * @{ */
255 static tor_tls_context_t *server_tls_context = NULL;
256 static tor_tls_context_t *client_tls_context = NULL;
257 /**@}*/
259 /** True iff tor_tls_init() has been called. */
260 static int tls_library_is_initialized = 0;
262 /* Module-internal error codes. */
263 #define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
264 #define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
266 /** Write a description of the current state of <b>tls</b> into the
267 * <b>sz</b>-byte buffer at <b>buf</b>. */
268 void
269 tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
271 const char *ssl_state;
272 const char *tortls_state;
274 if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
275 strlcpy(buf, "(No SSL object)", sz);
276 return;
279 ssl_state = SSL_state_string_long(tls->ssl);
280 switch (tls->state) {
281 #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
282 CASE(HANDSHAKE);
283 CASE(OPEN);
284 CASE(GOTCLOSE);
285 CASE(SENTCLOSE);
286 CASE(CLOSED);
287 CASE(RENEGOTIATE);
288 #undef CASE
289 case TOR_TLS_ST_BUFFEREVENT:
290 tortls_state = "";
291 break;
292 default:
293 tortls_state = " in unknown TLS state";
294 break;
297 tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
300 /** Log a single error <b>err</b> as returned by ERR_get_error(), which was
301 * received while performing an operation <b>doing</b> on <b>tls</b>. Log
302 * the message at <b>severity</b>, in log domain <b>domain</b>. */
303 void
304 tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
305 int severity, int domain, const char *doing)
307 const char *state = NULL, *addr;
308 const char *msg, *lib, *func;
310 state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
312 addr = tls ? tls->address : NULL;
314 /* Some errors are known-benign, meaning they are the fault of the other
315 * side of the connection. The caller doesn't know this, so override the
316 * priority for those cases. */
317 switch (ERR_GET_REASON(err)) {
318 case SSL_R_HTTP_REQUEST:
319 case SSL_R_HTTPS_PROXY_REQUEST:
320 case SSL_R_RECORD_LENGTH_MISMATCH:
321 case SSL_R_RECORD_TOO_LARGE:
322 case SSL_R_UNKNOWN_PROTOCOL:
323 case SSL_R_UNSUPPORTED_PROTOCOL:
324 severity = LOG_INFO;
325 break;
326 default:
327 break;
330 msg = (const char*)ERR_reason_error_string(err);
331 lib = (const char*)ERR_lib_error_string(err);
332 func = (const char*)ERR_func_error_string(err);
333 if (!msg) msg = "(null)";
334 if (!lib) lib = "(null)";
335 if (!func) func = "(null)";
336 if (doing) {
337 tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
338 doing, addr?" with ":"", addr?addr:"",
339 msg, lib, func, state);
340 } else {
341 tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
342 addr?" with ":"", addr?addr:"",
343 msg, lib, func, state);
347 /** Log all pending tls errors at level <b>severity</b> in log domain
348 * <b>domain</b>. Use <b>doing</b> to describe our current activities.
350 static void
351 tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
353 unsigned long err;
355 while ((err = ERR_get_error()) != 0) {
356 tor_tls_log_one_error(tls, err, severity, domain, doing);
360 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
361 * code. */
362 static int
363 tor_errno_to_tls_error(int e)
365 switch (e) {
366 case SOCK_ERRNO(ECONNRESET): // most common
367 return TOR_TLS_ERROR_CONNRESET;
368 case SOCK_ERRNO(ETIMEDOUT):
369 return TOR_TLS_ERROR_TIMEOUT;
370 case SOCK_ERRNO(EHOSTUNREACH):
371 case SOCK_ERRNO(ENETUNREACH):
372 return TOR_TLS_ERROR_NO_ROUTE;
373 case SOCK_ERRNO(ECONNREFUSED):
374 return TOR_TLS_ERROR_CONNREFUSED; // least common
375 default:
376 return TOR_TLS_ERROR_MISC;
380 /** Given a TOR_TLS_* error code, return a string equivalent. */
381 const char *
382 tor_tls_err_to_string(int err)
384 if (err >= 0)
385 return "[Not an error.]";
386 switch (err) {
387 case TOR_TLS_ERROR_MISC: return "misc error";
388 case TOR_TLS_ERROR_IO: return "unexpected close";
389 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
390 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
391 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
392 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
393 case TOR_TLS_CLOSE: return "closed";
394 case TOR_TLS_WANTREAD: return "want to read";
395 case TOR_TLS_WANTWRITE: return "want to write";
396 default: return "(unknown error code)";
400 #define CATCH_SYSCALL 1
401 #define CATCH_ZERO 2
403 /** Given a TLS object and the result of an SSL_* call, use
404 * SSL_get_error to determine whether an error has occurred, and if so
405 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
406 * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
407 * reporting syscall errors. If extra&CATCH_ZERO is true, return
408 * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
410 * If an error has occurred, log it at level <b>severity</b> and describe the
411 * current action as <b>doing</b>.
413 static int
414 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
415 const char *doing, int severity, int domain)
417 int err = SSL_get_error(tls->ssl, r);
418 int tor_error = TOR_TLS_ERROR_MISC;
419 switch (err) {
420 case SSL_ERROR_NONE:
421 return TOR_TLS_DONE;
422 case SSL_ERROR_WANT_READ:
423 return TOR_TLS_WANTREAD;
424 case SSL_ERROR_WANT_WRITE:
425 return TOR_TLS_WANTWRITE;
426 case SSL_ERROR_SYSCALL:
427 if (extra&CATCH_SYSCALL)
428 return TOR_TLS_SYSCALL_;
429 if (r == 0) {
430 tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
431 doing, SSL_state_string_long(tls->ssl));
432 tor_error = TOR_TLS_ERROR_IO;
433 } else {
434 int e = tor_socket_errno(tls->socket);
435 tor_log(severity, LD_NET,
436 "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
437 doing, e, tor_socket_strerror(e),
438 SSL_state_string_long(tls->ssl));
439 tor_error = tor_errno_to_tls_error(e);
441 tls_log_errors(tls, severity, domain, doing);
442 return tor_error;
443 case SSL_ERROR_ZERO_RETURN:
444 if (extra&CATCH_ZERO)
445 return TOR_TLS_ZERORETURN_;
446 tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
447 doing, SSL_state_string_long(tls->ssl));
448 tls_log_errors(tls, severity, domain, doing);
449 return TOR_TLS_CLOSE;
450 default:
451 tls_log_errors(tls, severity, domain, doing);
452 return TOR_TLS_ERROR_MISC;
456 /** Initialize OpenSSL, unless it has already been initialized.
458 static void
459 tor_tls_init(void)
461 if (!tls_library_is_initialized) {
462 long version;
463 SSL_library_init();
464 SSL_load_error_strings();
466 version = SSLeay();
468 /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
469 * here, but without thinking too hard about it: it turns out that the
470 * flag in question needed to be set at the last minute, and that it
471 * conflicted with an existing flag number that had already been added
472 * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
473 * the flag with an option and (it seems) broke anything that used
474 * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
475 * and we mustn't use the SSL3_FLAGS option with anything besides
476 * OpenSSL 0.9.8l.
478 * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
479 * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
480 * set option 0x00040000L everywhere.
482 * No, we can't simply detect whether the flag or the option is present
483 * in the headers at build-time: some vendors (notably Apple) like to
484 * leave their headers out of sync with their libraries.
486 * Yes, it _is_ almost as if the OpenSSL developers decided that no
487 * program should be allowed to use renegotiation unless it first passed
488 * a test of intelligence and determination.
490 if (version > OPENSSL_V(0,9,8,'k') && version <= OPENSSL_V(0,9,8,'l')) {
491 log_info(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l, but "
492 "some vendors have backported renegotiation code from "
493 "0.9.8m without updating the version number. "
494 "I will try SSL3_FLAGS and SSL_OP to enable renegotation.",
495 SSLeay_version(SSLEAY_VERSION));
496 use_unsafe_renegotiation_flag = 1;
497 use_unsafe_renegotiation_op = 1;
498 } else if (version > OPENSSL_V(0,9,8,'l')) {
499 log_info(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
500 "I will try SSL_OP to enable renegotiation",
501 SSLeay_version(SSLEAY_VERSION));
502 use_unsafe_renegotiation_op = 1;
503 } else if (version <= OPENSSL_V(0,9,8,'k')) {
504 log_info(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
505 "0.9.8l, but some vendors have backported 0.9.8l's "
506 "renegotiation code to earlier versions, and some have "
507 "backported the code from 0.9.8m or 0.9.8n. I'll set both "
508 "SSL3_FLAGS and SSL_OP just to be safe.",
509 SSLeay_version(SSLEAY_VERSION), version);
510 use_unsafe_renegotiation_flag = 1;
511 use_unsafe_renegotiation_op = 1;
512 } else {
513 /* this is dead code, yes? */
514 log_info(LD_GENERAL, "OpenSSL %s has version %lx",
515 SSLeay_version(SSLEAY_VERSION), version);
518 #if (SIZEOF_VOID_P >= 8 && \
519 !defined(OPENSSL_NO_EC) && \
520 OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
521 if (version >= OPENSSL_V_SERIES(1,0,1)) {
522 /* Warn if we could *almost* be running with much faster ECDH.
523 If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
524 don't have one of the built-in __uint128-based speedups, we are
525 just one build operation away from an accelerated handshake.
527 (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
528 doing this test, but that gives compile-time options, not runtime
529 behavior.)
531 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
532 const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
533 const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
534 const int warn = (m == EC_GFp_simple_method() ||
535 m == EC_GFp_mont_method() ||
536 m == EC_GFp_nist_method());
537 EC_KEY_free(key);
539 if (warn)
540 log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
541 "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
542 "that apparently lacks accelerated support for the NIST "
543 "P-224 and P-256 groups. Building openssl with such "
544 "support (using the enable-ec_nistp_64_gcc_128 option "
545 "when configuring it) would make ECDH much faster.");
547 #endif
549 tor_tls_allocate_tor_tls_object_ex_data_index();
551 tls_library_is_initialized = 1;
555 /** Free all global TLS structures. */
556 void
557 tor_tls_free_all(void)
559 if (server_tls_context) {
560 tor_tls_context_t *ctx = server_tls_context;
561 server_tls_context = NULL;
562 tor_tls_context_decref(ctx);
564 if (client_tls_context) {
565 tor_tls_context_t *ctx = client_tls_context;
566 client_tls_context = NULL;
567 tor_tls_context_decref(ctx);
569 #ifdef V2_HANDSHAKE_CLIENT
570 if (CLIENT_CIPHER_DUMMIES)
571 tor_free(CLIENT_CIPHER_DUMMIES);
572 if (CLIENT_CIPHER_STACK)
573 sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
574 #endif
577 /** We need to give OpenSSL a callback to verify certificates. This is
578 * it: We always accept peer certs and complete the handshake. We
579 * don't validate them until later.
581 static int
582 always_accept_verify_cb(int preverify_ok,
583 X509_STORE_CTX *x509_ctx)
585 (void) preverify_ok;
586 (void) x509_ctx;
587 return 1;
590 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
591 static X509_NAME *
592 tor_x509_name_new(const char *cname)
594 int nid;
595 X509_NAME *name;
596 if (!(name = X509_NAME_new()))
597 return NULL;
598 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
599 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
600 (unsigned char*)cname, -1, -1, 0)))
601 goto error;
602 return name;
603 error:
604 X509_NAME_free(name);
605 return NULL;
608 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
609 * signed by the private key <b>rsa_sign</b>. The commonName of the
610 * certificate will be <b>cname</b>; the commonName of the issuer will be
611 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
612 * seconds, starting from some time in the past.
614 * Return a certificate on success, NULL on failure.
616 static X509 *
617 tor_tls_create_certificate(crypto_pk_t *rsa,
618 crypto_pk_t *rsa_sign,
619 const char *cname,
620 const char *cname_sign,
621 unsigned int cert_lifetime)
623 /* OpenSSL generates self-signed certificates with random 64-bit serial
624 * numbers, so let's do that too. */
625 #define SERIAL_NUMBER_SIZE 8
627 time_t start_time, end_time;
628 BIGNUM *serial_number = NULL;
629 unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
630 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
631 X509 *x509 = NULL;
632 X509_NAME *name = NULL, *name_issuer=NULL;
634 tor_tls_init();
636 /* Make sure we're part-way through the certificate lifetime, rather
637 * than having it start right now. Don't choose quite uniformly, since
638 * then we might pick a time where we're about to expire. Lastly, be
639 * sure to start on a day boundary. */
640 start_time = time(NULL) - crypto_rand_int(cert_lifetime) + 2*24*3600;
641 start_time -= start_time % (24*3600);
643 tor_assert(rsa);
644 tor_assert(cname);
645 tor_assert(rsa_sign);
646 tor_assert(cname_sign);
647 if (!(sign_pkey = crypto_pk_get_evp_pkey_(rsa_sign,1)))
648 goto error;
649 if (!(pkey = crypto_pk_get_evp_pkey_(rsa,0)))
650 goto error;
651 if (!(x509 = X509_new()))
652 goto error;
653 if (!(X509_set_version(x509, 2)))
654 goto error;
656 { /* our serial number is 8 random bytes. */
657 if (crypto_rand((char *)serial_tmp, sizeof(serial_tmp)) < 0)
658 goto error;
659 if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
660 goto error;
661 if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
662 goto error;
665 if (!(name = tor_x509_name_new(cname)))
666 goto error;
667 if (!(X509_set_subject_name(x509, name)))
668 goto error;
669 if (!(name_issuer = tor_x509_name_new(cname_sign)))
670 goto error;
671 if (!(X509_set_issuer_name(x509, name_issuer)))
672 goto error;
674 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
675 goto error;
676 end_time = start_time + cert_lifetime;
677 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
678 goto error;
679 if (!X509_set_pubkey(x509, pkey))
680 goto error;
681 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
682 goto error;
684 goto done;
685 error:
686 if (x509) {
687 X509_free(x509);
688 x509 = NULL;
690 done:
691 tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
692 if (sign_pkey)
693 EVP_PKEY_free(sign_pkey);
694 if (pkey)
695 EVP_PKEY_free(pkey);
696 if (serial_number)
697 BN_clear_free(serial_number);
698 if (name)
699 X509_NAME_free(name);
700 if (name_issuer)
701 X509_NAME_free(name_issuer);
702 return x509;
704 #undef SERIAL_NUMBER_SIZE
707 /** List of ciphers that servers should select from when the client might be
708 * claiming extra unsupported ciphers in order to avoid fingerprinting. */
709 #define SERVER_CIPHER_LIST \
710 (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
711 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
712 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
714 /** List of ciphers that servers should select from when we actually have
715 * our choice of what cipher to use. */
716 const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
717 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CHC_SHA
718 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
719 #endif
720 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
721 TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
722 #endif
723 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
724 TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
725 #endif
726 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
727 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
728 #endif
729 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
730 TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
731 #endif
732 //#if TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA
733 // TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA ":"
734 //#endif
735 /* These next two are mandatory. */
736 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
737 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
738 #ifdef TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA
739 TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":"
740 #endif
741 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA;
743 /* Note: to set up your own private testing network with link crypto
744 * disabled, set your Tors' cipher list to
745 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
746 * with any of the "real" Tors, though. */
748 #ifdef V2_HANDSHAKE_CLIENT
749 #define CIPHER(id, name) name ":"
750 #define XCIPHER(id, name)
751 /** List of ciphers that clients should advertise, omitting items that
752 * our OpenSSL doesn't know about. */
753 static const char CLIENT_CIPHER_LIST[] =
754 #include "./ciphers.inc"
755 /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
756 * of any cipher we say. */
757 "!SSLv2"
759 #undef CIPHER
760 #undef XCIPHER
762 /** Holds a cipher that we want to advertise, and its 2-byte ID. */
763 typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
764 /** A list of all the ciphers that clients should advertise, including items
765 * that OpenSSL might not know about. */
766 static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
767 #define CIPHER(id, name) { id, name },
768 #define XCIPHER(id, name) { id, #name },
769 #include "./ciphers.inc"
770 #undef CIPHER
771 #undef XCIPHER
774 /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
775 static const int N_CLIENT_CIPHERS =
776 sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
777 #endif
779 #ifndef V2_HANDSHAKE_CLIENT
780 #undef CLIENT_CIPHER_LIST
781 #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
782 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
783 #endif
785 /** Free all storage held in <b>cert</b> */
786 void
787 tor_cert_free(tor_cert_t *cert)
789 if (! cert)
790 return;
791 if (cert->cert)
792 X509_free(cert->cert);
793 tor_free(cert->encoded);
794 memwipe(cert, 0x03, sizeof(*cert));
795 tor_free(cert);
799 * Allocate a new tor_cert_t to hold the certificate "x509_cert".
801 * Steals a reference to x509_cert.
803 static tor_cert_t *
804 tor_cert_new(X509 *x509_cert)
806 tor_cert_t *cert;
807 EVP_PKEY *pkey;
808 RSA *rsa;
809 int length, length2;
810 unsigned char *cp;
812 if (!x509_cert)
813 return NULL;
815 length = i2d_X509(x509_cert, NULL);
816 cert = tor_malloc_zero(sizeof(tor_cert_t));
817 if (length <= 0) {
818 tor_free(cert);
819 log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
820 X509_free(x509_cert);
821 return NULL;
823 cert->encoded_len = (size_t) length;
824 cp = cert->encoded = tor_malloc(length);
825 length2 = i2d_X509(x509_cert, &cp);
826 tor_assert(length2 == length);
828 cert->cert = x509_cert;
830 crypto_digest_all(&cert->cert_digests,
831 (char*)cert->encoded, cert->encoded_len);
833 if ((pkey = X509_get_pubkey(x509_cert)) &&
834 (rsa = EVP_PKEY_get1_RSA(pkey))) {
835 crypto_pk_t *pk = crypto_new_pk_from_rsa_(rsa);
836 crypto_pk_get_all_digests(pk, &cert->pkey_digests);
837 cert->pkey_digests_set = 1;
838 crypto_pk_free(pk);
839 EVP_PKEY_free(pkey);
842 return cert;
845 /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
846 * from a <b>certificate</b>. Return a newly allocated tor_cert_t on success
847 * and NULL on failure. */
848 tor_cert_t *
849 tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
851 X509 *x509;
852 const unsigned char *cp = (const unsigned char *)certificate;
853 tor_cert_t *newcert;
854 tor_assert(certificate);
856 if (certificate_len > INT_MAX)
857 return NULL;
859 x509 = d2i_X509(NULL, &cp, (int)certificate_len);
861 if (!x509)
862 return NULL; /* Couldn't decode */
863 if (cp - certificate != (int)certificate_len) {
864 X509_free(x509);
865 return NULL; /* Didn't use all the bytes */
867 newcert = tor_cert_new(x509);
868 if (!newcert) {
869 return NULL;
871 if (newcert->encoded_len != certificate_len ||
872 fast_memneq(newcert->encoded, certificate, certificate_len)) {
873 /* Cert wasn't in DER */
874 tor_cert_free(newcert);
875 return NULL;
877 return newcert;
880 /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
881 * representation and length, respectively. */
882 void
883 tor_cert_get_der(const tor_cert_t *cert,
884 const uint8_t **encoded_out, size_t *size_out)
886 tor_assert(cert);
887 tor_assert(encoded_out);
888 tor_assert(size_out);
889 *encoded_out = cert->encoded;
890 *size_out = cert->encoded_len;
893 /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
894 * cert's public key is not one we know how to take the digest of. */
895 const digests_t *
896 tor_cert_get_id_digests(const tor_cert_t *cert)
898 if (cert->pkey_digests_set)
899 return &cert->pkey_digests;
900 else
901 return NULL;
904 /** Return a set of digests for the public key in <b>cert</b>. */
905 const digests_t *
906 tor_cert_get_cert_digests(const tor_cert_t *cert)
908 return &cert->cert_digests;
911 /** Remove a reference to <b>ctx</b>, and free it if it has no more
912 * references. */
913 static void
914 tor_tls_context_decref(tor_tls_context_t *ctx)
916 tor_assert(ctx);
917 if (--ctx->refcnt == 0) {
918 SSL_CTX_free(ctx->ctx);
919 tor_cert_free(ctx->my_link_cert);
920 tor_cert_free(ctx->my_id_cert);
921 tor_cert_free(ctx->my_auth_cert);
922 crypto_pk_free(ctx->link_key);
923 crypto_pk_free(ctx->auth_key);
924 tor_free(ctx);
928 /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
929 * and ID certificate that we're currently using for our V3 in-protocol
930 * handshake's certificate chain. If <b>server</b> is true, provide the certs
931 * that we use in server mode; otherwise, provide the certs that we use in
932 * client mode. */
934 tor_tls_get_my_certs(int server,
935 const tor_cert_t **link_cert_out,
936 const tor_cert_t **id_cert_out)
938 tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
939 if (! ctx)
940 return -1;
941 if (link_cert_out)
942 *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
943 if (id_cert_out)
944 *id_cert_out = ctx->my_id_cert;
945 return 0;
949 * Return the authentication key that we use to authenticate ourselves as a
950 * client in the V3 in-protocol handshake.
952 crypto_pk_t *
953 tor_tls_get_my_client_auth_key(void)
955 if (! client_tls_context)
956 return NULL;
957 return client_tls_context->auth_key;
961 * Return a newly allocated copy of the public key that a certificate
962 * certifies. Return NULL if the cert's key is not RSA.
964 crypto_pk_t *
965 tor_tls_cert_get_key(tor_cert_t *cert)
967 crypto_pk_t *result = NULL;
968 EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
969 RSA *rsa;
970 if (!pkey)
971 return NULL;
972 rsa = EVP_PKEY_get1_RSA(pkey);
973 if (!rsa) {
974 EVP_PKEY_free(pkey);
975 return NULL;
977 result = crypto_new_pk_from_rsa_(rsa);
978 EVP_PKEY_free(pkey);
979 return result;
982 /** Return true iff <b>a</b> and <b>b</b> represent the same public key. */
983 static int
984 pkey_eq(EVP_PKEY *a, EVP_PKEY *b)
986 /* We'd like to do this, but openssl 0.9.7 doesn't have it:
987 return EVP_PKEY_cmp(a,b) == 1;
989 unsigned char *a_enc=NULL, *b_enc=NULL, *a_ptr, *b_ptr;
990 int a_len1, b_len1, a_len2, b_len2, result;
991 a_len1 = i2d_PublicKey(a, NULL);
992 b_len1 = i2d_PublicKey(b, NULL);
993 if (a_len1 != b_len1)
994 return 0;
995 a_ptr = a_enc = tor_malloc(a_len1);
996 b_ptr = b_enc = tor_malloc(b_len1);
997 a_len2 = i2d_PublicKey(a, &a_ptr);
998 b_len2 = i2d_PublicKey(b, &b_ptr);
999 tor_assert(a_len2 == a_len1);
1000 tor_assert(b_len2 == b_len1);
1001 result = tor_memeq(a_enc, b_enc, a_len1);
1002 tor_free(a_enc);
1003 tor_free(b_enc);
1004 return result;
1007 /** Return true iff the other side of <b>tls</b> has authenticated to us, and
1008 * the key certified in <b>cert</b> is the same as the key they used to do it.
1011 tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
1013 X509 *peercert = SSL_get_peer_certificate(tls->ssl);
1014 EVP_PKEY *link_key = NULL, *cert_key = NULL;
1015 int result;
1017 if (!peercert)
1018 return 0;
1019 link_key = X509_get_pubkey(peercert);
1020 cert_key = X509_get_pubkey(cert->cert);
1022 result = link_key && cert_key && pkey_eq(cert_key, link_key);
1024 X509_free(peercert);
1025 if (link_key)
1026 EVP_PKEY_free(link_key);
1027 if (cert_key)
1028 EVP_PKEY_free(cert_key);
1030 return result;
1033 /** Check whether <b>cert</b> is well-formed, currently live, and correctly
1034 * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
1035 * make sure that it has an RSA key with 1024 bits; otherwise, just check that
1036 * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
1037 * we couldn't check it. */
1039 tor_tls_cert_is_valid(int severity,
1040 const tor_cert_t *cert,
1041 const tor_cert_t *signing_cert,
1042 int check_rsa_1024)
1044 EVP_PKEY *cert_key;
1045 EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
1046 int r, key_ok = 0;
1047 if (!signing_key)
1048 return 0;
1049 r = X509_verify(cert->cert, signing_key);
1050 EVP_PKEY_free(signing_key);
1051 if (r <= 0)
1052 return 0;
1054 /* okay, the signature checked out right. Now let's check the check the
1055 * lifetime. */
1056 if (check_cert_lifetime_internal(severity, cert->cert,
1057 48*60*60, 30*24*60*60) < 0)
1058 return 0;
1060 cert_key = X509_get_pubkey(cert->cert);
1061 if (check_rsa_1024 && cert_key) {
1062 RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
1063 if (rsa && BN_num_bits(rsa->n) == 1024)
1064 key_ok = 1;
1065 if (rsa)
1066 RSA_free(rsa);
1067 } else if (cert_key) {
1068 int min_bits = 1024;
1069 #ifdef EVP_PKEY_EC
1070 if (EVP_PKEY_type(cert_key->type) == EVP_PKEY_EC)
1071 min_bits = 128;
1072 #endif
1073 if (EVP_PKEY_bits(cert_key) >= min_bits)
1074 key_ok = 1;
1076 EVP_PKEY_free(cert_key);
1077 if (!key_ok)
1078 return 0;
1080 /* XXXX compare DNs or anything? */
1082 return 1;
1085 /** Increase the reference count of <b>ctx</b>. */
1086 static void
1087 tor_tls_context_incref(tor_tls_context_t *ctx)
1089 ++ctx->refcnt;
1092 /** Create new global client and server TLS contexts.
1094 * If <b>server_identity</b> is NULL, this will not generate a server
1095 * TLS context. If TOR_TLS_CTX_IS_PUBLIC_SERVER is set in <b>flags</b>, use
1096 * the same TLS context for incoming and outgoing connections, and
1097 * ignore <b>client_identity</b>. If one of TOR_TLS_CTX_USE_ECDHE_P{224,256}
1098 * is set in <b>flags</b>, use that ECDHE group if possible; otherwise use
1099 * the default ECDHE group. */
1101 tor_tls_context_init(unsigned flags,
1102 crypto_pk_t *client_identity,
1103 crypto_pk_t *server_identity,
1104 unsigned int key_lifetime)
1106 int rv1 = 0;
1107 int rv2 = 0;
1108 const int is_public_server = flags & TOR_TLS_CTX_IS_PUBLIC_SERVER;
1110 if (is_public_server) {
1111 tor_tls_context_t *new_ctx;
1112 tor_tls_context_t *old_ctx;
1114 tor_assert(server_identity != NULL);
1116 rv1 = tor_tls_context_init_one(&server_tls_context,
1117 server_identity,
1118 key_lifetime, flags, 0);
1120 if (rv1 >= 0) {
1121 new_ctx = server_tls_context;
1122 tor_tls_context_incref(new_ctx);
1123 old_ctx = client_tls_context;
1124 client_tls_context = new_ctx;
1126 if (old_ctx != NULL) {
1127 tor_tls_context_decref(old_ctx);
1130 } else {
1131 if (server_identity != NULL) {
1132 rv1 = tor_tls_context_init_one(&server_tls_context,
1133 server_identity,
1134 key_lifetime,
1135 flags,
1137 } else {
1138 tor_tls_context_t *old_ctx = server_tls_context;
1139 server_tls_context = NULL;
1141 if (old_ctx != NULL) {
1142 tor_tls_context_decref(old_ctx);
1146 rv2 = tor_tls_context_init_one(&client_tls_context,
1147 client_identity,
1148 key_lifetime,
1149 flags,
1153 return MIN(rv1, rv2);
1156 /** Create a new global TLS context.
1158 * You can call this function multiple times. Each time you call it,
1159 * it generates new certificates; all new connections will use
1160 * the new SSL context.
1162 static int
1163 tor_tls_context_init_one(tor_tls_context_t **ppcontext,
1164 crypto_pk_t *identity,
1165 unsigned int key_lifetime,
1166 unsigned int flags,
1167 int is_client)
1169 tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
1170 key_lifetime,
1171 flags,
1172 is_client);
1173 tor_tls_context_t *old_ctx = *ppcontext;
1175 if (new_ctx != NULL) {
1176 *ppcontext = new_ctx;
1178 /* Free the old context if one existed. */
1179 if (old_ctx != NULL) {
1180 /* This is safe even if there are open connections: we reference-
1181 * count tor_tls_context_t objects. */
1182 tor_tls_context_decref(old_ctx);
1186 return ((new_ctx != NULL) ? 0 : -1);
1189 /** Create a new TLS context for use with Tor TLS handshakes.
1190 * <b>identity</b> should be set to the identity key used to sign the
1191 * certificate.
1193 static tor_tls_context_t *
1194 tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
1195 unsigned flags, int is_client)
1197 crypto_pk_t *rsa = NULL, *rsa_auth = NULL;
1198 EVP_PKEY *pkey = NULL;
1199 tor_tls_context_t *result = NULL;
1200 X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
1201 char *nickname = NULL, *nn2 = NULL;
1203 tor_tls_init();
1204 nickname = crypto_random_hostname(8, 20, "www.", ".net");
1205 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1206 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
1207 #else
1208 nn2 = crypto_random_hostname(8, 20, "www.", ".com");
1209 #endif
1211 /* Generate short-term RSA key for use with TLS. */
1212 if (!(rsa = crypto_pk_new()))
1213 goto error;
1214 if (crypto_pk_generate_key(rsa)<0)
1215 goto error;
1216 if (!is_client) {
1217 /* Generate short-term RSA key for use in the in-protocol ("v3")
1218 * authentication handshake. */
1219 if (!(rsa_auth = crypto_pk_new()))
1220 goto error;
1221 if (crypto_pk_generate_key(rsa_auth)<0)
1222 goto error;
1223 /* Create a link certificate signed by identity key. */
1224 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
1225 key_lifetime);
1226 /* Create self-signed certificate for identity key. */
1227 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
1228 IDENTITY_CERT_LIFETIME);
1229 /* Create an authentication certificate signed by identity key. */
1230 authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
1231 key_lifetime);
1232 if (!cert || !idcert || !authcert) {
1233 log_warn(LD_CRYPTO, "Error creating certificate");
1234 goto error;
1238 result = tor_malloc_zero(sizeof(tor_tls_context_t));
1239 result->refcnt = 1;
1240 if (!is_client) {
1241 result->my_link_cert = tor_cert_new(X509_dup(cert));
1242 result->my_id_cert = tor_cert_new(X509_dup(idcert));
1243 result->my_auth_cert = tor_cert_new(X509_dup(authcert));
1244 if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
1245 goto error;
1246 result->link_key = crypto_pk_dup_key(rsa);
1247 result->auth_key = crypto_pk_dup_key(rsa_auth);
1250 #if 0
1251 /* Tell OpenSSL to only use TLS1. This may have subtly different results
1252 * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
1253 * investigation before we consider adjusting it. It should be compatible
1254 * with existing Tors. */
1255 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
1256 goto error;
1257 #endif
1259 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
1260 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
1261 goto error;
1262 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
1264 /* Disable TLS1.1 and TLS1.2 if they exist. We need to do this to
1265 * workaround a bug present in all OpenSSL 1.0.1 versions (as of 1
1266 * June 2012), wherein renegotiating while using one of these TLS
1267 * protocols will cause the client to send a TLS 1.0 ServerHello
1268 * rather than a ServerHello written with the appropriate protocol
1269 * version. Once some version of OpenSSL does TLS1.1 and TLS1.2
1270 * renegotiation properly, we can turn them back on when built with
1271 * that version. */
1272 #if OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,1,'e')
1273 #ifdef SSL_OP_NO_TLSv1_2
1274 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_2);
1275 #endif
1276 #ifdef SSL_OP_NO_TLSv1_1
1277 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_1);
1278 #endif
1279 #endif
1281 /* Disable TLS tickets if they're supported. We never want to use them;
1282 * using them can make our perfect forward secrecy a little worse, *and*
1283 * create an opportunity to fingerprint us (since it's unusual to use them
1284 * with TLS sessions turned off).
1286 * In 0.2.4, clients advertise support for them though, to avoid a TLS
1287 * distinguishability vector. This can give us worse PFS, though, if we
1288 * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
1289 * be few such servers by the time 0.2.4 is more stable.
1291 #ifdef SSL_OP_NO_TICKET
1292 if (! is_client) {
1293 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
1295 #endif
1297 if (
1298 #ifdef DISABLE_SSL3_HANDSHAKE
1299 1 ||
1300 #endif
1301 SSLeay() < OPENSSL_V(0,9,8,'s') ||
1302 (SSLeay() >= OPENSSL_V_SERIES(0,9,9) &&
1303 SSLeay() < OPENSSL_V(1,0,0,'f'))) {
1304 /* And not SSL3 if it's subject to CVE-2011-4576. */
1305 log_info(LD_NET, "Disabling SSLv3 because this OpenSSL version "
1306 "might otherwise be vulnerable to CVE-2011-4576 "
1307 "(compile-time version %08lx (%s); "
1308 "runtime version %08lx (%s))",
1309 (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
1310 (unsigned long)SSLeay(), SSLeay_version(SSLEAY_VERSION));
1311 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
1314 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
1315 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
1317 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1318 SSL_CTX_set_options(result->ctx,
1319 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
1320 #endif
1321 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1322 * as authenticating any earlier-received data.
1324 if (use_unsafe_renegotiation_op) {
1325 SSL_CTX_set_options(result->ctx,
1326 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1328 /* Don't actually allow compression; it uses ram and time, but the data
1329 * we transmit is all encrypted anyway. */
1330 if (result->ctx->comp_methods)
1331 result->ctx->comp_methods = NULL;
1332 #ifdef SSL_MODE_RELEASE_BUFFERS
1333 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
1334 #endif
1335 if (! is_client) {
1336 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
1337 goto error;
1338 X509_free(cert); /* We just added a reference to cert. */
1339 cert=NULL;
1340 if (idcert) {
1341 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
1342 tor_assert(s);
1343 X509_STORE_add_cert(s, idcert);
1344 X509_free(idcert); /* The context now owns the reference to idcert */
1345 idcert = NULL;
1348 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
1349 if (!is_client) {
1350 tor_assert(rsa);
1351 if (!(pkey = crypto_pk_get_evp_pkey_(rsa,1)))
1352 goto error;
1353 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
1354 goto error;
1355 EVP_PKEY_free(pkey);
1356 pkey = NULL;
1357 if (!SSL_CTX_check_private_key(result->ctx))
1358 goto error;
1361 crypto_dh_t *dh = crypto_dh_new(DH_TYPE_TLS);
1362 tor_assert(dh);
1363 SSL_CTX_set_tmp_dh(result->ctx, crypto_dh_get_dh_(dh));
1364 crypto_dh_free(dh);
1366 #if (!defined(OPENSSL_NO_EC) && \
1367 OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0))
1368 if (! is_client) {
1369 int nid;
1370 EC_KEY *ec_key;
1371 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
1372 nid = NID_secp224r1;
1373 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
1374 nid = NID_X9_62_prime256v1;
1375 else
1376 nid = NID_X9_62_prime256v1;
1377 /* Use P-256 for ECDHE. */
1378 ec_key = EC_KEY_new_by_curve_name(nid);
1379 if (ec_key != NULL) /*XXXX Handle errors? */
1380 SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
1381 EC_KEY_free(ec_key);
1383 #else
1384 (void)flags;
1385 #endif
1386 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
1387 always_accept_verify_cb);
1388 /* let us realloc bufs that we're writing from */
1389 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1391 if (rsa)
1392 crypto_pk_free(rsa);
1393 if (rsa_auth)
1394 crypto_pk_free(rsa_auth);
1395 X509_free(authcert);
1396 tor_free(nickname);
1397 tor_free(nn2);
1398 return result;
1400 error:
1401 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
1402 tor_free(nickname);
1403 tor_free(nn2);
1404 if (pkey)
1405 EVP_PKEY_free(pkey);
1406 if (rsa)
1407 crypto_pk_free(rsa);
1408 if (rsa_auth)
1409 crypto_pk_free(rsa_auth);
1410 if (result)
1411 tor_tls_context_decref(result);
1412 if (cert)
1413 X509_free(cert);
1414 if (idcert)
1415 X509_free(idcert);
1416 if (authcert)
1417 X509_free(authcert);
1418 return NULL;
1421 #ifdef V2_HANDSHAKE_SERVER
1423 /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
1424 * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
1425 * that it claims to support. We'll prune this list to remove the ciphers
1426 * *we* don't recognize. */
1427 static uint16_t v2_cipher_list[] = {
1428 0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
1429 0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
1430 0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
1431 0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
1432 0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
1433 0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
1434 0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
1435 0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
1436 0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
1437 0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
1438 0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
1439 0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
1440 0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
1441 0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
1442 0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
1443 0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
1444 0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
1445 0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
1446 0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
1447 0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
1448 0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
1449 0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
1450 0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
1451 0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
1452 0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
1453 0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
1454 0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
1455 0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
1458 /** Have we removed the unrecognized ciphers from v2_cipher_list yet? */
1459 static int v2_cipher_list_pruned = 0;
1461 /** Remove from v2_cipher_list every cipher that we don't support, so that
1462 * comparing v2_cipher_list to a client's cipher list will give a sensible
1463 * result. */
1464 static void
1465 prune_v2_cipher_list(void)
1467 uint16_t *inp, *outp;
1468 const SSL_METHOD *m = SSLv23_method();
1470 inp = outp = v2_cipher_list;
1471 while (*inp) {
1472 unsigned char cipherid[2];
1473 const SSL_CIPHER *cipher;
1474 /* Is there no better way to do this? */
1475 set_uint16(cipherid, htons(*inp));
1476 cipher = m->get_cipher_by_char(cipherid);
1477 if (cipher) {
1478 tor_assert((cipher->id & 0xffff) == *inp);
1479 *outp++ = *inp++;
1480 } else {
1481 inp++;
1484 *outp = 0;
1486 v2_cipher_list_pruned = 1;
1489 /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
1490 const char *
1491 tor_tls_get_ciphersuite_name(tor_tls_t *tls)
1493 return SSL_get_cipher(tls->ssl);
1496 /** Examine the client cipher list in <b>ssl</b>, and determine what kind of
1497 * client it is. Return one of CIPHERS_ERR, CIPHERS_V1, CIPHERS_V2,
1498 * CIPHERS_UNRESTRICTED.
1500 static int
1501 tor_tls_classify_client_ciphers(const SSL *ssl,
1502 STACK_OF(SSL_CIPHER) *peer_ciphers)
1504 int i, res;
1505 tor_tls_t *tor_tls;
1506 if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
1507 prune_v2_cipher_list();
1509 tor_tls = tor_tls_get_by_ssl(ssl);
1510 if (tor_tls && tor_tls->client_cipher_list_type)
1511 return tor_tls->client_cipher_list_type;
1513 /* If we reached this point, we just got a client hello. See if there is
1514 * a cipher list. */
1515 if (!peer_ciphers) {
1516 log_info(LD_NET, "No ciphers on session");
1517 res = CIPHERS_ERR;
1518 goto done;
1520 /* Now we need to see if there are any ciphers whose presence means we're
1521 * dealing with an updated Tor. */
1522 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
1523 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
1524 const char *ciphername = SSL_CIPHER_get_name(cipher);
1525 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
1526 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
1527 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
1528 strcmp(ciphername, "(NONE)")) {
1529 log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
1530 // return 1;
1531 goto v2_or_higher;
1534 res = CIPHERS_V1;
1535 goto done;
1536 v2_or_higher:
1538 const uint16_t *v2_cipher = v2_cipher_list;
1539 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
1540 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
1541 uint16_t id = cipher->id & 0xffff;
1542 if (id == 0x00ff) /* extended renegotiation indicator. */
1543 continue;
1544 if (!id || id != *v2_cipher) {
1545 res = CIPHERS_UNRESTRICTED;
1546 goto dump_ciphers;
1548 ++v2_cipher;
1550 if (*v2_cipher != 0) {
1551 res = CIPHERS_UNRESTRICTED;
1552 goto dump_ciphers;
1554 res = CIPHERS_V2;
1557 dump_ciphers:
1559 smartlist_t *elts = smartlist_new();
1560 char *s;
1561 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
1562 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
1563 const char *ciphername = SSL_CIPHER_get_name(cipher);
1564 smartlist_add(elts, (char*)ciphername);
1566 s = smartlist_join_strings(elts, ":", 0, NULL);
1567 log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
1568 (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
1569 tor_free(s);
1570 smartlist_free(elts);
1572 done:
1573 if (tor_tls)
1574 return tor_tls->client_cipher_list_type = res;
1576 return res;
1579 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
1580 * a list that indicates that the client knows how to do the v2 TLS connection
1581 * handshake. */
1582 static int
1583 tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
1585 SSL_SESSION *session;
1586 if (!(session = SSL_get_session((SSL *)ssl))) {
1587 log_info(LD_NET, "No session on TLS?");
1588 return CIPHERS_ERR;
1591 return tor_tls_classify_client_ciphers(ssl, session->ciphers) >= CIPHERS_V2;
1594 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0)
1595 /** Callback to get invoked on a server after we've read the list of ciphers
1596 * the client supports, but before we pick our own ciphersuite.
1598 * We can't abuse an info_cb for this, since by the time one of the
1599 * client_hello info_cbs is called, we've already picked which ciphersuite to
1600 * use.
1602 * Technically, this function is an abuse of this callback, since the point of
1603 * a session_secret_cb is to try to set up and/or verify a shared-secret for
1604 * authentication on the fly. But as long as we return 0, we won't actually be
1605 * setting up a shared secret, and all will be fine.
1607 static int
1608 tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
1609 STACK_OF(SSL_CIPHER) *peer_ciphers,
1610 SSL_CIPHER **cipher, void *arg)
1612 (void) secret;
1613 (void) secret_len;
1614 (void) peer_ciphers;
1615 (void) cipher;
1616 (void) arg;
1618 if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
1619 CIPHERS_UNRESTRICTED) {
1620 SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
1623 SSL_set_session_secret_cb(ssl, NULL, NULL);
1625 return 0;
1627 static void
1628 tor_tls_setup_session_secret_cb(tor_tls_t *tls)
1630 SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
1632 #else
1633 #define tor_tls_setup_session_secret_cb(tls) STMT_NIL
1634 #endif
1636 /** Invoked when a TLS state changes: log the change at severity 'debug' */
1637 static void
1638 tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
1640 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
1641 ssl, SSL_state_string_long(ssl), type, val);
1644 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
1645 * changes state. We use this:
1646 * <ul><li>To alter the state of the handshake partway through, so we
1647 * do not send or request extra certificates in v2 handshakes.</li>
1648 * <li>To detect renegotiation</li></ul>
1650 static void
1651 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
1653 tor_tls_t *tls;
1654 (void) val;
1656 tor_tls_debug_state_callback(ssl, type, val);
1658 if (type != SSL_CB_ACCEPT_LOOP)
1659 return;
1660 if ((ssl->state != SSL3_ST_SW_SRVR_HELLO_A) &&
1661 (ssl->state != SSL3_ST_SW_SRVR_HELLO_B))
1662 return;
1664 tls = tor_tls_get_by_ssl(ssl);
1665 if (tls) {
1666 /* Check whether we're watching for renegotiates. If so, this is one! */
1667 if (tls->negotiated_callback)
1668 tls->got_renegotiate = 1;
1669 if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
1670 ++tls->server_handshake_count;
1671 } else {
1672 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
1673 return;
1676 /* Now check the cipher list. */
1677 if (tor_tls_client_is_using_v2_ciphers(ssl)) {
1678 if (tls->wasV2Handshake)
1679 return; /* We already turned this stuff off for the first handshake;
1680 * This is a renegotiation. */
1682 /* Yes, we're casting away the const from ssl. This is very naughty of us.
1683 * Let's hope openssl doesn't notice! */
1685 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
1686 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
1687 /* Don't send a hello request. */
1688 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
1690 if (tls) {
1691 tls->wasV2Handshake = 1;
1692 #ifdef USE_BUFFEREVENTS
1693 if (use_unsafe_renegotiation_flag)
1694 tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1695 #endif
1696 } else {
1697 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
1701 #endif
1703 /** Explain which ciphers we're missing. */
1704 static void
1705 log_unsupported_ciphers(smartlist_t *unsupported)
1707 char *joined;
1709 log_notice(LD_NET, "We weren't able to find support for all of the "
1710 "TLS ciphersuites that we wanted to advertise. This won't "
1711 "hurt security, but it might make your Tor (if run as a client) "
1712 "more easy for censors to block.");
1714 if (SSLeay() < 0x10000000L) {
1715 log_notice(LD_NET, "To correct this, use a more recent OpenSSL, "
1716 "built without disabling any secure ciphers or features.");
1717 } else {
1718 log_notice(LD_NET, "To correct this, use a version of OpenSSL "
1719 "built with none of its ciphers disabled.");
1722 joined = smartlist_join_strings(unsupported, ":", 0, NULL);
1723 log_info(LD_NET, "The unsupported ciphers were: %s", joined);
1724 tor_free(joined);
1727 /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
1728 * a list designed to mimic a common web browser. We might not be able to do
1729 * that if OpenSSL doesn't support all the ciphers we want. Some of the
1730 * ciphers in the list won't actually be implemented by OpenSSL: that's okay
1731 * so long as the server doesn't select them.
1733 * [If the server <b>does</b> select a bogus cipher, we won't crash or
1734 * anything; we'll just fail later when we try to look up the cipher in
1735 * ssl->cipher_list_by_id.]
1737 static void
1738 rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
1740 #ifdef V2_HANDSHAKE_CLIENT
1741 if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
1742 /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
1743 * we want to use/advertise. */
1744 int i = 0, j = 0;
1745 smartlist_t *unsupported = smartlist_new();
1747 /* First, create a dummy SSL_CIPHER for every cipher. */
1748 CLIENT_CIPHER_DUMMIES =
1749 tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
1750 for (i=0; i < N_CLIENT_CIPHERS; ++i) {
1751 CLIENT_CIPHER_DUMMIES[i].valid = 1;
1752 /* The "3<<24" here signifies that the cipher is supposed to work with
1753 * SSL3 and TLS1. */
1754 CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
1755 CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
1758 CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
1759 tor_assert(CLIENT_CIPHER_STACK);
1761 log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
1762 for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
1763 SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
1764 log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
1767 /* Then copy as many ciphers as we can from the good list, inserting
1768 * dummies as needed. Let j be an index into list of ciphers we have
1769 * (*ciphers) and let i be an index into the ciphers we want
1770 * (CLIENT_INFO_CIPHER_LIST). We are building a list of ciphers in
1771 * CLIENT_CIPHER_STACK.
1773 for (i = j = 0; i < N_CLIENT_CIPHERS; ) {
1774 SSL_CIPHER *cipher = NULL;
1775 if (j < sk_SSL_CIPHER_num(*ciphers))
1776 cipher = sk_SSL_CIPHER_value(*ciphers, j);
1777 if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
1778 /* Skip over non-v3 ciphers entirely. (This should no longer be
1779 * needed, thanks to saying !SSLv2 above.) */
1780 log_debug(LD_NET, "Skipping v%d cipher %s",
1781 (int)((cipher->id>>24) & 0xff),
1782 cipher->name);
1783 ++j;
1784 } else if (cipher &&
1785 (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
1786 /* "cipher" is the cipher we expect. Put it on the list. */
1787 log_debug(LD_NET, "Found cipher %s", cipher->name);
1788 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
1789 ++j;
1790 ++i;
1791 } else if (!strcmp(CLIENT_CIPHER_DUMMIES[i].name,
1792 "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA")) {
1793 /* We found bogus cipher 0xfeff, which OpenSSL doesn't support and
1794 * never has. For this one, we need a dummy. */
1795 log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
1796 sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
1797 ++i;
1798 } else {
1799 /* OpenSSL doesn't have this one. */
1800 log_debug(LD_NET, "Completely omitting unsupported cipher %s",
1801 CLIENT_CIPHER_INFO_LIST[i].name);
1802 smartlist_add(unsupported, (char*) CLIENT_CIPHER_INFO_LIST[i].name);
1803 ++i;
1807 if (smartlist_len(unsupported))
1808 log_unsupported_ciphers(unsupported);
1810 smartlist_free(unsupported);
1813 sk_SSL_CIPHER_free(*ciphers);
1814 *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
1815 tor_assert(*ciphers);
1817 #else
1818 (void)ciphers;
1819 #endif
1822 /** Create a new TLS object from a file descriptor, and a flag to
1823 * determine whether it is functioning as a server.
1825 tor_tls_t *
1826 tor_tls_new(int sock, int isServer)
1828 BIO *bio = NULL;
1829 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
1830 tor_tls_context_t *context = isServer ? server_tls_context :
1831 client_tls_context;
1832 result->magic = TOR_TLS_MAGIC;
1834 tor_assert(context); /* make sure somebody made it first */
1835 if (!(result->ssl = SSL_new(context->ctx))) {
1836 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
1837 tor_free(result);
1838 return NULL;
1841 #ifdef SSL_set_tlsext_host_name
1842 /* Browsers use the TLS hostname extension, so we should too. */
1843 if (!isServer) {
1844 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
1845 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
1846 tor_free(fake_hostname);
1848 #endif
1850 if (!SSL_set_cipher_list(result->ssl,
1851 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
1852 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
1853 #ifdef SSL_set_tlsext_host_name
1854 SSL_set_tlsext_host_name(result->ssl, NULL);
1855 #endif
1856 SSL_free(result->ssl);
1857 tor_free(result);
1858 return NULL;
1860 if (!isServer)
1861 rectify_client_ciphers(&result->ssl->cipher_list);
1862 result->socket = sock;
1863 bio = BIO_new_socket(sock, BIO_NOCLOSE);
1864 if (! bio) {
1865 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
1866 #ifdef SSL_set_tlsext_host_name
1867 SSL_set_tlsext_host_name(result->ssl, NULL);
1868 #endif
1869 SSL_free(result->ssl);
1870 tor_free(result);
1871 return NULL;
1874 int set_worked =
1875 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
1876 if (!set_worked) {
1877 log_warn(LD_BUG,
1878 "Couldn't set the tls for an SSL*; connection will fail");
1881 SSL_set_bio(result->ssl, bio, bio);
1882 tor_tls_context_incref(context);
1883 result->context = context;
1884 result->state = TOR_TLS_ST_HANDSHAKE;
1885 result->isServer = isServer;
1886 result->wantwrite_n = 0;
1887 result->last_write_count = BIO_number_written(bio);
1888 result->last_read_count = BIO_number_read(bio);
1889 if (result->last_write_count || result->last_read_count) {
1890 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
1891 result->last_read_count, result->last_write_count);
1893 #ifdef V2_HANDSHAKE_SERVER
1894 if (isServer) {
1895 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
1896 } else
1897 #endif
1899 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
1902 if (isServer)
1903 tor_tls_setup_session_secret_cb(result);
1905 /* Not expected to get called. */
1906 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
1907 return result;
1910 /** Make future log messages about <b>tls</b> display the address
1911 * <b>address</b>.
1913 void
1914 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
1916 tor_assert(tls);
1917 tor_free(tls->address);
1918 tls->address = tor_strdup(address);
1921 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1922 * next gets a client-side renegotiate in the middle of a read. Do not
1923 * invoke this function until <em>after</em> initial handshaking is done!
1925 void
1926 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
1927 void (*cb)(tor_tls_t *, void *arg),
1928 void *arg)
1930 tls->negotiated_callback = cb;
1931 tls->callback_arg = arg;
1932 tls->got_renegotiate = 0;
1933 #ifdef V2_HANDSHAKE_SERVER
1934 if (cb) {
1935 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
1936 } else {
1937 SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
1939 #endif
1942 /** If this version of openssl requires it, turn on renegotiation on
1943 * <b>tls</b>.
1945 void
1946 tor_tls_unblock_renegotiation(tor_tls_t *tls)
1948 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1949 * as authenticating any earlier-received data. */
1950 if (use_unsafe_renegotiation_flag) {
1951 tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1953 if (use_unsafe_renegotiation_op) {
1954 SSL_set_options(tls->ssl,
1955 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1959 /** If this version of openssl supports it, turn off renegotiation on
1960 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1961 * to use belt-and-suspenders here.)
1963 void
1964 tor_tls_block_renegotiation(tor_tls_t *tls)
1966 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1969 /** Assert that the flags that allow legacy renegotiation are still set */
1970 void
1971 tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
1973 if (use_unsafe_renegotiation_flag) {
1974 tor_assert(0 != (tls->ssl->s3->flags &
1975 SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
1977 if (use_unsafe_renegotiation_op) {
1978 long options = SSL_get_options(tls->ssl);
1979 tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
1983 /** Return whether this tls initiated the connect (client) or
1984 * received it (server). */
1986 tor_tls_is_server(tor_tls_t *tls)
1988 tor_assert(tls);
1989 return tls->isServer;
1992 /** Release resources associated with a TLS object. Does not close the
1993 * underlying file descriptor.
1995 void
1996 tor_tls_free(tor_tls_t *tls)
1998 if (!tls)
1999 return;
2000 tor_assert(tls->ssl);
2002 size_t r,w;
2003 tor_tls_get_n_raw_bytes(tls,&r,&w); /* ensure written_by_tls is updated */
2005 #ifdef SSL_set_tlsext_host_name
2006 SSL_set_tlsext_host_name(tls->ssl, NULL);
2007 #endif
2008 SSL_free(tls->ssl);
2009 tls->ssl = NULL;
2010 tls->negotiated_callback = NULL;
2011 if (tls->context)
2012 tor_tls_context_decref(tls->context);
2013 tor_free(tls->address);
2014 tls->magic = 0x99999999;
2015 tor_free(tls);
2018 /** Underlying function for TLS reading. Reads up to <b>len</b>
2019 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
2020 * number of characters read. On failure, returns TOR_TLS_ERROR,
2021 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
2024 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
2026 int r, err;
2027 tor_assert(tls);
2028 tor_assert(tls->ssl);
2029 tor_assert(tls->state == TOR_TLS_ST_OPEN);
2030 tor_assert(len<INT_MAX);
2031 r = SSL_read(tls->ssl, cp, (int)len);
2032 if (r > 0) {
2033 #ifdef V2_HANDSHAKE_SERVER
2034 if (tls->got_renegotiate) {
2035 /* Renegotiation happened! */
2036 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
2037 if (tls->negotiated_callback)
2038 tls->negotiated_callback(tls, tls->callback_arg);
2039 tls->got_renegotiate = 0;
2041 #endif
2042 return r;
2044 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
2045 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
2046 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
2047 tls->state = TOR_TLS_ST_CLOSED;
2048 return TOR_TLS_CLOSE;
2049 } else {
2050 tor_assert(err != TOR_TLS_DONE);
2051 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
2052 return err;
2056 /** Total number of bytes that we've used TLS to send. Used to track TLS
2057 * overhead. */
2058 static uint64_t total_bytes_written_over_tls = 0;
2059 /** Total number of bytes that TLS has put on the network for us. Used to
2060 * track TLS overhead. */
2061 static uint64_t total_bytes_written_by_tls = 0;
2063 /** Underlying function for TLS writing. Write up to <b>n</b>
2064 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
2065 * number of characters written. On failure, returns TOR_TLS_ERROR,
2066 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
2069 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
2071 int r, err;
2072 tor_assert(tls);
2073 tor_assert(tls->ssl);
2074 tor_assert(tls->state == TOR_TLS_ST_OPEN);
2075 tor_assert(n < INT_MAX);
2076 if (n == 0)
2077 return 0;
2078 if (tls->wantwrite_n) {
2079 /* if WANTWRITE last time, we must use the _same_ n as before */
2080 tor_assert(n >= tls->wantwrite_n);
2081 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
2082 (int)n, (int)tls->wantwrite_n);
2083 n = tls->wantwrite_n;
2084 tls->wantwrite_n = 0;
2086 r = SSL_write(tls->ssl, cp, (int)n);
2087 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
2088 if (err == TOR_TLS_DONE) {
2089 total_bytes_written_over_tls += r;
2090 return r;
2092 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
2093 tls->wantwrite_n = n;
2095 return err;
2098 /** Perform initial handshake on <b>tls</b>. When finished, returns
2099 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
2100 * or TOR_TLS_WANTWRITE.
2103 tor_tls_handshake(tor_tls_t *tls)
2105 int r;
2106 int oldstate;
2107 tor_assert(tls);
2108 tor_assert(tls->ssl);
2109 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
2110 check_no_tls_errors();
2111 oldstate = tls->ssl->state;
2112 if (tls->isServer) {
2113 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
2114 SSL_state_string_long(tls->ssl));
2115 r = SSL_accept(tls->ssl);
2116 } else {
2117 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
2118 SSL_state_string_long(tls->ssl));
2119 r = SSL_connect(tls->ssl);
2121 if (oldstate != tls->ssl->state)
2122 log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
2123 tls, SSL_state_string_long(tls->ssl));
2124 /* We need to call this here and not earlier, since OpenSSL has a penchant
2125 * for clearing its flags when you say accept or connect. */
2126 tor_tls_unblock_renegotiation(tls);
2127 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
2128 if (ERR_peek_error() != 0) {
2129 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
2130 "handshaking");
2131 return TOR_TLS_ERROR_MISC;
2133 if (r == TOR_TLS_DONE) {
2134 tls->state = TOR_TLS_ST_OPEN;
2135 return tor_tls_finish_handshake(tls);
2137 return r;
2140 /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
2141 * should be called for the first handshake only: it determines whether the v1
2142 * or the v2 handshake was used, and adjusts things for the renegotiation
2143 * handshake as appropriate.
2145 * tor_tls_handshake() calls this on its own; you only need to call this if
2146 * bufferevent is doing the handshake for you.
2149 tor_tls_finish_handshake(tor_tls_t *tls)
2151 int r = TOR_TLS_DONE;
2152 if (tls->isServer) {
2153 SSL_set_info_callback(tls->ssl, NULL);
2154 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
2155 /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
2156 tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
2157 #ifdef V2_HANDSHAKE_SERVER
2158 if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
2159 /* This check is redundant, but back when we did it in the callback,
2160 * we might have not been able to look up the tor_tls_t if the code
2161 * was buggy. Fixing that. */
2162 if (!tls->wasV2Handshake) {
2163 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
2164 " get set. Fixing that.");
2166 tls->wasV2Handshake = 1;
2167 log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
2168 " for renegotiation.");
2169 } else {
2170 tls->wasV2Handshake = 0;
2172 #endif
2173 } else {
2174 #ifdef V2_HANDSHAKE_CLIENT
2175 /* If we got no ID cert, we're a v2 handshake. */
2176 X509 *cert = SSL_get_peer_certificate(tls->ssl);
2177 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
2178 int n_certs = sk_X509_num(chain);
2179 if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
2180 log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
2181 "looks like a v1 handshake on %p", tls);
2182 tls->wasV2Handshake = 0;
2183 } else {
2184 log_debug(LD_HANDSHAKE,
2185 "Server sent back a single certificate; looks like "
2186 "a v2 handshake on %p.", tls);
2187 tls->wasV2Handshake = 1;
2189 if (cert)
2190 X509_free(cert);
2191 #endif
2192 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
2193 tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
2194 r = TOR_TLS_ERROR_MISC;
2197 return r;
2200 #ifdef USE_BUFFEREVENTS
2201 /** Put <b>tls</b>, which must be a client connection, into renegotiation
2202 * mode. */
2204 tor_tls_start_renegotiating(tor_tls_t *tls)
2206 int r = SSL_renegotiate(tls->ssl);
2207 if (r <= 0) {
2208 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
2209 LD_HANDSHAKE);
2211 return 0;
2213 #endif
2215 /** Client only: Renegotiate a TLS session. When finished, returns
2216 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
2217 * TOR_TLS_WANTWRITE.
2220 tor_tls_renegotiate(tor_tls_t *tls)
2222 int r;
2223 tor_assert(tls);
2224 /* We could do server-initiated renegotiation too, but that would be tricky.
2225 * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
2226 tor_assert(!tls->isServer);
2227 if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
2228 int r = SSL_renegotiate(tls->ssl);
2229 if (r <= 0) {
2230 return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
2231 LD_HANDSHAKE);
2233 tls->state = TOR_TLS_ST_RENEGOTIATE;
2235 r = SSL_do_handshake(tls->ssl);
2236 if (r == 1) {
2237 tls->state = TOR_TLS_ST_OPEN;
2238 return TOR_TLS_DONE;
2239 } else
2240 return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
2241 LD_HANDSHAKE);
2244 /** Shut down an open tls connection <b>tls</b>. When finished, returns
2245 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
2246 * or TOR_TLS_WANTWRITE.
2249 tor_tls_shutdown(tor_tls_t *tls)
2251 int r, err;
2252 char buf[128];
2253 tor_assert(tls);
2254 tor_assert(tls->ssl);
2256 while (1) {
2257 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
2258 /* If we've already called shutdown once to send a close message,
2259 * we read until the other side has closed too.
2261 do {
2262 r = SSL_read(tls->ssl, buf, 128);
2263 } while (r>0);
2264 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
2265 LOG_INFO, LD_NET);
2266 if (err == TOR_TLS_ZERORETURN_) {
2267 tls->state = TOR_TLS_ST_GOTCLOSE;
2268 /* fall through... */
2269 } else {
2270 return err;
2274 r = SSL_shutdown(tls->ssl);
2275 if (r == 1) {
2276 /* If shutdown returns 1, the connection is entirely closed. */
2277 tls->state = TOR_TLS_ST_CLOSED;
2278 return TOR_TLS_DONE;
2280 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
2281 LOG_INFO, LD_NET);
2282 if (err == TOR_TLS_SYSCALL_) {
2283 /* The underlying TCP connection closed while we were shutting down. */
2284 tls->state = TOR_TLS_ST_CLOSED;
2285 return TOR_TLS_DONE;
2286 } else if (err == TOR_TLS_ZERORETURN_) {
2287 /* The TLS connection says that it sent a shutdown record, but
2288 * isn't done shutting down yet. Make sure that this hasn't
2289 * happened before, then go back to the start of the function
2290 * and try to read.
2292 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
2293 tls->state == TOR_TLS_ST_SENTCLOSE) {
2294 log_warn(LD_NET,
2295 "TLS returned \"half-closed\" value while already half-closed");
2296 return TOR_TLS_ERROR_MISC;
2298 tls->state = TOR_TLS_ST_SENTCLOSE;
2299 /* fall through ... */
2300 } else {
2301 return err;
2303 } /* end loop */
2306 /** Return true iff this TLS connection is authenticated.
2309 tor_tls_peer_has_cert(tor_tls_t *tls)
2311 X509 *cert;
2312 cert = SSL_get_peer_certificate(tls->ssl);
2313 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
2314 if (!cert)
2315 return 0;
2316 X509_free(cert);
2317 return 1;
2320 /** Return the peer certificate, or NULL if there isn't one. */
2321 tor_cert_t *
2322 tor_tls_get_peer_cert(tor_tls_t *tls)
2324 X509 *cert;
2325 cert = SSL_get_peer_certificate(tls->ssl);
2326 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
2327 if (!cert)
2328 return NULL;
2329 return tor_cert_new(cert);
2332 /** Warn that a certificate lifetime extends through a certain range. */
2333 static void
2334 log_cert_lifetime(int severity, const X509 *cert, const char *problem)
2336 BIO *bio = NULL;
2337 BUF_MEM *buf;
2338 char *s1=NULL, *s2=NULL;
2339 char mytime[33];
2340 time_t now = time(NULL);
2341 struct tm tm;
2343 if (problem)
2344 tor_log(severity, LD_GENERAL,
2345 "Certificate %s. Either their clock is set wrong, or your clock "
2346 "is wrong.",
2347 problem);
2349 if (!(bio = BIO_new(BIO_s_mem()))) {
2350 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
2352 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
2353 tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
2354 goto end;
2356 BIO_get_mem_ptr(bio, &buf);
2357 s1 = tor_strndup(buf->data, buf->length);
2359 (void)BIO_reset(bio);
2360 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
2361 tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
2362 goto end;
2364 BIO_get_mem_ptr(bio, &buf);
2365 s2 = tor_strndup(buf->data, buf->length);
2367 strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
2369 tor_log(severity, LD_GENERAL,
2370 "(certificate lifetime runs from %s through %s. Your time is %s.)",
2371 s1,s2,mytime);
2373 end:
2374 /* Not expected to get invoked */
2375 tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
2376 if (bio)
2377 BIO_free(bio);
2378 tor_free(s1);
2379 tor_free(s2);
2382 /** Helper function: try to extract a link certificate and an identity
2383 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
2384 * *<b>id_cert_out</b> respectively. Log all messages at level
2385 * <b>severity</b>.
2387 * Note that a reference is added to cert_out, so it needs to be
2388 * freed. id_cert_out doesn't. */
2389 static void
2390 try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
2391 X509 **cert_out, X509 **id_cert_out)
2393 X509 *cert = NULL, *id_cert = NULL;
2394 STACK_OF(X509) *chain = NULL;
2395 int num_in_chain, i;
2396 *cert_out = *id_cert_out = NULL;
2398 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
2399 return;
2400 *cert_out = cert;
2401 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
2402 return;
2403 num_in_chain = sk_X509_num(chain);
2404 /* 1 means we're receiving (server-side), and it's just the id_cert.
2405 * 2 means we're connecting (client-side), and it's both the link
2406 * cert and the id_cert.
2408 if (num_in_chain < 1) {
2409 log_fn(severity,LD_PROTOCOL,
2410 "Unexpected number of certificates in chain (%d)",
2411 num_in_chain);
2412 return;
2414 for (i=0; i<num_in_chain; ++i) {
2415 id_cert = sk_X509_value(chain, i);
2416 if (X509_cmp(id_cert, cert) != 0)
2417 break;
2419 *id_cert_out = id_cert;
2422 /** If the provided tls connection is authenticated and has a
2423 * certificate chain that is currently valid and signed, then set
2424 * *<b>identity_key</b> to the identity certificate's key and return
2425 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
2428 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
2430 X509 *cert = NULL, *id_cert = NULL;
2431 EVP_PKEY *id_pkey = NULL;
2432 RSA *rsa;
2433 int r = -1;
2435 *identity_key = NULL;
2437 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
2438 if (!cert)
2439 goto done;
2440 if (!id_cert) {
2441 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
2442 goto done;
2444 tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
2446 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
2447 X509_verify(cert, id_pkey) <= 0) {
2448 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
2449 tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
2450 goto done;
2453 rsa = EVP_PKEY_get1_RSA(id_pkey);
2454 if (!rsa)
2455 goto done;
2456 *identity_key = crypto_new_pk_from_rsa_(rsa);
2458 r = 0;
2460 done:
2461 if (cert)
2462 X509_free(cert);
2463 if (id_pkey)
2464 EVP_PKEY_free(id_pkey);
2466 /* This should never get invoked, but let's make sure in case OpenSSL
2467 * acts unexpectedly. */
2468 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
2470 return r;
2473 /** Check whether the certificate set on the connection <b>tls</b> is expired
2474 * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
2475 * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
2477 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
2480 tor_tls_check_lifetime(int severity, tor_tls_t *tls,
2481 int past_tolerance, int future_tolerance)
2483 X509 *cert;
2484 int r = -1;
2486 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
2487 goto done;
2489 if (check_cert_lifetime_internal(severity, cert,
2490 past_tolerance, future_tolerance) < 0)
2491 goto done;
2493 r = 0;
2494 done:
2495 if (cert)
2496 X509_free(cert);
2497 /* Not expected to get invoked */
2498 tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
2500 return r;
2503 /** Helper: check whether <b>cert</b> is expired give or take
2504 * <b>past_tolerance</b> seconds, or not-yet-valid give or take
2505 * <b>future_tolerance</b> seconds. If it is live, return 0. If it is not
2506 * live, log a message and return -1. */
2507 static int
2508 check_cert_lifetime_internal(int severity, const X509 *cert,
2509 int past_tolerance, int future_tolerance)
2511 time_t now, t;
2513 now = time(NULL);
2515 t = now + future_tolerance;
2516 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
2517 log_cert_lifetime(severity, cert, "not yet valid");
2518 return -1;
2520 t = now - past_tolerance;
2521 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
2522 log_cert_lifetime(severity, cert, "already expired");
2523 return -1;
2526 return 0;
2529 /** Return the number of bytes available for reading from <b>tls</b>.
2532 tor_tls_get_pending_bytes(tor_tls_t *tls)
2534 tor_assert(tls);
2535 return SSL_pending(tls->ssl);
2538 /** If <b>tls</b> requires that the next write be of a particular size,
2539 * return that size. Otherwise, return 0. */
2540 size_t
2541 tor_tls_get_forced_write_size(tor_tls_t *tls)
2543 return tls->wantwrite_n;
2546 /** Sets n_read and n_written to the number of bytes read and written,
2547 * respectively, on the raw socket used by <b>tls</b> since the last time this
2548 * function was called on <b>tls</b>. */
2549 void
2550 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
2552 BIO *wbio, *tmpbio;
2553 unsigned long r, w;
2554 r = BIO_number_read(SSL_get_rbio(tls->ssl));
2555 /* We want the number of bytes actually for real written. Unfortunately,
2556 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
2557 * which makes the answer turn out wrong. Let's cope with that. Note
2558 * that this approach will fail if we ever replace tls->ssl's BIOs with
2559 * buffering bios for reasons of our own. As an alternative, we could
2560 * save the original BIO for tls->ssl in the tor_tls_t structure, but
2561 * that would be tempting fate. */
2562 wbio = SSL_get_wbio(tls->ssl);
2563 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
2564 wbio = tmpbio;
2565 w = BIO_number_written(wbio);
2567 /* We are ok with letting these unsigned ints go "negative" here:
2568 * If we wrapped around, this should still give us the right answer, unless
2569 * we wrapped around by more than ULONG_MAX since the last time we called
2570 * this function.
2572 *n_read = (size_t)(r - tls->last_read_count);
2573 *n_written = (size_t)(w - tls->last_write_count);
2574 if (*n_read > INT_MAX || *n_written > INT_MAX) {
2575 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
2576 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
2577 r, tls->last_read_count, w, tls->last_write_count);
2579 total_bytes_written_by_tls += *n_written;
2580 tls->last_read_count = r;
2581 tls->last_write_count = w;
2584 /** Return a ratio of the bytes that TLS has sent to the bytes that we've told
2585 * it to send. Used to track whether our TLS records are getting too tiny. */
2586 double
2587 tls_get_write_overhead_ratio(void)
2589 if (total_bytes_written_over_tls == 0)
2590 return 1.0;
2592 return U64_TO_DBL(total_bytes_written_by_tls) /
2593 U64_TO_DBL(total_bytes_written_over_tls);
2596 /** Implement check_no_tls_errors: If there are any pending OpenSSL
2597 * errors, log an error message. */
2598 void
2599 check_no_tls_errors_(const char *fname, int line)
2601 if (ERR_peek_error() == 0)
2602 return;
2603 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
2604 tor_fix_source_file(fname), line);
2605 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
2608 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
2609 * TLS handshake. Output is undefined if the handshake isn't finished. */
2611 tor_tls_used_v1_handshake(tor_tls_t *tls)
2613 if (tls->isServer) {
2614 #ifdef V2_HANDSHAKE_SERVER
2615 return ! tls->wasV2Handshake;
2616 #endif
2617 } else {
2618 #ifdef V2_HANDSHAKE_CLIENT
2619 return ! tls->wasV2Handshake;
2620 #endif
2622 return 1;
2625 /** Return true iff <b>name</b> is a DN of a kind that could only
2626 * occur in a v3-handshake-indicating certificate */
2627 static int
2628 dn_indicates_v3_cert(X509_NAME *name)
2630 #ifdef DISABLE_V3_LINKPROTO_CLIENTSIDE
2631 (void)name;
2632 return 0;
2633 #else
2634 X509_NAME_ENTRY *entry;
2635 int n_entries;
2636 ASN1_OBJECT *obj;
2637 ASN1_STRING *str;
2638 unsigned char *s;
2639 int len, r;
2641 n_entries = X509_NAME_entry_count(name);
2642 if (n_entries != 1)
2643 return 1; /* More than one entry in the DN. */
2644 entry = X509_NAME_get_entry(name, 0);
2646 obj = X509_NAME_ENTRY_get_object(entry);
2647 if (OBJ_obj2nid(obj) != OBJ_txt2nid("commonName"))
2648 return 1; /* The entry isn't a commonName. */
2650 str = X509_NAME_ENTRY_get_data(entry);
2651 len = ASN1_STRING_to_UTF8(&s, str);
2652 if (len < 0)
2653 return 0;
2654 r = fast_memneq(s + len - 4, ".net", 4);
2655 OPENSSL_free(s);
2656 return r;
2657 #endif
2660 /** Return true iff the peer certificate we're received on <b>tls</b>
2661 * indicates that this connection should use the v3 (in-protocol)
2662 * authentication handshake.
2664 * Only the connection initiator should use this, and only once the initial
2665 * handshake is done; the responder detects a v1 handshake by cipher types,
2666 * and a v3/v2 handshake by Versions cell vs renegotiation.
2669 tor_tls_received_v3_certificate(tor_tls_t *tls)
2671 X509 *cert = SSL_get_peer_certificate(tls->ssl);
2672 EVP_PKEY *key = NULL;
2673 X509_NAME *issuer_name, *subject_name;
2674 int is_v3 = 0;
2676 if (!cert) {
2677 log_warn(LD_BUG, "Called on a connection with no peer certificate");
2678 goto done;
2681 subject_name = X509_get_subject_name(cert);
2682 issuer_name = X509_get_issuer_name(cert);
2684 if (X509_name_cmp(subject_name, issuer_name) == 0) {
2685 is_v3 = 1; /* purportedly self signed */
2686 goto done;
2689 if (dn_indicates_v3_cert(subject_name) ||
2690 dn_indicates_v3_cert(issuer_name)) {
2691 is_v3 = 1; /* DN is fancy */
2692 goto done;
2695 key = X509_get_pubkey(cert);
2696 if (EVP_PKEY_bits(key) != 1024 ||
2697 EVP_PKEY_type(key->type) != EVP_PKEY_RSA) {
2698 is_v3 = 1; /* Key is fancy */
2699 goto done;
2702 done:
2703 if (key)
2704 EVP_PKEY_free(key);
2705 if (cert)
2706 X509_free(cert);
2708 return is_v3;
2711 /** Return the number of server handshakes that we've noticed doing on
2712 * <b>tls</b>. */
2714 tor_tls_get_num_server_handshakes(tor_tls_t *tls)
2716 return tls->server_handshake_count;
2719 /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
2720 * request it was waiting for. */
2722 tor_tls_server_got_renegotiate(tor_tls_t *tls)
2724 return tls->got_renegotiate;
2727 /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
2728 * the v3 handshake to prove that the client knows the TLS secrets for the
2729 * connection <b>tls</b>. Return 0 on success, -1 on failure.
2732 tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
2734 #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
2735 char buf[128];
2736 size_t len;
2737 tor_assert(tls);
2738 tor_assert(tls->ssl);
2739 tor_assert(tls->ssl->s3);
2740 tor_assert(tls->ssl->session);
2742 The value is an HMAC, using the TLS master key as the HMAC key, of
2743 client_random | server_random | TLSSECRET_MAGIC
2745 memcpy(buf + 0, tls->ssl->s3->client_random, 32);
2746 memcpy(buf + 32, tls->ssl->s3->server_random, 32);
2747 memcpy(buf + 64, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
2748 len = 64 + strlen(TLSSECRET_MAGIC) + 1;
2749 crypto_hmac_sha256((char*)secrets_out,
2750 (char*)tls->ssl->session->master_key,
2751 tls->ssl->session->master_key_length,
2752 buf, len);
2753 memwipe(buf, 0, sizeof(buf));
2754 return 0;
2757 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
2758 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
2759 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
2760 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
2761 * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
2762 void
2763 tor_tls_get_buffer_sizes(tor_tls_t *tls,
2764 size_t *rbuf_capacity, size_t *rbuf_bytes,
2765 size_t *wbuf_capacity, size_t *wbuf_bytes)
2767 if (tls->ssl->s3->rbuf.buf)
2768 *rbuf_capacity = tls->ssl->s3->rbuf.len;
2769 else
2770 *rbuf_capacity = 0;
2771 if (tls->ssl->s3->wbuf.buf)
2772 *wbuf_capacity = tls->ssl->s3->wbuf.len;
2773 else
2774 *wbuf_capacity = 0;
2775 *rbuf_bytes = tls->ssl->s3->rbuf.left;
2776 *wbuf_bytes = tls->ssl->s3->wbuf.left;
2779 #ifdef USE_BUFFEREVENTS
2780 /** Construct and return an TLS-encrypting bufferevent to send data over
2781 * <b>socket</b>, which must match the socket of the underlying bufferevent
2782 * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
2784 * This function will either create a filtering bufferevent that wraps around
2785 * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
2786 * uses the <b>tls</b> to talk to the network directly. Do not use
2787 * <b>bufev_in</b> after calling this function.
2789 * The connection will start out doing a server handshake if <b>receiving</b>
2790 * is strue, and a client handshake otherwise.
2792 * Returns NULL on failure.
2794 struct bufferevent *
2795 tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
2796 evutil_socket_t socket, int receiving,
2797 int filter)
2799 struct bufferevent *out;
2800 const enum bufferevent_ssl_state state = receiving ?
2801 BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
2803 if (filter || tor_libevent_using_iocp_bufferevents()) {
2804 /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
2805 means that the SSL will get freed too.
2807 This increment makes our SSL usage not-threadsafe, BTW. We should
2808 see if we're allowed to use CRYPTO_add from outside openssl. */
2809 tls->ssl->references += 1;
2810 out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
2811 bufev_in,
2812 tls->ssl,
2813 state,
2814 BEV_OPT_DEFER_CALLBACKS|
2815 BEV_OPT_CLOSE_ON_FREE);
2816 /* Tell the underlying bufferevent when to accept more data from the SSL
2817 filter (only when it's got less than 32K to write), and when to notify
2818 the SSL filter that it could write more (when it drops under 24K). */
2819 bufferevent_setwatermark(bufev_in, EV_WRITE, 24*1024, 32*1024);
2820 } else {
2821 if (bufev_in) {
2822 evutil_socket_t s = bufferevent_getfd(bufev_in);
2823 tor_assert(s == -1 || s == socket);
2824 tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
2825 tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
2826 tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
2827 tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
2828 bufferevent_free(bufev_in);
2831 /* Current versions (as of 2.0.x) of Libevent need to defer
2832 * bufferevent_openssl callbacks, or else our callback functions will
2833 * get called reentrantly, which is bad for us.
2835 out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
2836 socket,
2837 tls->ssl,
2838 state,
2839 BEV_OPT_DEFER_CALLBACKS);
2841 tls->state = TOR_TLS_ST_BUFFEREVENT;
2843 /* Unblock _after_ creating the bufferevent, since accept/connect tend to
2844 * clear flags. */
2845 tor_tls_unblock_renegotiation(tls);
2847 return out;
2849 #endif