-
Notifications
You must be signed in to change notification settings - Fork 762
/
ssl_lib.cc
3446 lines (2932 loc) · 102 KB
/
ssl_lib.cc
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) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE. */
#include <openssl/ssl.h>
#include <algorithm>
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bytestring.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/lhash.h>
#include <openssl/mem.h>
#include <openssl/rand.h>
#include "internal.h"
#include "../crypto/internal.h"
#if defined(OPENSSL_WINDOWS)
#include <sys/timeb.h>
#else
#include <sys/socket.h>
#include <sys/time.h>
#endif
BSSL_NAMESPACE_BEGIN
static_assert(SSL3_RT_MAX_ENCRYPTED_OVERHEAD >=
SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD,
"max overheads are inconsistent");
// |SSL_R_UNKNOWN_PROTOCOL| is no longer emitted, but continue to define it
// to avoid downstream churn.
OPENSSL_DECLARE_ERROR_REASON(SSL, UNKNOWN_PROTOCOL)
// The following errors are no longer emitted, but are used in nginx without
// #ifdefs.
OPENSSL_DECLARE_ERROR_REASON(SSL, BLOCK_CIPHER_PAD_IS_WRONG)
OPENSSL_DECLARE_ERROR_REASON(SSL, NO_CIPHERS_SPECIFIED)
// Some error codes are special. Ensure the make_errors.go script never
// regresses this.
static_assert(SSL_R_TLSV1_ALERT_NO_RENEGOTIATION ==
SSL_AD_NO_RENEGOTIATION + SSL_AD_REASON_OFFSET,
"alert reason code mismatch");
// kMaxHandshakeSize is the maximum size, in bytes, of a handshake message.
static const size_t kMaxHandshakeSize = (1u << 24) - 1;
static CRYPTO_EX_DATA_CLASS g_ex_data_class_ssl =
CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
static CRYPTO_EX_DATA_CLASS g_ex_data_class_ssl_ctx =
CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out) {
uint8_t *ptr;
size_t len;
if (!CBB_finish(cbb, &ptr, &len)) {
OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
return false;
}
out->Reset(ptr, len);
return true;
}
void ssl_reset_error_state(SSL *ssl) {
// Functions which use |SSL_get_error| must reset I/O and error state on
// entry.
ssl->s3->rwstate = SSL_ERROR_NONE;
ERR_clear_error();
ERR_clear_system_error();
}
void ssl_set_read_error(SSL* ssl) {
ssl->s3->read_shutdown = ssl_shutdown_error;
ssl->s3->read_error.reset(ERR_save_state());
}
static bool check_read_error(const SSL *ssl) {
if (ssl->s3->read_shutdown == ssl_shutdown_error) {
ERR_restore_state(ssl->s3->read_error.get());
return false;
}
return true;
}
bool ssl_can_write(const SSL *ssl) {
return !SSL_in_init(ssl) || ssl->s3->hs->can_early_write;
}
bool ssl_can_read(const SSL *ssl) {
return !SSL_in_init(ssl) || ssl->s3->hs->can_early_read;
}
ssl_open_record_t ssl_open_handshake(SSL *ssl, size_t *out_consumed,
uint8_t *out_alert, Span<uint8_t> in) {
*out_consumed = 0;
if (!check_read_error(ssl)) {
*out_alert = 0;
return ssl_open_record_error;
}
auto ret = ssl->method->open_handshake(ssl, out_consumed, out_alert, in);
if (ret == ssl_open_record_error) {
ssl_set_read_error(ssl);
}
return ret;
}
ssl_open_record_t ssl_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
uint8_t *out_alert,
Span<uint8_t> in) {
*out_consumed = 0;
if (!check_read_error(ssl)) {
*out_alert = 0;
return ssl_open_record_error;
}
auto ret =
ssl->method->open_change_cipher_spec(ssl, out_consumed, out_alert, in);
if (ret == ssl_open_record_error) {
ssl_set_read_error(ssl);
}
return ret;
}
ssl_open_record_t ssl_open_app_data(SSL *ssl, Span<uint8_t> *out,
size_t *out_consumed, uint8_t *out_alert,
Span<uint8_t> in) {
*out_consumed = 0;
if (!check_read_error(ssl)) {
*out_alert = 0;
return ssl_open_record_error;
}
auto ret = ssl->method->open_app_data(ssl, out, out_consumed, out_alert, in);
if (ret == ssl_open_record_error) {
ssl_set_read_error(ssl);
}
return ret;
}
static uint8_t hex_char_consttime(uint8_t b) {
declassify_assert(b < 16);
return constant_time_select_8(constant_time_lt_8(b, 10), b + '0',
b - 10 + 'a');
}
static bool cbb_add_hex_consttime(CBB *cbb, Span<const uint8_t> in) {
uint8_t *out;
if (!CBB_add_space(cbb, &out, in.size() * 2)) {
return false;
}
for (uint8_t b : in) {
*(out++) = hex_char_consttime(b >> 4);
*(out++) = hex_char_consttime(b & 0xf);
}
return true;
}
bool ssl_log_secret(const SSL *ssl, const char *label,
Span<const uint8_t> secret) {
if (ssl->ctx->keylog_callback == NULL) {
return true;
}
ScopedCBB cbb;
Array<uint8_t> line;
if (!CBB_init(cbb.get(), strlen(label) + 1 + SSL3_RANDOM_SIZE * 2 + 1 +
secret.size() * 2 + 1) ||
!CBB_add_bytes(cbb.get(), reinterpret_cast<const uint8_t *>(label),
strlen(label)) ||
!CBB_add_u8(cbb.get(), ' ') ||
!cbb_add_hex_consttime(cbb.get(), ssl->s3->client_random) ||
!CBB_add_u8(cbb.get(), ' ') ||
// Convert to hex in constant time to avoid leaking |secret|. If the
// callback discards the data, we should not introduce side channels.
!cbb_add_hex_consttime(cbb.get(), secret) ||
!CBB_add_u8(cbb.get(), 0 /* NUL */) ||
!CBBFinishArray(cbb.get(), &line)) {
return false;
}
ssl->ctx->keylog_callback(ssl, reinterpret_cast<const char *>(line.data()));
return true;
}
void ssl_do_info_callback(const SSL *ssl, int type, int value) {
void (*cb)(const SSL *ssl, int type, int value) = NULL;
if (ssl->info_callback != NULL) {
cb = ssl->info_callback;
} else if (ssl->ctx->info_callback != NULL) {
cb = ssl->ctx->info_callback;
}
if (cb != NULL) {
cb(ssl, type, value);
}
}
void ssl_do_msg_callback(const SSL *ssl, int is_write, int content_type,
Span<const uint8_t> in) {
if (ssl->msg_callback == NULL) {
return;
}
// |version| is zero when calling for |SSL3_RT_HEADER| and |SSL2_VERSION| for
// a V2ClientHello.
int version;
switch (content_type) {
case 0:
// V2ClientHello
version = SSL2_VERSION;
break;
case SSL3_RT_HEADER:
version = 0;
break;
default:
version = SSL_version(ssl);
}
ssl->msg_callback(is_write, version, content_type, in.data(), in.size(),
const_cast<SSL *>(ssl), ssl->msg_callback_arg);
}
void ssl_get_current_time(const SSL *ssl, struct OPENSSL_timeval *out_clock) {
// TODO(martinkr): Change callers to |ssl_ctx_get_current_time| and drop the
// |ssl| arg from |current_time_cb| if possible.
ssl_ctx_get_current_time(ssl->ctx.get(), out_clock);
}
void ssl_ctx_get_current_time(const SSL_CTX *ctx,
struct OPENSSL_timeval *out_clock) {
if (ctx->current_time_cb != NULL) {
// TODO(davidben): Update current_time_cb to use OPENSSL_timeval. See
// https://crbug.com/boringssl/155.
struct timeval clock;
ctx->current_time_cb(nullptr /* ssl */, &clock);
if (clock.tv_sec < 0) {
assert(0);
out_clock->tv_sec = 0;
out_clock->tv_usec = 0;
} else {
out_clock->tv_sec = (uint64_t)clock.tv_sec;
out_clock->tv_usec = (uint32_t)clock.tv_usec;
}
return;
}
#if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
out_clock->tv_sec = 1234;
out_clock->tv_usec = 1234;
#elif defined(OPENSSL_WINDOWS)
struct _timeb time;
_ftime(&time);
if (time.time < 0) {
assert(0);
out_clock->tv_sec = 0;
out_clock->tv_usec = 0;
} else {
out_clock->tv_sec = time.time;
out_clock->tv_usec = time.millitm * 1000;
}
#else
struct timeval clock;
gettimeofday(&clock, NULL);
if (clock.tv_sec < 0) {
assert(0);
out_clock->tv_sec = 0;
out_clock->tv_usec = 0;
} else {
out_clock->tv_sec = (uint64_t)clock.tv_sec;
out_clock->tv_usec = (uint32_t)clock.tv_usec;
}
#endif
}
void SSL_CTX_set_handoff_mode(SSL_CTX *ctx, bool on) {
ctx->handoff = on;
}
static bool ssl_can_renegotiate(const SSL *ssl) {
if (ssl->server || SSL_is_dtls(ssl)) {
return false;
}
if (ssl->s3->version != 0 &&
ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
return false;
}
// The config has already been shed.
if (!ssl->config) {
return false;
}
switch (ssl->renegotiate_mode) {
case ssl_renegotiate_ignore:
case ssl_renegotiate_never:
return false;
case ssl_renegotiate_freely:
case ssl_renegotiate_explicit:
return true;
case ssl_renegotiate_once:
return ssl->s3->total_renegotiations == 0;
}
assert(0);
return false;
}
static void ssl_maybe_shed_handshake_config(SSL *ssl) {
if (ssl->s3->hs != nullptr ||
ssl->config == nullptr ||
!ssl->config->shed_handshake_config ||
ssl_can_renegotiate(ssl)) {
return;
}
ssl->config.reset();
}
void SSL_set_handoff_mode(SSL *ssl, bool on) {
if (!ssl->config) {
return;
}
ssl->config->handoff = on;
}
bool SSL_get_traffic_secrets(const SSL *ssl,
Span<const uint8_t> *out_read_traffic_secret,
Span<const uint8_t> *out_write_traffic_secret) {
// This API is not well-defined for DTLS 1.3 (see https://crbug.com/42290608)
// or QUIC, where multiple epochs may be alive at once.
if (SSL_is_dtls(ssl) || ssl->quic_method != nullptr) {
OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return false;
}
if (!ssl->s3->initial_handshake_complete) {
OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_NOT_COMPLETE);
return false;
}
if (SSL_version(ssl) < TLS1_3_VERSION) {
OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
return false;
}
*out_read_traffic_secret = ssl->s3->read_traffic_secret;
*out_write_traffic_secret = ssl->s3->write_traffic_secret;
return true;
}
void SSL_CTX_set_aes_hw_override_for_testing(SSL_CTX *ctx,
bool override_value) {
ctx->aes_hw_override = true;
ctx->aes_hw_override_value = override_value;
}
void SSL_set_aes_hw_override_for_testing(SSL *ssl, bool override_value) {
ssl->config->aes_hw_override = true;
ssl->config->aes_hw_override_value = override_value;
}
BSSL_NAMESPACE_END
using namespace bssl;
int SSL_library_init(void) { return 1; }
int OPENSSL_init_ssl(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) {
return 1;
}
static uint32_t ssl_session_hash(const SSL_SESSION *sess) {
return ssl_hash_session_id(sess->session_id);
}
static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b) {
return MakeConstSpan(a->session_id) == b->session_id ? 0 : 1;
}
ssl_ctx_st::ssl_ctx_st(const SSL_METHOD *ssl_method)
: RefCounted(CheckSubClass()),
method(ssl_method->method),
x509_method(ssl_method->x509_method),
retain_only_sha256_of_client_certs(false),
quiet_shutdown(false),
ocsp_stapling_enabled(false),
signed_cert_timestamps_enabled(false),
channel_id_enabled(false),
grease_enabled(false),
permute_extensions(false),
allow_unknown_alpn_protos(false),
false_start_allowed_without_alpn(false),
handoff(false),
enable_early_data(false),
aes_hw_override(false),
aes_hw_override_value(false) {
CRYPTO_MUTEX_init(&lock);
CRYPTO_new_ex_data(&ex_data);
}
ssl_ctx_st::~ssl_ctx_st() {
// Free the internal session cache. Note that this calls the caller-supplied
// remove callback, so we must do it before clearing ex_data. (See ticket
// [openssl.org #212].)
SSL_CTX_flush_sessions(this, 0);
CRYPTO_free_ex_data(&g_ex_data_class_ssl_ctx, this, &ex_data);
CRYPTO_MUTEX_cleanup(&lock);
lh_SSL_SESSION_free(sessions);
x509_method->ssl_ctx_free(this);
}
SSL_CTX *SSL_CTX_new(const SSL_METHOD *method) {
if (method == NULL) {
OPENSSL_PUT_ERROR(SSL, SSL_R_NULL_SSL_METHOD_PASSED);
return nullptr;
}
UniquePtr<SSL_CTX> ret = MakeUnique<SSL_CTX>(method);
if (!ret) {
return nullptr;
}
ret->cert = MakeUnique<CERT>(method->x509_method);
ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
ret->client_CA.reset(sk_CRYPTO_BUFFER_new_null());
ret->CA_names.reset(sk_CRYPTO_BUFFER_new_null());
if (ret->cert == nullptr || //
!ret->cert->is_valid() || //
ret->sessions == nullptr || //
ret->client_CA == nullptr || //
ret->CA_names == nullptr || //
!ret->x509_method->ssl_ctx_new(ret.get())) {
return nullptr;
}
if (!SSL_CTX_set_strict_cipher_list(ret.get(), SSL_DEFAULT_CIPHER_LIST) ||
// Lock the SSL_CTX to the specified version, for compatibility with
// legacy uses of SSL_METHOD.
!SSL_CTX_set_max_proto_version(ret.get(), method->version) ||
!SSL_CTX_set_min_proto_version(ret.get(), method->version)) {
OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
return nullptr;
}
return ret.release();
}
int SSL_CTX_up_ref(SSL_CTX *ctx) {
ctx->UpRefInternal();
return 1;
}
void SSL_CTX_free(SSL_CTX *ctx) {
if (ctx != nullptr) {
ctx->DecRefInternal();
}
}
ssl_st::ssl_st(SSL_CTX *ctx_arg)
: method(ctx_arg->method),
max_send_fragment(ctx_arg->max_send_fragment),
msg_callback(ctx_arg->msg_callback),
msg_callback_arg(ctx_arg->msg_callback_arg),
ctx(UpRef(ctx_arg)),
session_ctx(UpRef(ctx_arg)),
options(ctx->options),
mode(ctx->mode),
max_cert_list(ctx->max_cert_list),
server(false),
quiet_shutdown(ctx->quiet_shutdown),
enable_early_data(ctx->enable_early_data) {
CRYPTO_new_ex_data(&ex_data);
}
ssl_st::~ssl_st() {
CRYPTO_free_ex_data(&g_ex_data_class_ssl, this, &ex_data);
// |config| refers to |this|, so we must release it earlier.
config.reset();
if (method != NULL) {
method->ssl_free(this);
}
}
SSL *SSL_new(SSL_CTX *ctx) {
if (ctx == nullptr) {
OPENSSL_PUT_ERROR(SSL, SSL_R_NULL_SSL_CTX);
return nullptr;
}
UniquePtr<SSL> ssl = MakeUnique<SSL>(ctx);
if (ssl == nullptr) {
return nullptr;
}
ssl->config = MakeUnique<SSL_CONFIG>(ssl.get());
if (ssl->config == nullptr) {
return nullptr;
}
ssl->config->conf_min_version = ctx->conf_min_version;
ssl->config->conf_max_version = ctx->conf_max_version;
ssl->config->cert = ssl_cert_dup(ctx->cert.get());
if (ssl->config->cert == nullptr) {
return nullptr;
}
ssl->config->verify_mode = ctx->verify_mode;
ssl->config->verify_callback = ctx->default_verify_callback;
ssl->config->custom_verify_callback = ctx->custom_verify_callback;
ssl->config->retain_only_sha256_of_client_certs =
ctx->retain_only_sha256_of_client_certs;
ssl->config->permute_extensions = ctx->permute_extensions;
ssl->config->aes_hw_override = ctx->aes_hw_override;
ssl->config->aes_hw_override_value = ctx->aes_hw_override_value;
ssl->config->tls13_cipher_policy = ctx->tls13_cipher_policy;
if (!ssl->config->supported_group_list.CopyFrom(ctx->supported_group_list) ||
!ssl->config->alpn_client_proto_list.CopyFrom(
ctx->alpn_client_proto_list) ||
!ssl->config->verify_sigalgs.CopyFrom(ctx->verify_sigalgs)) {
return nullptr;
}
if (ctx->psk_identity_hint) {
ssl->config->psk_identity_hint.reset(
OPENSSL_strdup(ctx->psk_identity_hint.get()));
if (ssl->config->psk_identity_hint == nullptr) {
return nullptr;
}
}
ssl->config->psk_client_callback = ctx->psk_client_callback;
ssl->config->psk_server_callback = ctx->psk_server_callback;
ssl->config->channel_id_enabled = ctx->channel_id_enabled;
ssl->config->channel_id_private = UpRef(ctx->channel_id_private);
ssl->config->signed_cert_timestamps_enabled =
ctx->signed_cert_timestamps_enabled;
ssl->config->ocsp_stapling_enabled = ctx->ocsp_stapling_enabled;
ssl->config->handoff = ctx->handoff;
ssl->quic_method = ctx->quic_method;
if (!ssl->method->ssl_new(ssl.get()) ||
!ssl->ctx->x509_method->ssl_new(ssl->s3->hs.get())) {
return nullptr;
}
return ssl.release();
}
SSL_CONFIG::SSL_CONFIG(SSL *ssl_arg)
: ssl(ssl_arg),
ech_grease_enabled(false),
signed_cert_timestamps_enabled(false),
ocsp_stapling_enabled(false),
channel_id_enabled(false),
enforce_rsa_key_usage(true),
retain_only_sha256_of_client_certs(false),
handoff(false),
shed_handshake_config(false),
jdk11_workaround(false),
quic_use_legacy_codepoint(false),
permute_extensions(false),
alps_use_new_codepoint(false),
check_client_certificate_type(true),
check_ecdsa_curve(true) {
assert(ssl);
}
SSL_CONFIG::~SSL_CONFIG() {
if (ssl->ctx != nullptr) {
ssl->ctx->x509_method->ssl_config_free(this);
}
}
void SSL_free(SSL *ssl) {
Delete(ssl);
}
void SSL_set_connect_state(SSL *ssl) {
ssl->server = false;
ssl->do_handshake = ssl_client_handshake;
}
void SSL_set_accept_state(SSL *ssl) {
ssl->server = true;
ssl->do_handshake = ssl_server_handshake;
}
void SSL_set0_rbio(SSL *ssl, BIO *rbio) {
ssl->rbio.reset(rbio);
}
void SSL_set0_wbio(SSL *ssl, BIO *wbio) {
ssl->wbio.reset(wbio);
}
void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio) {
// For historical reasons, this function has many different cases in ownership
// handling.
// If nothing has changed, do nothing
if (rbio == SSL_get_rbio(ssl) && wbio == SSL_get_wbio(ssl)) {
return;
}
// If the two arguments are equal, one fewer reference is granted than
// taken.
if (rbio != NULL && rbio == wbio) {
BIO_up_ref(rbio);
}
// If only the wbio is changed, adopt only one reference.
if (rbio == SSL_get_rbio(ssl)) {
SSL_set0_wbio(ssl, wbio);
return;
}
// There is an asymmetry here for historical reasons. If only the rbio is
// changed AND the rbio and wbio were originally different, then we only adopt
// one reference.
if (wbio == SSL_get_wbio(ssl) && SSL_get_rbio(ssl) != SSL_get_wbio(ssl)) {
SSL_set0_rbio(ssl, rbio);
return;
}
// Otherwise, adopt both references.
SSL_set0_rbio(ssl, rbio);
SSL_set0_wbio(ssl, wbio);
}
BIO *SSL_get_rbio(const SSL *ssl) { return ssl->rbio.get(); }
BIO *SSL_get_wbio(const SSL *ssl) { return ssl->wbio.get(); }
size_t SSL_quic_max_handshake_flight_len(const SSL *ssl,
enum ssl_encryption_level_t level) {
// Limits flights to 16K by default when there are no large
// (certificate-carrying) messages.
static const size_t kDefaultLimit = 16384;
switch (level) {
case ssl_encryption_initial:
return kDefaultLimit;
case ssl_encryption_early_data:
// QUIC does not send EndOfEarlyData.
return 0;
case ssl_encryption_handshake:
if (ssl->server) {
// Servers may receive Certificate message if configured to request
// client certificates.
if (!!(ssl->config->verify_mode & SSL_VERIFY_PEER) &&
ssl->max_cert_list > kDefaultLimit) {
return ssl->max_cert_list;
}
} else {
// Clients may receive both Certificate message and a CertificateRequest
// message.
if (2*ssl->max_cert_list > kDefaultLimit) {
return 2*ssl->max_cert_list;
}
}
return kDefaultLimit;
case ssl_encryption_application:
// Note there is not actually a bound on the number of NewSessionTickets
// one may send in a row. This level may need more involved flow
// control. See https://github.com/quicwg/base-drafts/issues/1834.
return kDefaultLimit;
}
return 0;
}
enum ssl_encryption_level_t SSL_quic_read_level(const SSL *ssl) {
assert(ssl->quic_method != nullptr);
return ssl->s3->quic_read_level;
}
enum ssl_encryption_level_t SSL_quic_write_level(const SSL *ssl) {
assert(ssl->quic_method != nullptr);
return ssl->s3->quic_write_level;
}
int SSL_provide_quic_data(SSL *ssl, enum ssl_encryption_level_t level,
const uint8_t *data, size_t len) {
if (ssl->quic_method == nullptr) {
OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (level != ssl->s3->quic_read_level) {
OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_ENCRYPTION_LEVEL_RECEIVED);
return 0;
}
size_t new_len = (ssl->s3->hs_buf ? ssl->s3->hs_buf->length : 0) + len;
if (new_len < len ||
new_len > SSL_quic_max_handshake_flight_len(ssl, level)) {
OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
return 0;
}
return tls_append_handshake_data(ssl, MakeConstSpan(data, len));
}
int SSL_do_handshake(SSL *ssl) {
ssl_reset_error_state(ssl);
if (ssl->do_handshake == NULL) {
OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_TYPE_NOT_SET);
return -1;
}
if (!SSL_in_init(ssl)) {
return 1;
}
// Run the handshake.
SSL_HANDSHAKE *hs = ssl->s3->hs.get();
bool early_return = false;
int ret = ssl_run_handshake(hs, &early_return);
ssl_do_info_callback(
ssl, ssl->server ? SSL_CB_ACCEPT_EXIT : SSL_CB_CONNECT_EXIT, ret);
if (ret <= 0) {
return ret;
}
// Destroy the handshake object if the handshake has completely finished.
if (!early_return) {
ssl->s3->hs.reset();
ssl_maybe_shed_handshake_config(ssl);
}
return 1;
}
int SSL_connect(SSL *ssl) {
if (ssl->do_handshake == NULL) {
// Not properly initialized yet
SSL_set_connect_state(ssl);
}
return SSL_do_handshake(ssl);
}
int SSL_accept(SSL *ssl) {
if (ssl->do_handshake == NULL) {
// Not properly initialized yet
SSL_set_accept_state(ssl);
}
return SSL_do_handshake(ssl);
}
static int ssl_do_post_handshake(SSL *ssl, const SSLMessage &msg) {
if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
return tls13_post_handshake(ssl, msg);
}
// Check for renegotiation on the server before parsing to use the correct
// error. Renegotiation is triggered by a different message for servers.
if (ssl->server) {
OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_NO_RENEGOTIATION);
return 0;
}
if (msg.type != SSL3_MT_HELLO_REQUEST || CBS_len(&msg.body) != 0) {
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HELLO_REQUEST);
return 0;
}
if (ssl->renegotiate_mode == ssl_renegotiate_ignore) {
return 1; // Ignore the HelloRequest.
}
ssl->s3->renegotiate_pending = true;
if (ssl->renegotiate_mode == ssl_renegotiate_explicit) {
return 1; // Handle it later.
}
if (!SSL_renegotiate(ssl)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_NO_RENEGOTIATION);
return 0;
}
return 1;
}
int SSL_process_quic_post_handshake(SSL *ssl) {
ssl_reset_error_state(ssl);
if (SSL_in_init(ssl)) {
OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
// Replay post-handshake message errors.
if (!check_read_error(ssl)) {
return 0;
}
// Process any buffered post-handshake messages.
SSLMessage msg;
while (ssl->method->get_message(ssl, &msg)) {
// Handle the post-handshake message and try again.
if (!ssl_do_post_handshake(ssl, msg)) {
ssl_set_read_error(ssl);
return 0;
}
ssl->method->next_message(ssl);
}
return 1;
}
static int ssl_read_impl(SSL *ssl) {
ssl_reset_error_state(ssl);
if (ssl->do_handshake == NULL) {
OPENSSL_PUT_ERROR(SSL, SSL_R_UNINITIALIZED);
return -1;
}
// Replay post-handshake message errors.
if (!check_read_error(ssl)) {
return -1;
}
while (ssl->s3->pending_app_data.empty()) {
if (ssl->s3->renegotiate_pending) {
ssl->s3->rwstate = SSL_ERROR_WANT_RENEGOTIATE;
return -1;
}
// Complete the current handshake, if any. False Start will cause
// |SSL_do_handshake| to return mid-handshake, so this may require multiple
// iterations.
while (!ssl_can_read(ssl)) {
int ret = SSL_do_handshake(ssl);
if (ret < 0) {
return ret;
}
if (ret == 0) {
OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
// Process any buffered post-handshake messages.