/
tortls.c
2553 lines (2310 loc) · 77.7 KB
/
tortls.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2003, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
* Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file tortls.c
* \brief Wrapper functions to present a consistent interface to
* TLS, SSL, and X.509 functions from OpenSSL.
**/
/* (Unlike other tor functions, these
* are prefixed with tor_ in order to avoid conflicting with OpenSSL
* functions and variables.)
*/
#include "orconfig.h"
#define TORTLS_PRIVATE
#include <assert.h>
#ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include "compat.h"
/* 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. */
DISABLE_GCC_WARNING(redundant-decls)
#include <openssl/opensslv.h>
#include "crypto.h"
#ifdef OPENSSL_NO_EC
#error "We require OpenSSL with ECC support"
#endif
#include <openssl/ssl.h>
#include <openssl/ssl3.h>
#include <openssl/err.h>
#include <openssl/tls1.h>
#include <openssl/asn1.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
ENABLE_GCC_WARNING(redundant-decls)
#define TORTLS_PRIVATE
#include "tortls.h"
#include "util.h"
#include "torlog.h"
#include "container.h"
#include <string.h>
#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))
/* Copied from or.h */
#define LEGAL_NICKNAME_CHARACTERS \
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
/** How long do identity certificates live? (sec) */
#define IDENTITY_CERT_LIFETIME (365*24*60*60)
#define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
#if OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f')
/* This is a version of OpenSSL before 1.0.0f. It does not have
* the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
* SSL3 safely at the same time.
*/
#define DISABLE_SSL3_HANDSHAKE
#endif
/* 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
/** 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
/** @} */
/** The ex_data index in which we store a pointer to an SSL object's
* corresponding tor_tls_t object. */
STATIC int tor_tls_object_ex_data_index = -1;
/** Helper: Allocate tor_tls_object_ex_data_index. */
STATIC void
tor_tls_allocate_tor_tls_object_ex_data_index(void)
{
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);
}
}
/** Helper: given a SSL* pointer, return the tor_tls_t object using that
* pointer. */
STATIC tor_tls_t *
tor_tls_get_by_ssl(const SSL *ssl)
{
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;
}
static void tor_tls_context_decref(tor_tls_context_t *ctx);
static void tor_tls_context_incref(tor_tls_context_t *ctx);
static int check_cert_lifetime_internal(int severity, const X509 *cert,
time_t now,
int past_tolerance, int future_tolerance);
/** Global TLS contexts. We keep them here because nobody else needs
* to touch them.
*
* @{ */
STATIC tor_tls_context_t *server_tls_context = NULL;
STATIC tor_tls_context_t *client_tls_context = NULL;
/**@}*/
/** True iff tor_tls_init() has been called. */
static int tls_library_is_initialized = 0;
/* Module-internal error codes. */
#define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
#define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
/** Write a description of the current state of <b>tls</b> into the
* <b>sz</b>-byte buffer at <b>buf</b>. */
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;
}
ssl_state = SSL_state_string_long(tls->ssl);
switch (tls->state) {
#define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
CASE(HANDSHAKE);
CASE(OPEN);
CASE(GOTCLOSE);
CASE(SENTCLOSE);
CASE(CLOSED);
CASE(RENEGOTIATE);
#undef CASE
case TOR_TLS_ST_BUFFEREVENT:
tortls_state = "";
break;
default:
tortls_state = " in unknown TLS state";
break;
}
tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
}
/** 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>. */
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;
state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
addr = tls ? tls->address : NULL;
/* 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:
#ifndef OPENSSL_1_1_API
case SSL_R_RECORD_TOO_LARGE:
#endif
case SSL_R_UNKNOWN_PROTOCOL:
case SSL_R_UNSUPPORTED_PROTOCOL:
severity = LOG_INFO;
break;
default:
break;
}
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) {
tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
doing, addr?" with ":"", addr?addr:"",
msg, lib, func, state);
} else {
tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
addr?" with ":"", addr?addr:"",
msg, lib, func, state);
}
}
/** 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.
*/
STATIC void
tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
{
unsigned long err;
while ((err = ERR_get_error()) != 0) {
tor_tls_log_one_error(tls, err, severity, domain, doing);
}
}
/** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
* code. */
STATIC int
tor_errno_to_tls_error(int e)
{
switch (e) {
case SOCK_ERRNO(ECONNRESET): // most common
return TOR_TLS_ERROR_CONNRESET;
case SOCK_ERRNO(ETIMEDOUT):
return TOR_TLS_ERROR_TIMEOUT;
case SOCK_ERRNO(EHOSTUNREACH):
case SOCK_ERRNO(ENETUNREACH):
return TOR_TLS_ERROR_NO_ROUTE;
case SOCK_ERRNO(ECONNREFUSED):
return TOR_TLS_ERROR_CONNREFUSED; // least common
default:
return TOR_TLS_ERROR_MISC;
}
}
/** Given a TOR_TLS_* error code, return a string equivalent. */
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)";
}
}
#define CATCH_SYSCALL 1
#define CATCH_ZERO 2
/** Given a TLS object and the result of an SSL_* call, use
* SSL_get_error to determine whether an error has occurred, and if so
* which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
* If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
* reporting syscall errors. If extra&CATCH_ZERO is true, return
* TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
*
* If an error has occurred, log it at level <b>severity</b> and describe the
* current action as <b>doing</b>.
*/
STATIC int
tor_tls_get_error(tor_tls_t *tls, int r, int extra,
const char *doing, int severity, int domain)
{
int err = SSL_get_error(tls->ssl, r);
int tor_error = TOR_TLS_ERROR_MISC;
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:
if (extra&CATCH_SYSCALL)
return TOR_TLS_SYSCALL_;
if (r == 0) {
tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
doing, SSL_state_string_long(tls->ssl));
tor_error = TOR_TLS_ERROR_IO;
} else {
int e = tor_socket_errno(tls->socket);
tor_log(severity, LD_NET,
"TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
doing, e, tor_socket_strerror(e),
SSL_state_string_long(tls->ssl));
tor_error = tor_errno_to_tls_error(e);
}
tls_log_errors(tls, severity, domain, doing);
return tor_error;
case SSL_ERROR_ZERO_RETURN:
if (extra&CATCH_ZERO)
return TOR_TLS_ZERORETURN_;
tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
doing, SSL_state_string_long(tls->ssl));
tls_log_errors(tls, severity, domain, doing);
return TOR_TLS_CLOSE;
default:
tls_log_errors(tls, severity, domain, doing);
return TOR_TLS_ERROR_MISC;
}
}
/** Initialize OpenSSL, unless it has already been initialized.
*/
static void
tor_tls_init(void)
{
check_no_tls_errors();
if (!tls_library_is_initialized) {
SSL_library_init();
SSL_load_error_strings();
#if (SIZEOF_VOID_P >= 8 && \
OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
long version = OpenSSL_version_num();
/* LCOV_EXCL_START : we can't test these lines on the same machine */
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 "
"when configuring it) would make ECDH much faster.");
}
/* LCOV_EXCL_STOP */
#endif
tor_tls_allocate_tor_tls_object_ex_data_index();
tls_library_is_initialized = 1;
}
}
/** Free all global TLS structures. */
void
tor_tls_free_all(void)
{
check_no_tls_errors();
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);
}
}
/** We need to give OpenSSL a callback to verify certificates. This is
* it: We always accept peer certs and complete the handshake. We
* don't validate them until later.
*/
STATIC int
always_accept_verify_cb(int preverify_ok,
X509_STORE_CTX *x509_ctx)
{
(void) preverify_ok;
(void) x509_ctx;
return 1;
}
/** Return a newly allocated X509 name with commonName <b>cname</b>. */
static X509_NAME *
tor_x509_name_new(const char *cname)
{
int nid;
X509_NAME *name;
/* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
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;
/* LCOV_EXCL_BR_STOP */
return name;
error:
/* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
X509_NAME_free(name);
return NULL;
/* LCOV_EXCL_STOP */
}
/** 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
* <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.
*/
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))
{
/* OpenSSL generates self-signed certificates with random 64-bit serial
* numbers, so let's do that too. */
#define SERIAL_NUMBER_SIZE 8
time_t start_time, end_time;
BIGNUM *serial_number = NULL;
unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
X509 *x509 = NULL;
X509_NAME *name = NULL, *name_issuer=NULL;
tor_tls_init();
/* 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. */
time_t now = time(NULL);
start_time = crypto_rand_time_range(now - cert_lifetime, now) + 2*24*3600;
start_time -= start_time % (24*3600);
tor_assert(rsa);
tor_assert(cname);
tor_assert(rsa_sign);
tor_assert(cname_sign);
if (!(sign_pkey = crypto_pk_get_evp_pkey_(rsa_sign,1)))
goto error;
if (!(pkey = crypto_pk_get_evp_pkey_(rsa,0)))
goto error;
if (!(x509 = X509_new()))
goto error;
if (!(X509_set_version(x509, 2)))
goto error;
{ /* our serial number is 8 random bytes. */
crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
goto error;
if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
goto error;
}
if (!(name = tor_x509_name_new(cname)))
goto error;
if (!(X509_set_subject_name(x509, name)))
goto error;
if (!(name_issuer = tor_x509_name_new(cname_sign)))
goto error;
if (!(X509_set_issuer_name(x509, name_issuer)))
goto error;
if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
goto error;
end_time = start_time + cert_lifetime;
if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
goto error;
if (!X509_set_pubkey(x509, pkey))
goto error;
if (!X509_sign(x509, sign_pkey, EVP_sha256()))
goto error;
goto done;
error:
if (x509) {
X509_free(x509);
x509 = NULL;
}
done:
tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
if (sign_pkey)
EVP_PKEY_free(sign_pkey);
if (pkey)
EVP_PKEY_free(pkey);
if (serial_number)
BN_clear_free(serial_number);
if (name)
X509_NAME_free(name);
if (name_issuer)
X509_NAME_free(name_issuer);
return x509;
#undef SERIAL_NUMBER_SIZE
}
/** List of ciphers that servers should select from when the client might be
* claiming extra unsupported ciphers in order to avoid fingerprinting. */
#define SERVER_CIPHER_LIST \
(TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
/** List of ciphers that servers should select from when we actually have
* our choice of what cipher to use. */
static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
/* This list is autogenerated with the gen_server_ciphers.py script;
* don't hand-edit it. */
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
#endif
#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
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
#endif
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
#endif
#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
#endif
#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_CCM
TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
#endif
#ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
#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 ":"
#endif
/* Required */
TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
/* Required */
TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
#ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
#endif
#ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
#endif
;
/* 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
* with any of the "real" Tors, though. */
#define CIPHER(id, name) name ":"
#define XCIPHER(id, name)
/** List of ciphers that clients should advertise, omitting items that
* our OpenSSL doesn't know about. */
static const char CLIENT_CIPHER_LIST[] =
#include "ciphers.inc"
/* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
* of any cipher we say. */
"!SSLv2"
;
#undef CIPHER
#undef XCIPHER
/** Free all storage held in <b>cert</b> */
void
tor_x509_cert_free(tor_x509_cert_t *cert)
{
if (! cert)
return;
if (cert->cert)
X509_free(cert->cert);
tor_free(cert->encoded);
memwipe(cert, 0x03, sizeof(*cert));
/* LCOV_EXCL_BR_START since cert will never be NULL here */
tor_free(cert);
/* LCOV_EXCL_BR_STOP */
}
/**
* Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
*
* Steals a reference to x509_cert.
*/
MOCK_IMPL(STATIC tor_x509_cert_t *,
tor_x509_cert_new,(X509 *x509_cert))
{
tor_x509_cert_t *cert;
EVP_PKEY *pkey;
RSA *rsa;
int length;
unsigned char *buf = NULL;
if (!x509_cert)
return NULL;
length = i2d_X509(x509_cert, &buf);
cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
if (length <= 0 || buf == NULL) {
/* LCOV_EXCL_START for the same reason as the exclusion above */
tor_free(cert);
log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
X509_free(x509_cert);
return NULL;
/* LCOV_EXCL_STOP */
}
cert->encoded_len = (size_t) length;
cert->encoded = tor_malloc(length);
memcpy(cert->encoded, buf, length);
OPENSSL_free(buf);
cert->cert = x509_cert;
crypto_common_digests(&cert->cert_digests,
(char*)cert->encoded, cert->encoded_len);
if ((pkey = X509_get_pubkey(x509_cert)) &&
(rsa = EVP_PKEY_get1_RSA(pkey))) {
crypto_pk_t *pk = crypto_new_pk_from_rsa_(rsa);
crypto_pk_get_common_digests(pk, &cert->pkey_digests);
cert->pkey_digests_set = 1;
crypto_pk_free(pk);
EVP_PKEY_free(pkey);
}
return cert;
}
/** Return a copy of <b>cert</b> */
tor_x509_cert_t *
tor_x509_cert_dup(const tor_x509_cert_t *cert)
{
return tor_x509_cert_new(X509_dup(cert->cert));
}
/** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
* from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
* success and NULL on failure. */
tor_x509_cert_t *
tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
{
X509 *x509;
const unsigned char *cp = (const unsigned char *)certificate;
tor_x509_cert_t *newcert;
tor_assert(certificate);
check_no_tls_errors();
if (certificate_len > INT_MAX)
goto err;
x509 = d2i_X509(NULL, &cp, (int)certificate_len);
if (!x509)
goto err; /* Couldn't decode */
if (cp - certificate != (int)certificate_len) {
X509_free(x509);
goto err; /* Didn't use all the bytes */
}
newcert = tor_x509_cert_new(x509);
if (!newcert) {
goto err;
}
if (newcert->encoded_len != certificate_len ||
fast_memneq(newcert->encoded, certificate, certificate_len)) {
/* Cert wasn't in DER */
tor_x509_cert_free(newcert);
goto err;
}
return newcert;
err:
tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
return NULL;
}
/** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
* representation and length, respectively. */
void
tor_x509_cert_get_der(const tor_x509_cert_t *cert,
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;
}
/** 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. */
const common_digests_t *
tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
{
if (cert->pkey_digests_set)
return &cert->pkey_digests;
else
return NULL;
}
/** Return a set of digests for the public key in <b>cert</b>. */
const common_digests_t *
tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
{
return &cert->cert_digests;
}
/** Remove a reference to <b>ctx</b>, and free it if it has no more
* references. */
static void
tor_tls_context_decref(tor_tls_context_t *ctx)
{
tor_assert(ctx);
if (--ctx->refcnt == 0) {
SSL_CTX_free(ctx->ctx);
tor_x509_cert_free(ctx->my_link_cert);
tor_x509_cert_free(ctx->my_id_cert);
tor_x509_cert_free(ctx->my_auth_cert);
crypto_pk_free(ctx->link_key);
crypto_pk_free(ctx->auth_key);
/* LCOV_EXCL_BR_START since ctx will never be NULL here */
tor_free(ctx);
/* LCOV_EXCL_BR_STOP */
}
}
/** 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 (auth, ID); otherwise, provide the certs that we
* use in client mode. (link, ID) */
int
tor_tls_get_my_certs(int server,
const tor_x509_cert_t **link_cert_out,
const tor_x509_cert_t **id_cert_out)
{
tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
if (! ctx)
return -1;
if (link_cert_out)
*link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
if (id_cert_out)
*id_cert_out = ctx->my_id_cert;
return 0;
}
/**
* Return the authentication key that we use to authenticate ourselves as a
* client in the V3 in-protocol handshake.
*/
crypto_pk_t *
tor_tls_get_my_client_auth_key(void)
{
if (! client_tls_context)
return NULL;
return client_tls_context->auth_key;
}
/**
* Return a newly allocated copy of the public key that a certificate
* certifies. Watch out! This returns NULL if the cert's key is not RSA.
*/
crypto_pk_t *
tor_tls_cert_get_key(tor_x509_cert_t *cert)
{
crypto_pk_t *result = NULL;
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;
}
result = crypto_new_pk_from_rsa_(rsa);
EVP_PKEY_free(pkey);
return result;
}
/** 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.
*/
MOCK_IMPL(int,
tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
{
X509 *peercert = SSL_get_peer_certificate(tls->ssl);
EVP_PKEY *link_key = NULL, *cert_key = NULL;
int result;
if (!peercert)
return 0;
link_key = X509_get_pubkey(peercert);
cert_key = X509_get_pubkey(cert->cert);
result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
X509_free(peercert);
if (link_key)
EVP_PKEY_free(link_key);
if (cert_key)
EVP_PKEY_free(cert_key);
return result;
}
/** Check whether <b>cert</b> is well-formed, currently live, and correctly
* 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. */
int
tor_tls_cert_is_valid(int severity,
const tor_x509_cert_t *cert,
const tor_x509_cert_t *signing_cert,
time_t now,
int check_rsa_1024)
{
check_no_tls_errors();
EVP_PKEY *cert_key;
int r, key_ok = 0;
if (!signing_cert || !cert)
goto bad;
EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
if (!signing_key)
goto bad;
r = X509_verify(cert->cert, signing_key);
EVP_PKEY_free(signing_key);
if (r <= 0)
goto bad;
/* okay, the signature checked out right. Now let's check the check the
* lifetime. */
if (check_cert_lifetime_internal(severity, cert->cert, now,
48*60*60, 30*24*60*60) < 0)
goto bad;
cert_key = X509_get_pubkey(cert->cert);
if (check_rsa_1024 && cert_key) {
RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
#ifdef OPENSSL_1_1_API
if (rsa && RSA_bits(rsa) == 1024)
#else
if (rsa && BN_num_bits(rsa->n) == 1024)
#endif
key_ok = 1;
if (rsa)
RSA_free(rsa);
} else if (cert_key) {
int min_bits = 1024;
#ifdef EVP_PKEY_EC
if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
min_bits = 128;
#endif
if (EVP_PKEY_bits(cert_key) >= min_bits)
key_ok = 1;
}
EVP_PKEY_free(cert_key);
if (!key_ok)
goto bad;
/* XXXX compare DNs or anything? */
return 1;
bad:
tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
return 0;
}
/** Increase the reference count of <b>ctx</b>. */
static void
tor_tls_context_incref(tor_tls_context_t *ctx)
{
++ctx->refcnt;
}
/** Create new global client and server TLS contexts.
*
* If <b>server_identity</b> is NULL, this will not generate a server
* TLS context. If TOR_TLS_CTX_IS_PUBLIC_SERVER is set in <b>flags</b>, use
* the same TLS context for incoming and outgoing connections, and
* 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. */
int
tor_tls_context_init(unsigned flags,
crypto_pk_t *client_identity,
crypto_pk_t *server_identity,
unsigned int key_lifetime)
{
int rv1 = 0;
int rv2 = 0;
const int is_public_server = flags & TOR_TLS_CTX_IS_PUBLIC_SERVER;
check_no_tls_errors();
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,
key_lifetime, flags, 0);
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,
key_lifetime,
flags,
0);
} else {
tor_tls_context_t *old_ctx = server_tls_context;
server_tls_context = NULL;
if (old_ctx != NULL) {
tor_tls_context_decref(old_ctx);
}
}
rv2 = tor_tls_context_init_one(&client_tls_context,
client_identity,
key_lifetime,
flags,