tortls.c 77.8 KB
Newer Older
1
2
/* Copyright (c) 2003, Roger Dingledine.
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Nick Mathewson's avatar
Nick Mathewson committed
3
 * Copyright (c) 2007-2016, The Tor Project, Inc. */
4
5
/* See LICENSE for licensing information */

Nick Mathewson's avatar
Nick Mathewson committed
6
7
/**
 * \file tortls.c
8
9
 * \brief Wrapper functions to present a consistent interface to
 * TLS, SSL, and X.509 functions from OpenSSL.
Nick Mathewson's avatar
Nick Mathewson committed
10
 **/
11

Nick Mathewson's avatar
Nick Mathewson committed
12
/* (Unlike other tor functions, these
13
14
 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
 * functions and variables.)
Nick Mathewson's avatar
Nick Mathewson committed
15
 */
16

17
#include "orconfig.h"
18

19
20
#define TORTLS_PRIVATE

21
#include <assert.h>
22
#ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
Nick Mathewson's avatar
Nick Mathewson committed
23
24
  #include <winsock2.h>
  #include <ws2tcpip.h>
25
#endif
26

27
#include "compat.h"
28

29
30
/* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
 * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
31
DISABLE_GCC_WARNING(redundant-decls)
32

33
34
35
#include <openssl/opensslv.h>
#include "crypto.h"

36
37
38
#ifdef OPENSSL_NO_EC
#error "We require OpenSSL with ECC support"
#endif
39

40
#include <openssl/ssl.h>
41
#include <openssl/ssl3.h>
42
43
44
45
#include <openssl/err.h>
#include <openssl/tls1.h>
#include <openssl/asn1.h>
#include <openssl/bio.h>
46
47
#include <openssl/bn.h>
#include <openssl/rsa.h>
48

49
ENABLE_GCC_WARNING(redundant-decls)
50

Ola Bini's avatar
Ola Bini committed
51
#define TORTLS_PRIVATE
52
53
#include "tortls.h"
#include "util.h"
Nick Mathewson's avatar
Nick Mathewson committed
54
#include "torlog.h"
55
#include "container.h"
56
#include <string.h>
57

58
59
60
61
62
#define X509_get_notBefore_const(cert) \
  ((const ASN1_TIME*) X509_get_notBefore((X509 *)cert))
#define X509_get_notAfter_const(cert) \
  ((const ASN1_TIME*) X509_get_notAfter((X509 *)cert))

63
/* Copied from or.h */
64
65
#define LEGAL_NICKNAME_CHARACTERS \
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
66

Nick Mathewson's avatar
Nick Mathewson committed
67
/** How long do identity certificates live? (sec) */
68
#define IDENTITY_CERT_LIFETIME  (365*24*60*60)
Nick Mathewson's avatar
Nick Mathewson committed
69

70
71
#define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")

72
73
#if OPENSSL_VERSION_NUMBER <  OPENSSL_V(1,0,0,'f')
/* This is a version of OpenSSL before 1.0.0f. It does not have
74
 * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
75
76
77
78
79
 * SSL3 safely at the same time.
 */
#define DISABLE_SSL3_HANDSHAKE
#endif

80
81
82
83
84
85
86
87
88
89
90
/* We redefine these so that we can run correctly even if the vendor gives us
 * a version of OpenSSL that does not match its header files.  (Apple: I am
 * looking at you.)
 */
#ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
#define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
#endif
#ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
#define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
#endif

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/** Return values for tor_tls_classify_client_ciphers.
 *
 * @{
 */
/** An error occurred when examining the client ciphers */
#define CIPHERS_ERR -1
/** The client cipher list indicates that a v1 handshake was in use. */
#define CIPHERS_V1 1
/** The client cipher list indicates that the client is using the v2 or the
 * v3 handshake, but that it is (probably!) lying about what ciphers it
 * supports */
#define CIPHERS_V2 2
/** The client cipher list indicates that the client is using the v2 or the
 * v3 handshake, and that it is telling the truth about what ciphers it
 * supports */
#define CIPHERS_UNRESTRICTED 3
/** @} */

109
110
/** The ex_data index in which we store a pointer to an SSL object's
 * corresponding tor_tls_t object. */
Ola Bini's avatar
Ola Bini committed
111
STATIC int tor_tls_object_ex_data_index = -1;
112
113

/** Helper: Allocate tor_tls_object_ex_data_index. */
Ola Bini's avatar
Ola Bini committed
114
STATIC void
115
tor_tls_allocate_tor_tls_object_ex_data_index(void)
116
117
118
119
120
121
122
123
{
  if (tor_tls_object_ex_data_index == -1) {
    tor_tls_object_ex_data_index =
      SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
    tor_assert(tor_tls_object_ex_data_index != -1);
  }
}

124
125
/** Helper: given a SSL* pointer, return the tor_tls_t object using that
 * pointer. */
126
STATIC tor_tls_t *
127
tor_tls_get_by_ssl(const SSL *ssl)
128
{
129
130
131
132
  tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
  if (result)
    tor_assert(result->magic == TOR_TLS_MAGIC);
  return result;
133
134
}

135
136
static void tor_tls_context_decref(tor_tls_context_t *ctx);
static void tor_tls_context_incref(tor_tls_context_t *ctx);
Ola Bini's avatar
Ola Bini committed
137

138
static int check_cert_lifetime_internal(int severity, const X509 *cert,
139
                                   int past_tolerance, int future_tolerance);
140

141
/** Global TLS contexts. We keep them here because nobody else needs
Nick Mathewson's avatar
Nick Mathewson committed
142
143
144
 * to touch them.
 *
 * @{ */
Ola Bini's avatar
Ola Bini committed
145
146
STATIC tor_tls_context_t *server_tls_context = NULL;
STATIC tor_tls_context_t *client_tls_context = NULL;
Nick Mathewson's avatar
Nick Mathewson committed
147
/**@}*/
148

Nick Mathewson's avatar
Nick Mathewson committed
149
/** True iff tor_tls_init() has been called. */
150
static int tls_library_is_initialized = 0;
151

152
/* Module-internal error codes. */
153
154
#define TOR_TLS_SYSCALL_    (MIN_TOR_TLS_ERROR_VAL_ - 2)
#define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
155

156
157
/** Write a description of the current state of <b>tls</b> into the
 * <b>sz</b>-byte buffer at <b>buf</b>. */
158
159
160
161
162
163
164
165
166
167
168
void
tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
{
  const char *ssl_state;
  const char *tortls_state;

  if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
    strlcpy(buf, "(No SSL object)", sz);
    return;
  }

169
  ssl_state = SSL_state_string_long(tls->ssl);
170
  switch (tls->state) {
171
#define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
172
173
174
175
176
177
178
    CASE(HANDSHAKE);
    CASE(OPEN);
    CASE(GOTCLOSE);
    CASE(SENTCLOSE);
    CASE(CLOSED);
    CASE(RENEGOTIATE);
#undef CASE
179
180
181
  case TOR_TLS_ST_BUFFEREVENT:
    tortls_state = "";
    break;
182
  default:
183
    tortls_state = " in unknown TLS state";
184
185
186
    break;
  }

187
  tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
188
189
}

Nick Mathewson's avatar
Nick Mathewson committed
190
191
192
/** Log a single error <b>err</b> as returned by ERR_get_error(), which was
 * received while performing an operation <b>doing</b> on <b>tls</b>.  Log
 * the message at <b>severity</b>, in log domain <b>domain</b>. */
193
194
195
196
197
198
199
void
tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
                  int severity, int domain, const char *doing)
{
  const char *state = NULL, *addr;
  const char *msg, *lib, *func;

200
  state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
201
202
203

  addr = tls ? tls->address : NULL;

204
205
206
207
208
209
210
  /* Some errors are known-benign, meaning they are the fault of the other
   * side of the connection. The caller doesn't know this, so override the
   * priority for those cases. */
  switch (ERR_GET_REASON(err)) {
    case SSL_R_HTTP_REQUEST:
    case SSL_R_HTTPS_PROXY_REQUEST:
    case SSL_R_RECORD_LENGTH_MISMATCH:
211
#ifndef OPENSSL_1_1_API
212
    case SSL_R_RECORD_TOO_LARGE:
213
#endif
214
215
216
217
218
219
220
221
    case SSL_R_UNKNOWN_PROTOCOL:
    case SSL_R_UNSUPPORTED_PROTOCOL:
      severity = LOG_INFO;
      break;
    default:
      break;
  }

222
223
224
225
226
227
228
  msg = (const char*)ERR_reason_error_string(err);
  lib = (const char*)ERR_lib_error_string(err);
  func = (const char*)ERR_func_error_string(err);
  if (!msg) msg = "(null)";
  if (!lib) lib = "(null)";
  if (!func) func = "(null)";
  if (doing) {
229
    tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
230
231
232
        doing, addr?" with ":"", addr?addr:"",
        msg, lib, func, state);
  } else {
233
    tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
234
235
236
237
238
        addr?" with ":"", addr?addr:"",
        msg, lib, func, state);
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
239
240
/** Log all pending tls errors at level <b>severity</b> in log domain
 * <b>domain</b>.  Use <b>doing</b> to describe our current activities.
241
 */
Ola Bini's avatar
Ola Bini committed
242
STATIC void
243
tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
Nick Mathewson's avatar
Nick Mathewson committed
244
{
245
  unsigned long err;
246

Nick Mathewson's avatar
Nick Mathewson committed
247
  while ((err = ERR_get_error()) != 0) {
248
    tor_tls_log_one_error(tls, err, severity, domain, doing);
Nick Mathewson's avatar
Nick Mathewson committed
249
250
  }
}
251

252
253
/** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
 * code. */
Ola Bini's avatar
Ola Bini committed
254
STATIC int
255
256
257
tor_errno_to_tls_error(int e)
{
  switch (e) {
258
    case SOCK_ERRNO(ECONNRESET): // most common
259
      return TOR_TLS_ERROR_CONNRESET;
260
    case SOCK_ERRNO(ETIMEDOUT):
261
      return TOR_TLS_ERROR_TIMEOUT;
262
263
    case SOCK_ERRNO(EHOSTUNREACH):
    case SOCK_ERRNO(ENETUNREACH):
264
      return TOR_TLS_ERROR_NO_ROUTE;
265
    case SOCK_ERRNO(ECONNREFUSED):
266
267
268
269
270
271
      return TOR_TLS_ERROR_CONNREFUSED; // least common
    default:
      return TOR_TLS_ERROR_MISC;
  }
}

272
/** Given a TOR_TLS_* error code, return a string equivalent. */
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const char *
tor_tls_err_to_string(int err)
{
  if (err >= 0)
    return "[Not an error.]";
  switch (err) {
    case TOR_TLS_ERROR_MISC: return "misc error";
    case TOR_TLS_ERROR_IO: return "unexpected close";
    case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
    case TOR_TLS_ERROR_CONNRESET: return "connection reset";
    case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
    case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
    case TOR_TLS_CLOSE: return "closed";
    case TOR_TLS_WANTREAD: return "want to read";
    case TOR_TLS_WANTWRITE: return "want to write";
    default: return "(unknown error code)";
  }
}

292
293
294
#define CATCH_SYSCALL 1
#define CATCH_ZERO    2

Nick Mathewson's avatar
Nick Mathewson committed
295
/** Given a TLS object and the result of an SSL_* call, use
296
297
 * SSL_get_error to determine whether an error has occurred, and if so
 * which one.  Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
298
 * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
299
 * reporting syscall errors.  If extra&CATCH_ZERO is true, return
300
 * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
301
 *
Nick Mathewson's avatar
Nick Mathewson committed
302
303
 * If an error has occurred, log it at level <b>severity</b> and describe the
 * current action as <b>doing</b>.
304
 */
Ola Bini's avatar
Ola Bini committed
305
STATIC int
306
tor_tls_get_error(tor_tls_t *tls, int r, int extra,
307
                  const char *doing, int severity, int domain)
308
309
{
  int err = SSL_get_error(tls->ssl, r);
310
  int tor_error = TOR_TLS_ERROR_MISC;
311
312
313
314
315
316
317
318
  switch (err) {
    case SSL_ERROR_NONE:
      return TOR_TLS_DONE;
    case SSL_ERROR_WANT_READ:
      return TOR_TLS_WANTREAD;
    case SSL_ERROR_WANT_WRITE:
      return TOR_TLS_WANTWRITE;
    case SSL_ERROR_SYSCALL:
319
      if (extra&CATCH_SYSCALL)
320
        return TOR_TLS_SYSCALL_;
321
      if (r == 0) {
322
        tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
323
            doing, SSL_state_string_long(tls->ssl));
324
325
        tor_error = TOR_TLS_ERROR_IO;
      } else {
326
        int e = tor_socket_errno(tls->socket);
327
        tor_log(severity, LD_NET,
328
329
            "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
            doing, e, tor_socket_strerror(e),
330
            SSL_state_string_long(tls->ssl));
331
        tor_error = tor_errno_to_tls_error(e);
332
      }
333
      tls_log_errors(tls, severity, domain, doing);
334
      return tor_error;
335
    case SSL_ERROR_ZERO_RETURN:
336
      if (extra&CATCH_ZERO)
337
        return TOR_TLS_ZERORETURN_;
338
      tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
339
          doing, SSL_state_string_long(tls->ssl));
340
      tls_log_errors(tls, severity, domain, doing);
341
      return TOR_TLS_CLOSE;
342
    default:
343
      tls_log_errors(tls, severity, domain, doing);
344
      return TOR_TLS_ERROR_MISC;
345
346
347
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
348
/** Initialize OpenSSL, unless it has already been initialized.
349
 */
350
static void
351
352
tor_tls_init(void)
{
353
354
  check_no_tls_errors();

355
356
  if (!tls_library_is_initialized) {
    SSL_library_init();
357
    SSL_load_error_strings();
358

359
360
#if (SIZEOF_VOID_P >= 8 &&                              \
     OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
361
    long version = OpenSSL_version_num();
362

Nick Mathewson's avatar
Nick Mathewson committed
363
    /* LCOV_EXCL_START : we can't test these lines on the same machine */
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    if (version >= OPENSSL_V_SERIES(1,0,1)) {
      /* Warn if we could *almost* be running with much faster ECDH.
         If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
         don't have one of the built-in __uint128-based speedups, we are
         just one build operation away from an accelerated handshake.

         (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
          doing this test, but that gives compile-time options, not runtime
          behavior.)
      */
      EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
      const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
      const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
      const int warn = (m == EC_GFp_simple_method() ||
                        m == EC_GFp_mont_method() ||
                        m == EC_GFp_nist_method());
      EC_KEY_free(key);

      if (warn)
        log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
                   "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
                   "that apparently lacks accelerated support for the NIST "
                   "P-224 and P-256 groups. Building openssl with such "
                   "support (using the enable-ec_nistp_64_gcc_128 option "
388
                   "when configuring it) would make ECDH much faster.");
389
    }
Ola Bini's avatar
Ola Bini committed
390
    /* LCOV_EXCL_STOP */
391
392
#endif

393
394
    tor_tls_allocate_tor_tls_object_ex_data_index();

395
396
397
398
    tls_library_is_initialized = 1;
  }
}

399
/** Free all global TLS structures. */
400
401
402
void
tor_tls_free_all(void)
{
403
404
  check_no_tls_errors();

405
406
407
408
409
410
411
412
413
  if (server_tls_context) {
    tor_tls_context_t *ctx = server_tls_context;
    server_tls_context = NULL;
    tor_tls_context_decref(ctx);
  }
  if (client_tls_context) {
    tor_tls_context_t *ctx = client_tls_context;
    client_tls_context = NULL;
    tor_tls_context_decref(ctx);
414
415
416
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
417
/** We need to give OpenSSL a callback to verify certificates. This is
418
419
420
 * it: We always accept peer certs and complete the handshake.  We
 * don't validate them until later.
 */
Ola Bini's avatar
Ola Bini committed
421
STATIC int
422
423
always_accept_verify_cb(int preverify_ok,
                        X509_STORE_CTX *x509_ctx)
424
{
425
426
  (void) preverify_ok;
  (void) x509_ctx;
427
428
429
  return 1;
}

Roger Dingledine's avatar
Roger Dingledine committed
430
/** Return a newly allocated X509 name with commonName <b>cname</b>. */
431
432
433
434
435
static X509_NAME *
tor_x509_name_new(const char *cname)
{
  int nid;
  X509_NAME *name;
Nick Mathewson's avatar
Nick Mathewson committed
436
  /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
437
438
439
440
441
442
  if (!(name = X509_NAME_new()))
    return NULL;
  if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
                                   (unsigned char*)cname, -1, -1, 0)))
    goto error;
Ola Bini's avatar
Ola Bini committed
443
  /* LCOV_EXCL_BR_STOP */
444
445
  return name;
 error:
Nick Mathewson's avatar
Nick Mathewson committed
446
  /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
447
448
  X509_NAME_free(name);
  return NULL;
Ola Bini's avatar
Ola Bini committed
449
  /* LCOV_EXCL_STOP */
450
451
}

Nick Mathewson's avatar
Nick Mathewson committed
452
453
454
/** Generate and sign an X509 certificate with the public key <b>rsa</b>,
 * signed by the private key <b>rsa_sign</b>.  The commonName of the
 * certificate will be <b>cname</b>; the commonName of the issuer will be
455
456
457
458
 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
 * seconds, starting from some time in the past.
 *
 * Return a certificate on success, NULL on failure.
459
 */
Ola Bini's avatar
Ola Bini committed
460
461
462
463
464
465
MOCK_IMPL(STATIC X509 *,
          tor_tls_create_certificate,(crypto_pk_t *rsa,
                                      crypto_pk_t *rsa_sign,
                                      const char *cname,
                                      const char *cname_sign,
                                      unsigned int cert_lifetime))
466
{
Nick Mathewson's avatar
Nick Mathewson committed
467
468
  /* OpenSSL generates self-signed certificates with random 64-bit serial
   * numbers, so let's do that too. */
469
470
#define SERIAL_NUMBER_SIZE 8

471
  time_t start_time, end_time;
472
473
  BIGNUM *serial_number = NULL;
  unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
474
  EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
475
  X509 *x509 = NULL;
476
  X509_NAME *name = NULL, *name_issuer=NULL;
477

478
479
  tor_tls_init();

480
481
482
483
  /* Make sure we're part-way through the certificate lifetime, rather
   * than having it start right now. Don't choose quite uniformly, since
   * then we might pick a time where we're about to expire. Lastly, be
   * sure to start on a day boundary. */
484
  time_t now = time(NULL);
Nick Mathewson's avatar
Nick Mathewson committed
485
  start_time = crypto_rand_time_range(now - cert_lifetime, now) + 2*24*3600;
486
  start_time -= start_time % (24*3600);
487

488
489
490
491
  tor_assert(rsa);
  tor_assert(cname);
  tor_assert(rsa_sign);
  tor_assert(cname_sign);
492
  if (!(sign_pkey = crypto_pk_get_evp_pkey_(rsa_sign,1)))
493
    goto error;
494
  if (!(pkey = crypto_pk_get_evp_pkey_(rsa,0)))
495
    goto error;
Nick Mathewson's avatar
Nick Mathewson committed
496
  if (!(x509 = X509_new()))
497
    goto error;
Nick Mathewson's avatar
Nick Mathewson committed
498
  if (!(X509_set_version(x509, 2)))
499
    goto error;
500
501

  { /* our serial number is 8 random bytes. */
502
    crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
Nick Mathewson's avatar
Nick Mathewson committed
503
    if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
Nick Mathewson's avatar
Nick Mathewson committed
504
      goto error;
Nick Mathewson's avatar
Nick Mathewson committed
505
    if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
Nick Mathewson's avatar
Nick Mathewson committed
506
      goto error;
507
  }
508

509
  if (!(name = tor_x509_name_new(cname)))
510
    goto error;
511
512
  if (!(X509_set_subject_name(x509, name)))
    goto error;
513
  if (!(name_issuer = tor_x509_name_new(cname_sign)))
514
    goto error;
515
  if (!(X509_set_issuer_name(x509, name_issuer)))
516
    goto error;
517

518
  if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
519
    goto error;
520
  end_time = start_time + cert_lifetime;
521
  if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
522
    goto error;
523
  if (!X509_set_pubkey(x509, pkey))
524
    goto error;
525
  if (!X509_sign(x509, sign_pkey, EVP_sha1()))
526
    goto error;
527

528
529
  goto done;
 error:
530
  if (x509) {
531
    X509_free(x509);
532
533
    x509 = NULL;
  }
534
 done:
535
  tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
536
537
  if (sign_pkey)
    EVP_PKEY_free(sign_pkey);
538
539
  if (pkey)
    EVP_PKEY_free(pkey);
540
  if (serial_number)
541
    BN_clear_free(serial_number);
542
543
  if (name)
    X509_NAME_free(name);
544
545
  if (name_issuer)
    X509_NAME_free(name_issuer);
546
  return x509;
547
548

#undef SERIAL_NUMBER_SIZE
549
550
}

551
552
/** List of ciphers that servers should select from when the client might be
 * claiming extra unsupported ciphers in order to avoid fingerprinting.  */
553
554
555
556
557
558
559
560
561
562
563
static const char SERVER_CIPHER_LIST[] =
#ifdef  TLS1_3_TXT_AES_128_GCM_SHA256
  /* This one can never actually get selected, since if the client lists it,
   * we will assume that the client is honest, and not use this list.
   * Nonetheless we list it if it's available, so that the server doesn't
   * conclude that it has no valid ciphers if it's running with TLS1.3.
   */
  TLS1_3_TXT_AES_128_GCM_SHA256 ":"
#endif
  TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
  TLS1_TXT_DHE_RSA_WITH_AES_128_SHA;
564
565
566

/** List of ciphers that servers should select from when we actually have
 * our choice of what cipher to use. */
567
static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
568
569
570
571
572
573
574
575
576
577
578
579
580
581
  /* Here are the TLS 1.3 ciphers we like, in the order we prefer. */
#ifdef TLS1_3_TXT_AES_256_GCM_SHA384
  TLS1_3_TXT_AES_256_GCM_SHA384 ":"
#endif
#ifdef TLS1_3_TXT_CHACHA20_POLY1305_SHA256
  TLS1_3_TXT_CHACHA20_POLY1305_SHA256 ":"
#endif
#ifdef TLS1_3_TXT_AES_128_GCM_SHA256
  TLS1_3_TXT_AES_128_GCM_SHA256 ":"
#endif
#ifdef TLS1_3_TXT_AES_128_CCM_SHA256
  TLS1_3_TXT_AES_128_CCM_SHA256 ":"
#endif

582
583
  /* This list is autogenerated with the gen_server_ciphers.py script;
   * don't hand-edit it. */
584
585
586
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
       TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
#endif
587
588
589
590
591
592
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
       TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
#endif
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
       TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
#endif
593
594
595
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
       TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
#endif
596
597
598
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
       TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
#endif
599
600
601
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
       TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
#endif
602
603
604
605
606
607
608
609
610
611
612
#ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
       TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
#endif
#ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
       TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
#endif
#ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
       TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
#endif
#ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
       TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
613
#endif
614
615
616
       /* Required */
       TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
       /* Required */
617
618
       TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
       ;
619

620
621
622
/* Note: to set up your own private testing network with link crypto
 * disabled, set your Tors' cipher list to
 * (SSL3_TXT_RSA_NULL_SHA).  If you do this, you won't be able to communicate
623
624
 * with any of the "real" Tors, though. */

625
626
627
#define CIPHER(id, name) name ":"
#define XCIPHER(id, name)
/** List of ciphers that clients should advertise, omitting items that
628
 * our OpenSSL doesn't know about. */
629
static const char CLIENT_CIPHER_LIST[] =
630
#include "ciphers.inc"
631
632
633
  /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
   * of any cipher we say. */
  "!SSLv2"
634
635
636
637
  ;
#undef CIPHER
#undef XCIPHER

638
639
/** Free all storage held in <b>cert</b> */
void
640
tor_x509_cert_free(tor_x509_cert_t *cert)
641
642
643
644
645
646
{
  if (! cert)
    return;
  if (cert->cert)
    X509_free(cert->cert);
  tor_free(cert->encoded);
647
  memwipe(cert, 0x03, sizeof(*cert));
Ola Bini's avatar
Ola Bini committed
648
  /* LCOV_EXCL_BR_START since cert will never be NULL here */
649
  tor_free(cert);
Ola Bini's avatar
Ola Bini committed
650
  /* LCOV_EXCL_BR_STOP */
651
652
653
}

/**
654
 * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
655
656
657
 *
 * Steals a reference to x509_cert.
 */
Ola Bini's avatar
Ola Bini committed
658
659
MOCK_IMPL(STATIC tor_x509_cert_t *,
          tor_x509_cert_new,(X509 *x509_cert))
660
{
661
  tor_x509_cert_t *cert;
662
663
  EVP_PKEY *pkey;
  RSA *rsa;
664
665
  int length;
  unsigned char *buf = NULL;
666

667
668
669
  if (!x509_cert)
    return NULL;

670
  length = i2d_X509(x509_cert, &buf);
671
  cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
Nick Mathewson's avatar
Nick Mathewson committed
672
  if (length <= 0 || buf == NULL) {
Ola Bini's avatar
Ola Bini committed
673
    /* LCOV_EXCL_START for the same reason as the exclusion above */
674
675
676
677
    tor_free(cert);
    log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
    X509_free(x509_cert);
    return NULL;
Ola Bini's avatar
Ola Bini committed
678
    /* LCOV_EXCL_STOP */
679
680
  }
  cert->encoded_len = (size_t) length;
681
682
683
  cert->encoded = tor_malloc(length);
  memcpy(cert->encoded, buf, length);
  OPENSSL_free(buf);
684
685
686

  cert->cert = x509_cert;

687
  crypto_common_digests(&cert->cert_digests,
688
689
690
691
                    (char*)cert->encoded, cert->encoded_len);

  if ((pkey = X509_get_pubkey(x509_cert)) &&
      (rsa = EVP_PKEY_get1_RSA(pkey))) {
692
    crypto_pk_t *pk = crypto_new_pk_from_rsa_(rsa);
Nick Mathewson's avatar
Nick Mathewson committed
693
    crypto_pk_get_common_digests(pk, &cert->pkey_digests);
694
    cert->pkey_digests_set = 1;
695
    crypto_pk_free(pk);
696
697
698
699
700
701
    EVP_PKEY_free(pkey);
  }

  return cert;
}

702
703
704
705
706
707
708
709
710
/** Return a new copy of <b>cert</b>. */
tor_x509_cert_t *
tor_x509_cert_dup(const tor_x509_cert_t *cert)
{
  tor_assert(cert);
  X509 *x509 = cert->cert;
  return tor_x509_cert_new(X509_dup(x509));
}

711
/** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
712
713
 * from a <b>certificate</b>.  Return a newly allocated tor_x509_cert_t on
 * success and NULL on failure. */
714
715
tor_x509_cert_t *
tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
716
717
718
{
  X509 *x509;
  const unsigned char *cp = (const unsigned char *)certificate;
719
  tor_x509_cert_t *newcert;
720
  tor_assert(certificate);
721
  check_no_tls_errors();
722
723

  if (certificate_len > INT_MAX)
724
    goto err;
725
726

  x509 = d2i_X509(NULL, &cp, (int)certificate_len);
727

728
  if (!x509)
729
    goto err; /* Couldn't decode */
730
731
  if (cp - certificate != (int)certificate_len) {
    X509_free(x509);
732
    goto err; /* Didn't use all the bytes */
733
  }
734
  newcert = tor_x509_cert_new(x509);
735
  if (!newcert) {
736
    goto err;
737
738
739
740
  }
  if (newcert->encoded_len != certificate_len ||
      fast_memneq(newcert->encoded, certificate, certificate_len)) {
    /* Cert wasn't in DER */
741
    tor_x509_cert_free(newcert);
742
    goto err;
743
744
  }
  return newcert;
745
746
747
 err:
  tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
  return NULL;
748
749
}

750
/** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
751
752
 * representation and length, respectively. */
void
753
tor_x509_cert_get_der(const tor_x509_cert_t *cert,
754
755
756
757
758
759
760
761
762
                 const uint8_t **encoded_out, size_t *size_out)
{
  tor_assert(cert);
  tor_assert(encoded_out);
  tor_assert(size_out);
  *encoded_out = cert->encoded;
  *size_out = cert->encoded_len;
}

763
764
/** Return a set of digests for the public key in <b>cert</b>, or NULL if this
 * cert's public key is not one we know how to take the digest of. */
765
const common_digests_t *
766
tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
767
{
768
769
770
771
  if (cert->pkey_digests_set)
    return &cert->pkey_digests;
  else
    return NULL;
772
773
774
}

/** Return a set of digests for the public key in <b>cert</b>. */
775
const common_digests_t *
776
tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
777
778
779
780
{
  return &cert->cert_digests;
}

781
782
/** Remove a reference to <b>ctx</b>, and free it if it has no more
 * references. */
783
static void
784
tor_tls_context_decref(tor_tls_context_t *ctx)
785
{
786
787
788
  tor_assert(ctx);
  if (--ctx->refcnt == 0) {
    SSL_CTX_free(ctx->ctx);
789
790
791
    tor_x509_cert_free(ctx->my_link_cert);
    tor_x509_cert_free(ctx->my_id_cert);
    tor_x509_cert_free(ctx->my_auth_cert);
792
793
    crypto_pk_free(ctx->link_key);
    crypto_pk_free(ctx->auth_key);
Ola Bini's avatar
Ola Bini committed
794
    /* LCOV_EXCL_BR_START since ctx will never be NULL here */
795
    tor_free(ctx);
Ola Bini's avatar
Ola Bini committed
796
    /* LCOV_EXCL_BR_STOP */
797
798
799
  }
}

800
801
802
803
804
805
806
/** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
 * and ID certificate that we're currently using for our V3 in-protocol
 * handshake's certificate chain.  If <b>server</b> is true, provide the certs
 * that we use in server mode; otherwise, provide the certs that we use in
 * client mode. */
int
tor_tls_get_my_certs(int server,
807
808
                     const tor_x509_cert_t **link_cert_out,
                     const tor_x509_cert_t **id_cert_out)
809
810
811
812
813
{
  tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
  if (! ctx)
    return -1;
  if (link_cert_out)
814
    *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
815
816
817
818
819
  if (id_cert_out)
    *id_cert_out = ctx->my_id_cert;
  return 0;
}

820
821
822
823
/**
 * Return the authentication key that we use to authenticate ourselves as a
 * client in the V3 in-protocol handshake.
 */
824
crypto_pk_t *
825
826
827
828
829
830
831
832
tor_tls_get_my_client_auth_key(void)
{
  if (! client_tls_context)
    return NULL;
  return client_tls_context->auth_key;
}

/**
833
834
 * Return a newly allocated copy of the public key that a certificate
 * certifies.  Return NULL if the cert's key is not RSA.
835
 */
836
crypto_pk_t *
837
tor_tls_cert_get_key(tor_x509_cert_t *cert)
838
{
839
  crypto_pk_t *result = NULL;
840
841
842
843
844
845
846
847
848
  EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  RSA *rsa;
  if (!pkey)
    return NULL;
  rsa = EVP_PKEY_get1_RSA(pkey);
  if (!rsa) {
    EVP_PKEY_free(pkey);
    return NULL;
  }
849
  result = crypto_new_pk_from_rsa_(rsa);
850
851
852
853
  EVP_PKEY_free(pkey);
  return result;
}

854
855
856
/** Return true iff the other side of <b>tls</b> has authenticated to us, and
 * the key certified in <b>cert</b> is the same as the key they used to do it.
 */
857
858
MOCK_IMPL(int,
tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
859
{
860
861
862
863
864
  tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
  if (!peer)
    return 0;

  X509 *peercert = peer->cert;
865
866
867
868
869
870
  EVP_PKEY *link_key = NULL, *cert_key = NULL;
  int result;

  link_key = X509_get_pubkey(peercert);
  cert_key = X509_get_pubkey(cert->cert);

871
  result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
872

873
  tor_x509_cert_free(peer);
874
875
876
877
878
879
880
881
  if (link_key)
    EVP_PKEY_free(link_key);
  if (cert_key)
    EVP_PKEY_free(cert_key);

  return result;
}

882
/** Check whether <b>cert</b> is well-formed, currently live, and correctly
883
884
885
886
 * signed by the public key in <b>signing_cert</b>.  If <b>check_rsa_1024</b>,
 * make sure that it has an RSA key with 1024 bits; otherwise, just check that
 * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
 * we couldn't check it. */
887
int
888
tor_tls_cert_is_valid(int severity,
889
890
                      const tor_x509_cert_t *cert,
                      const tor_x509_cert_t *signing_cert,
891
                      int check_rsa_1024)
892
{
893
  check_no_tls_errors();
894
895
  EVP_PKEY *cert_key;
  int r, key_ok = 0;
896

897
  if (!signing_cert || !cert)
898
899
900
    goto bad;

  EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
901
  if (!signing_key)
902
    goto bad;
903
904
905
  r = X509_verify(cert->cert, signing_key);
  EVP_PKEY_free(signing_key);
  if (r <= 0)
906
    goto bad;
907
908
909

  /* okay, the signature checked out right.  Now let's check the check the
   * lifetime. */
910
911
  if (check_cert_lifetime_internal(severity, cert->cert,
                                   48*60*60, 30*24*60*60) < 0)
912
    goto bad;
913

914
915
916
  cert_key = X509_get_pubkey(cert->cert);
  if (check_rsa_1024 && cert_key) {
    RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
917
918
919
#ifdef OPENSSL_1_1_API
    if (rsa && RSA_bits(rsa) == 1024)
#else
920
    if (rsa && BN_num_bits(rsa->n) == 1024)
921
#endif
922
923
924
925
926
927
      key_ok = 1;
    if (rsa)
      RSA_free(rsa);
  } else if (cert_key) {
    int min_bits = 1024;
#ifdef EVP_PKEY_EC
928
    if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
929
930
931
932
933
934
935
      min_bits = 128;
#endif
    if (EVP_PKEY_bits(cert_key) >= min_bits)
      key_ok = 1;
  }
  EVP_PKEY_free(cert_key);
  if (!key_ok)
936
    goto bad;
937

938
939
  /* XXXX compare DNs or anything? */

940
  return 1;
941
942
943
 bad:
  tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
  return 0;
944
945
}

946
/** Increase the reference count of <b>ctx</b>. */
947
948
949
950
static void
tor_tls_context_incref(tor_tls_context_t *ctx)
{
  ++ctx->refcnt;
951
952
}

953
954
955
/** Create new global client and server TLS contexts.
 *
 * If <b>server_identity</b> is NULL, this will not generate a server
956
 * TLS context. If TOR_TLS_CTX_IS_PUBLIC_SERVER is set in <b>flags</b>, use
957
 * the same TLS context for incoming and outgoing connections, and
958
959
960
 * ignore <b>client_identity</b>. If one of TOR_TLS_CTX_USE_ECDHE_P{224,256}
 * is set in <b>flags</b>, use that ECDHE group if possible; otherwise use
 * the default ECDHE group. */
961
int
962
tor_tls_context_init(unsigned flags,
963
964
                     crypto_pk_t *client_identity,
                     crypto_pk_t *server_identity,
965
966
967
968
                     unsigned int key_lifetime)
{
  int rv1 = 0;
  int rv2 = 0;
969
  const int is_public_server = flags & TOR_TLS_CTX_IS_PUBLIC_SERVER;
970
  check_no_tls_errors();
971
972
973
974
975
976
977
978
979

  if (is_public_server) {
    tor_tls_context_t *new_ctx;
    tor_tls_context_t *old_ctx;

    tor_assert(server_identity != NULL);

    rv1 = tor_tls_context_init_one(&server_tls_context,
                                   server_identity,
980
                                   key_lifetime, flags, 0);
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995

    if (rv1 >= 0) {
      new_ctx = server_tls_context;
      tor_tls_context_incref(new_ctx);
      old_ctx = client_tls_context;
      client_tls_context = new_ctx;

      if (old_ctx != NULL) {
        tor_tls_context_decref(old_ctx);
      }
    }
  } else {
    if (server_identity != NULL) {
      rv1 = tor_tls_context_init_one(&server_tls_context,
                                     server_identity,