-
Notifications
You must be signed in to change notification settings - Fork 788
/
Copy pathhandshake_server.cc
1906 lines (1684 loc) · 63.4 KB
/
handshake_server.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 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
// Copyright 2005 Nokia. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <openssl/ssl.h>
#include <assert.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/bytestring.h>
#include <openssl/cipher.h>
#include <openssl/curve25519.h>
#include <openssl/digest.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>
#include <openssl/mem.h>
#include <openssl/nid.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include "../crypto/internal.h"
#include "internal.h"
BSSL_NAMESPACE_BEGIN
bool ssl_client_cipher_list_contains_cipher(
const SSL_CLIENT_HELLO *client_hello, uint16_t id) {
CBS cipher_suites;
CBS_init(&cipher_suites, client_hello->cipher_suites,
client_hello->cipher_suites_len);
while (CBS_len(&cipher_suites) > 0) {
uint16_t got_id;
if (!CBS_get_u16(&cipher_suites, &got_id)) {
return false;
}
if (got_id == id) {
return true;
}
}
return false;
}
static bool negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
const SSL_CLIENT_HELLO *client_hello) {
SSL *const ssl = hs->ssl;
assert(ssl->s3->version == 0);
CBS supported_versions, versions;
if (ssl_client_hello_get_extension(client_hello, &supported_versions,
TLSEXT_TYPE_supported_versions)) {
if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) || //
CBS_len(&supported_versions) != 0 || //
CBS_len(&versions) == 0) {
OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
*out_alert = SSL_AD_DECODE_ERROR;
return false;
}
} else {
// Convert the ClientHello version to an equivalent supported_versions
// extension.
static const uint8_t kTLSVersions[] = {
0x03, 0x03, // TLS 1.2
0x03, 0x02, // TLS 1.1
0x03, 0x01, // TLS 1
};
static const uint8_t kDTLSVersions[] = {
0xfe, 0xfd, // DTLS 1.2
0xfe, 0xff, // DTLS 1.0
};
size_t versions_len = 0;
if (SSL_is_dtls(ssl)) {
if (client_hello->version <= DTLS1_2_VERSION) {
versions_len = 4;
} else if (client_hello->version <= DTLS1_VERSION) {
versions_len = 2;
}
versions = Span(kDTLSVersions).last(versions_len);
} else {
if (client_hello->version >= TLS1_2_VERSION) {
versions_len = 6;
} else if (client_hello->version >= TLS1_1_VERSION) {
versions_len = 4;
} else if (client_hello->version >= TLS1_VERSION) {
versions_len = 2;
}
versions = Span(kTLSVersions).last(versions_len);
}
}
if (!ssl_negotiate_version(hs, out_alert, &ssl->s3->version, &versions)) {
return false;
}
// Handle FALLBACK_SCSV.
if (ssl_client_cipher_list_contains_cipher(client_hello,
SSL3_CK_FALLBACK_SCSV & 0xffff) &&
ssl_protocol_version(ssl) < hs->max_version) {
OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
*out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
return false;
}
return true;
}
static UniquePtr<STACK_OF(SSL_CIPHER)> ssl_parse_client_cipher_list(
const SSL_CLIENT_HELLO *client_hello) {
CBS cipher_suites;
CBS_init(&cipher_suites, client_hello->cipher_suites,
client_hello->cipher_suites_len);
UniquePtr<STACK_OF(SSL_CIPHER)> sk(sk_SSL_CIPHER_new_null());
if (!sk) {
return nullptr;
}
while (CBS_len(&cipher_suites) > 0) {
uint16_t cipher_suite;
if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
return nullptr;
}
const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
if (c != NULL && !sk_SSL_CIPHER_push(sk.get(), c)) {
return nullptr;
}
}
return sk;
}
static const SSL_CIPHER *choose_cipher(SSL_HANDSHAKE *hs,
const STACK_OF(SSL_CIPHER) *client_pref,
uint32_t mask_k, uint32_t mask_a) {
SSL *const ssl = hs->ssl;
const STACK_OF(SSL_CIPHER) *prio, *allow;
// in_group_flags will either be NULL, or will point to an array of bytes
// which indicate equal-preference groups in the |prio| stack. See the
// comment about |in_group_flags| in the |SSLCipherPreferenceList|
// struct.
const bool *in_group_flags;
// group_min contains the minimal index so far found in a group, or -1 if no
// such value exists yet.
int group_min = -1;
const SSLCipherPreferenceList *server_pref =
hs->config->cipher_list ? hs->config->cipher_list.get()
: ssl->ctx->cipher_list.get();
if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
prio = server_pref->ciphers.get();
in_group_flags = server_pref->in_group_flags;
allow = client_pref;
} else {
prio = client_pref;
in_group_flags = NULL;
allow = server_pref->ciphers.get();
}
for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
const SSL_CIPHER *c = sk_SSL_CIPHER_value(prio, i);
size_t cipher_index;
if ( // Check if the cipher is supported for the current version.
SSL_CIPHER_get_min_version(c) <= ssl_protocol_version(ssl) && //
ssl_protocol_version(ssl) <= SSL_CIPHER_get_max_version(c) && //
// Check the cipher is supported for the server configuration.
(c->algorithm_mkey & mask_k) && //
(c->algorithm_auth & mask_a) && //
// Check the cipher is in the |allow| list.
sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
if (in_group_flags != NULL && in_group_flags[i]) {
// This element of |prio| is in a group. Update the minimum index found
// so far and continue looking.
if (group_min == -1 || (size_t)group_min > cipher_index) {
group_min = cipher_index;
}
} else {
if (group_min != -1 && (size_t)group_min < cipher_index) {
cipher_index = group_min;
}
return sk_SSL_CIPHER_value(allow, cipher_index);
}
}
if (in_group_flags != NULL && !in_group_flags[i] && group_min != -1) {
// We are about to leave a group, but we found a match in it, so that's
// our answer.
return sk_SSL_CIPHER_value(allow, group_min);
}
}
OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
return nullptr;
}
struct TLS12ServerParams {
bool ok() const { return cipher != nullptr; }
const SSL_CIPHER *cipher = nullptr;
uint16_t signature_algorithm = 0;
};
static TLS12ServerParams choose_params(SSL_HANDSHAKE *hs,
const SSL_CREDENTIAL *cred,
const STACK_OF(SSL_CIPHER) *client_pref,
bool has_ecdhe_group) {
// Determine the usable cipher suites.
uint32_t mask_k = 0, mask_a = 0;
if (has_ecdhe_group) {
mask_k |= SSL_kECDHE;
}
if (hs->config->psk_server_callback != nullptr) {
mask_k |= SSL_kPSK;
mask_a |= SSL_aPSK;
}
uint16_t sigalg = 0;
if (cred != nullptr && cred->type == SSLCredentialType::kX509) {
bool sign_ok = tls1_choose_signature_algorithm(hs, cred, &sigalg);
ERR_clear_error();
// ECDSA keys must additionally be checked against the peer's supported
// curve list.
int key_type = EVP_PKEY_id(cred->pubkey.get());
if (key_type == EVP_PKEY_EC) {
EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(cred->pubkey.get());
uint16_t group_id;
if (!ssl_nid_to_group_id(
&group_id, EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key))) ||
std::find(hs->peer_supported_group_list.begin(),
hs->peer_supported_group_list.end(),
group_id) == hs->peer_supported_group_list.end()) {
sign_ok = false;
// If this would make us unable to pick any cipher, return an error.
// This is not strictly necessary, but it gives us a more specific
// error to help the caller diagnose issues.
if (mask_a == 0) {
OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
return TLS12ServerParams();
}
}
}
mask_a |= ssl_cipher_auth_mask_for_key(cred->pubkey.get(), sign_ok);
if (key_type == EVP_PKEY_RSA) {
mask_k |= SSL_kRSA;
}
}
TLS12ServerParams params;
params.cipher = choose_cipher(hs, client_pref, mask_k, mask_a);
if (params.cipher == nullptr) {
return TLS12ServerParams();
}
if (ssl_cipher_requires_server_key_exchange(params.cipher) &&
ssl_cipher_uses_certificate_auth(params.cipher)) {
params.signature_algorithm = sigalg;
}
return params;
}
static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) {
ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_START, 1);
hs->state = state12_read_client_hello;
return ssl_hs_ok;
}
// is_probably_jdk11_with_tls13 returns whether |client_hello| was probably sent
// from a JDK 11 client with both TLS 1.3 and a prior version enabled.
static bool is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO *client_hello) {
// JDK 11 ClientHellos contain a number of unusual properties which should
// limit false positives.
// JDK 11 does not support ChaCha20-Poly1305. This is unusual: many modern
// clients implement ChaCha20-Poly1305.
if (ssl_client_cipher_list_contains_cipher(
client_hello, TLS1_3_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
return false;
}
// JDK 11 always sends extensions in a particular order.
constexpr uint16_t kMaxFragmentLength = 0x0001;
constexpr uint16_t kStatusRequestV2 = 0x0011;
static constexpr struct {
uint16_t id;
bool required;
} kJavaExtensions[] = {
{TLSEXT_TYPE_server_name, false},
{kMaxFragmentLength, false},
{TLSEXT_TYPE_status_request, false},
{TLSEXT_TYPE_supported_groups, true},
{TLSEXT_TYPE_ec_point_formats, false},
{TLSEXT_TYPE_signature_algorithms, true},
// Java always sends signature_algorithms_cert.
{TLSEXT_TYPE_signature_algorithms_cert, true},
{TLSEXT_TYPE_application_layer_protocol_negotiation, false},
{kStatusRequestV2, false},
{TLSEXT_TYPE_extended_master_secret, false},
{TLSEXT_TYPE_supported_versions, true},
{TLSEXT_TYPE_cookie, false},
{TLSEXT_TYPE_psk_key_exchange_modes, true},
{TLSEXT_TYPE_key_share, true},
{TLSEXT_TYPE_renegotiate, false},
{TLSEXT_TYPE_pre_shared_key, false},
};
Span<const uint8_t> sigalgs, sigalgs_cert;
bool has_status_request = false, has_status_request_v2 = false;
CBS extensions, supported_groups;
CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
for (const auto &java_extension : kJavaExtensions) {
CBS copy = extensions;
uint16_t id;
if (CBS_get_u16(©, &id) && id == java_extension.id) {
// The next extension is the one we expected.
extensions = copy;
CBS body;
if (!CBS_get_u16_length_prefixed(&extensions, &body)) {
return false;
}
switch (id) {
case TLSEXT_TYPE_status_request:
has_status_request = true;
break;
case kStatusRequestV2:
has_status_request_v2 = true;
break;
case TLSEXT_TYPE_signature_algorithms:
sigalgs = body;
break;
case TLSEXT_TYPE_signature_algorithms_cert:
sigalgs_cert = body;
break;
case TLSEXT_TYPE_supported_groups:
supported_groups = body;
break;
}
} else if (java_extension.required) {
return false;
}
}
if (CBS_len(&extensions) != 0) {
return false;
}
// JDK 11 never advertises X25519. It is not offered by default, and
// -Djdk.tls.namedGroups=x25519 does not work. This is unusual: many modern
// clients implement X25519.
while (CBS_len(&supported_groups) > 0) {
uint16_t group;
if (!CBS_get_u16(&supported_groups, &group) || //
group == SSL_GROUP_X25519) {
return false;
}
}
if ( // JDK 11 always sends the same contents in signature_algorithms and
// signature_algorithms_cert. This is unusual:
// signature_algorithms_cert, if omitted, is treated as if it were
// signature_algorithms.
sigalgs != sigalgs_cert ||
// When TLS 1.2 or below is enabled, JDK 11 sends status_request_v2 iff it
// sends status_request. This is unusual: status_request_v2 is not widely
// implemented.
has_status_request != has_status_request_v2) {
return false;
}
return true;
}
static bool decrypt_ech(SSL_HANDSHAKE *hs, uint8_t *out_alert,
const SSL_CLIENT_HELLO *client_hello) {
SSL *const ssl = hs->ssl;
CBS body;
if (!ssl_client_hello_get_extension(client_hello, &body,
TLSEXT_TYPE_encrypted_client_hello)) {
return true;
}
uint8_t type;
if (!CBS_get_u8(&body, &type)) {
OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
*out_alert = SSL_AD_DECODE_ERROR;
return false;
}
if (type != ECH_CLIENT_OUTER) {
return true;
}
// This is a ClientHelloOuter ECH extension. Attempt to decrypt it.
uint8_t config_id;
uint16_t kdf_id, aead_id;
CBS enc, payload;
if (!CBS_get_u16(&body, &kdf_id) || //
!CBS_get_u16(&body, &aead_id) || //
!CBS_get_u8(&body, &config_id) ||
!CBS_get_u16_length_prefixed(&body, &enc) ||
!CBS_get_u16_length_prefixed(&body, &payload) || //
CBS_len(&body) != 0) {
OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
*out_alert = SSL_AD_DECODE_ERROR;
return false;
}
{
MutexReadLock lock(&ssl->ctx->lock);
hs->ech_keys = UpRef(ssl->ctx->ech_keys);
}
if (!hs->ech_keys) {
ssl->s3->ech_status = ssl_ech_rejected;
return true;
}
for (const auto &config : hs->ech_keys->configs) {
hs->ech_hpke_ctx.Reset();
if (config_id != config->ech_config().config_id ||
!config->SetupContext(hs->ech_hpke_ctx.get(), kdf_id, aead_id, enc)) {
// Ignore the error and try another ECHConfig.
ERR_clear_error();
continue;
}
bool is_decrypt_error;
if (!ssl_client_hello_decrypt(hs, out_alert, &is_decrypt_error,
&hs->ech_client_hello_buf, client_hello,
payload)) {
if (is_decrypt_error) {
// Ignore the error and try another ECHConfig.
ERR_clear_error();
// The |out_alert| calling convention currently relies on a default of
// |SSL_AD_DECODE_ERROR|. https://crbug.com/boringssl/373 tracks
// switching to sum types, which avoids this.
*out_alert = SSL_AD_DECODE_ERROR;
continue;
}
OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
return false;
}
hs->ech_config_id = config_id;
ssl->s3->ech_status = ssl_ech_accepted;
return true;
}
// If we did not accept ECH, proceed with the ClientHelloOuter. Note this
// could be key mismatch or ECH GREASE, so we must complete the handshake
// as usual, except EncryptedExtensions will contain retry configs.
ssl->s3->ech_status = ssl_ech_rejected;
return true;
}
static bool extract_sni(SSL_HANDSHAKE *hs, uint8_t *out_alert,
const SSL_CLIENT_HELLO *client_hello) {
SSL *const ssl = hs->ssl;
CBS sni;
if (!ssl_client_hello_get_extension(client_hello, &sni,
TLSEXT_TYPE_server_name)) {
// No SNI extension to parse.
//
// Clear state in case we previously extracted SNI from ClientHelloOuter.
ssl->s3->hostname.reset();
return true;
}
CBS server_name_list, host_name;
uint8_t name_type;
if (!CBS_get_u16_length_prefixed(&sni, &server_name_list) || //
!CBS_get_u8(&server_name_list, &name_type) || //
// Although the server_name extension was intended to be extensible to
// new name types and multiple names, OpenSSL 1.0.x had a bug which meant
// different name types will cause an error. Further, RFC 4366 originally
// defined syntax inextensibly. RFC 6066 corrected this mistake, but
// adding new name types is no longer feasible.
//
// Act as if the extensibility does not exist to simplify parsing.
!CBS_get_u16_length_prefixed(&server_name_list, &host_name) || //
CBS_len(&server_name_list) != 0 || //
CBS_len(&sni) != 0) {
*out_alert = SSL_AD_DECODE_ERROR;
return false;
}
if (name_type != TLSEXT_NAMETYPE_host_name || //
CBS_len(&host_name) == 0 || //
CBS_len(&host_name) > TLSEXT_MAXLEN_host_name || //
CBS_contains_zero_byte(&host_name)) {
*out_alert = SSL_AD_UNRECOGNIZED_NAME;
return false;
}
// Copy the hostname as a string.
char *raw = nullptr;
if (!CBS_strdup(&host_name, &raw)) {
*out_alert = SSL_AD_INTERNAL_ERROR;
return false;
}
ssl->s3->hostname.reset(raw);
return true;
}
static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
SSL *const ssl = hs->ssl;
SSLMessage msg;
if (!ssl->method->get_message(ssl, &msg)) {
return ssl_hs_read_message;
}
if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
return ssl_hs_error;
}
SSL_CLIENT_HELLO client_hello;
if (!SSL_parse_client_hello(ssl, &client_hello, CBS_data(&msg.body),
CBS_len(&msg.body))) {
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
return ssl_hs_error;
}
// ClientHello should be the end of the flight. We check this early to cover
// all protocol versions.
if (ssl->method->has_unprocessed_handshake_data(ssl)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
return ssl_hs_error;
}
if (hs->config->handoff) {
return ssl_hs_handoff;
}
uint8_t alert = SSL_AD_DECODE_ERROR;
// We check for rejection status in case we've rewound the state machine after
// determining `ClientHelloInner` is invalid.
if (ssl->s3->ech_status != ssl_ech_rejected &&
!decrypt_ech(hs, &alert, &client_hello)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
return ssl_hs_error;
}
// ECH may have changed which ClientHello we process. Update |msg| and
// |client_hello| in case.
if (!hs->GetClientHello(&msg, &client_hello)) {
OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
return ssl_hs_error;
}
if (!extract_sni(hs, &alert, &client_hello)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
return ssl_hs_error;
}
hs->state = state12_read_client_hello_after_ech;
return ssl_hs_ok;
}
static enum ssl_hs_wait_t do_read_client_hello_after_ech(SSL_HANDSHAKE *hs) {
SSL *const ssl = hs->ssl;
SSLMessage msg_unused;
SSL_CLIENT_HELLO client_hello;
if (!hs->GetClientHello(&msg_unused, &client_hello)) {
return ssl_hs_error;
}
// Run the early callback.
if (ssl->ctx->select_certificate_cb != NULL) {
switch (ssl->ctx->select_certificate_cb(&client_hello)) {
case ssl_select_cert_retry:
return ssl_hs_certificate_selection_pending;
case ssl_select_cert_disable_ech:
hs->ech_client_hello_buf.Reset();
hs->ech_keys = nullptr;
hs->state = state12_read_client_hello;
ssl->s3->ech_status = ssl_ech_rejected;
return ssl_hs_ok;
case ssl_select_cert_error:
// Connection rejected.
OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
return ssl_hs_error;
default:
/* fallthrough */;
}
}
// Freeze the version range after the early callback.
if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
return ssl_hs_error;
}
if (hs->config->jdk11_workaround &&
is_probably_jdk11_with_tls13(&client_hello)) {
hs->apply_jdk11_workaround = true;
}
uint8_t alert = SSL_AD_DECODE_ERROR;
if (!negotiate_version(hs, &alert, &client_hello)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
return ssl_hs_error;
}
hs->client_version = client_hello.version;
if (client_hello.random_len != SSL3_RANDOM_SIZE) {
OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
return ssl_hs_error;
}
OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
client_hello.random_len);
// Only null compression is supported. TLS 1.3 further requires the peer
// advertise no other compression.
if (OPENSSL_memchr(client_hello.compression_methods, 0,
client_hello.compression_methods_len) == NULL ||
(ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
client_hello.compression_methods_len != 1)) {
OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
return ssl_hs_error;
}
// TLS extensions.
if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
return ssl_hs_error;
}
hs->state = state12_cert_callback;
return ssl_hs_ok;
}
static enum ssl_hs_wait_t do_cert_callback(SSL_HANDSHAKE *hs) {
SSL *const ssl = hs->ssl;
// Call |cert_cb| to update server certificates if required.
if (hs->config->cert->cert_cb != NULL) {
int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
if (rv == 0) {
OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
return ssl_hs_error;
}
if (rv < 0) {
return ssl_hs_x509_lookup;
}
}
if (hs->ocsp_stapling_requested &&
ssl->ctx->legacy_ocsp_callback != nullptr) {
switch (ssl->ctx->legacy_ocsp_callback(
ssl, ssl->ctx->legacy_ocsp_callback_arg)) {
case SSL_TLSEXT_ERR_OK:
break;
case SSL_TLSEXT_ERR_NOACK:
hs->ocsp_stapling_requested = false;
break;
default:
OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
return ssl_hs_error;
}
}
if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
// Jump to the TLS 1.3 state machine.
hs->state = state12_tls13;
return ssl_hs_ok;
}
// It should not be possible to negotiate TLS 1.2 with ECH. The
// ClientHelloInner decoding function rejects ClientHellos which offer TLS 1.2
// or below.
assert(ssl->s3->ech_status != ssl_ech_accepted);
ssl->s3->early_data_reason = ssl_early_data_protocol_version;
hs->state = state12_select_parameters;
return ssl_hs_ok;
}
static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
if (wait == ssl_hs_ok) {
hs->state = state12_finish_server_handshake;
return ssl_hs_ok;
}
return wait;
}
static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
SSL *const ssl = hs->ssl;
SSLMessage msg;
SSL_CLIENT_HELLO client_hello;
if (!hs->GetClientHello(&msg, &client_hello)) {
return ssl_hs_error;
}
// Determine the ECDHE group to use, if we are to use ECDHE.
uint16_t group_id = 0;
bool has_ecdhe_group = tls1_get_shared_group(hs, &group_id);
// Select the credential and cipher suite. This must be done after |cert_cb|
// runs, so the final credential list is known.
//
// TODO(davidben): In the course of picking these, we also pick the ECDHE
// group and signature algorithm. It would be tidier if we saved that decision
// and avoided redoing it later.
UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
ssl_parse_client_cipher_list(&client_hello);
if (client_pref == nullptr) {
return ssl_hs_error;
}
Array<SSL_CREDENTIAL *> creds;
if (!ssl_get_full_credential_list(hs, &creds)) {
return ssl_hs_error;
}
TLS12ServerParams params;
if (creds.empty()) {
// The caller may have configured no credentials, but set a PSK callback.
params =
choose_params(hs, /*cred=*/nullptr, client_pref.get(), has_ecdhe_group);
} else {
// Select the first credential which works.
for (SSL_CREDENTIAL *cred : creds) {
ERR_clear_error();
params = choose_params(hs, cred, client_pref.get(), has_ecdhe_group);
if (params.ok()) {
hs->credential = UpRef(cred);
break;
}
}
}
if (!params.ok()) {
// The error from the last attempt is in the error queue.
assert(ERR_peek_error() != 0);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
return ssl_hs_error;
}
hs->new_cipher = params.cipher;
hs->signature_algorithm = params.signature_algorithm;
// |SSL_parse_client_hello| checks that |client_hello.session_id| is not too
// large.
hs->session_id.CopyFrom(
Span(client_hello.session_id, client_hello.session_id_len));
// Determine whether we are doing session resumption.
UniquePtr<SSL_SESSION> session;
bool tickets_supported = false, renew_ticket = false;
enum ssl_hs_wait_t wait = ssl_get_prev_session(
hs, &session, &tickets_supported, &renew_ticket, &client_hello);
if (wait != ssl_hs_ok) {
return wait;
}
if (session) {
if (session->extended_master_secret && !hs->extended_master_secret) {
// A ClientHello without EMS that attempts to resume a session with EMS
// is fatal to the connection.
OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
return ssl_hs_error;
}
if (!ssl_session_is_resumable(hs, session.get()) ||
// If the client offers the EMS extension, but the previous session
// didn't use it, then negotiate a new session.
hs->extended_master_secret != session->extended_master_secret) {
session.reset();
}
}
if (session) {
// Use the old session.
hs->ticket_expected = renew_ticket;
ssl->session = std::move(session);
ssl->s3->session_reused = true;
hs->can_release_private_key = true;
} else {
hs->ticket_expected = tickets_supported;
ssl_set_session(ssl, nullptr);
if (!ssl_get_new_session(hs)) {
return ssl_hs_error;
}
// Assign a session ID if not using session tickets.
if (!hs->ticket_expected &&
(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
hs->new_session->session_id.ResizeForOverwrite(
SSL3_SSL_SESSION_ID_LENGTH);
RAND_bytes(hs->new_session->session_id.data(),
hs->new_session->session_id.size());
}
}
if (ssl->ctx->dos_protection_cb != NULL &&
ssl->ctx->dos_protection_cb(&client_hello) == 0) {
// Connection rejected for DOS reasons.
OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
return ssl_hs_error;
}
if (ssl->session == NULL) {
hs->new_session->cipher = hs->new_cipher;
if (hs->new_session->cipher->algorithm_mkey & SSL_kECDHE) {
assert(has_ecdhe_group);
hs->new_session->group_id = group_id;
}
// Determine whether to request a client certificate.
hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
// Only request a certificate if Channel ID isn't negotiated.
if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
hs->channel_id_negotiated) {
hs->cert_request = false;
}
// CertificateRequest may only be sent in certificate-based ciphers.
if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
hs->cert_request = false;
}
if (!hs->cert_request) {
// OpenSSL returns X509_V_OK when no certificates are requested. This is
// classed by them as a bug, but it's assumed by at least NGINX.
hs->new_session->verify_result = X509_V_OK;
}
}
// HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
// deferred. Complete it now.
uint8_t alert = SSL_AD_DECODE_ERROR;
if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
return ssl_hs_error;
}
// Now that all parameters are known, initialize the handshake hash and hash
// the ClientHello.
if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
return ssl_hs_error;
}
// Handback includes the whole handshake transcript, so we cannot free the
// transcript buffer in the handback case.
if (!hs->cert_request && !hs->handback) {
hs->transcript.FreeBuffer();
}
if (!ssl_hash_message(hs, msg)) {
ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
return ssl_hs_error;
}
ssl->method->next_message(ssl);
hs->state = state12_send_server_hello;
return ssl_hs_ok;
}
static void copy_suffix(Span<uint8_t> out, Span<const uint8_t> in) {
out = out.last(in.size());
OPENSSL_memcpy(out.data(), in.data(), in.size());
}
static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
SSL *const ssl = hs->ssl;
// We only accept ChannelIDs on connections with ECDHE in order to avoid a
// known attack while we fix ChannelID itself.
if (hs->channel_id_negotiated &&
(hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
hs->channel_id_negotiated = false;
}
// If this is a resumption and the original handshake didn't support
// ChannelID then we didn't record the original handshake hashes in the
// session and so cannot resume with ChannelIDs.
if (ssl->session != nullptr &&
ssl->session->original_handshake_hash.empty()) {
hs->channel_id_negotiated = false;
}
SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
if (hints && !hs->hints_requested &&
hints->server_random_tls12.size() == SSL3_RANDOM_SIZE) {
OPENSSL_memcpy(ssl->s3->server_random, hints->server_random_tls12.data(),
SSL3_RANDOM_SIZE);
} else {
OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
CRYPTO_store_u32_be(ssl->s3->server_random,
static_cast<uint32_t>(now.tv_sec));
if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
return ssl_hs_error;
}
if (hints && hs->hints_requested &&
!hints->server_random_tls12.CopyFrom(ssl->s3->server_random)) {
return ssl_hs_error;
}
}
// Implement the TLS 1.3 anti-downgrade feature.
if (hs->max_version >= TLS1_3_VERSION) {
if (ssl_protocol_version(ssl) == TLS1_2_VERSION) {
if (hs->apply_jdk11_workaround) {
// JDK 11 implements the TLS 1.3 downgrade signal, so we cannot send it
// here. However, the signal is only effective if all TLS 1.2
// ServerHellos produced by the server are marked. Thus we send a
// different non-standard signal for the time being, until JDK 11.0.2 is
// released and clients have updated.
copy_suffix(ssl->s3->server_random, kJDK11DowngradeRandom);
} else {
copy_suffix(ssl->s3->server_random, kTLS13DowngradeRandom);
}
} else {
copy_suffix(ssl->s3->server_random, kTLS12DowngradeRandom);
}
}
Span<const uint8_t> session_id;
if (ssl->session != nullptr) {
// Echo the session ID from the ClientHello to indicate resumption.
session_id = hs->session_id;
} else {
session_id = hs->new_session->session_id;
}
ScopedCBB cbb;
CBB body, session_id_bytes;
if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
!CBB_add_u16(&body, ssl->s3->version) ||
!CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
!CBB_add_u8_length_prefixed(&body, &session_id_bytes) ||
!CBB_add_bytes(&session_id_bytes, session_id.data(), session_id.size()) ||
!CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
!CBB_add_u8(&body, 0 /* no compression */) ||
!ssl_add_serverhello_tlsext(hs, &body) ||
!ssl_add_message_cbb(ssl, cbb.get())) {
OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
return ssl_hs_error;
}
if (ssl->session != nullptr) {
// No additional hints to generate in resumption.
if (hs->hints_requested) {
return ssl_hs_hints_ready;
}
hs->state = state12_send_server_finished;
} else {
hs->state = state12_send_server_certificate;
}
return ssl_hs_ok;
}
static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
SSL *const ssl = hs->ssl;
ScopedCBB cbb;
if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
assert(hs->credential != nullptr);
if (!ssl_send_tls12_certificate(hs)) {
return ssl_hs_error;
}
if (hs->certificate_status_expected) {
CBB body, ocsp_response;
if (!ssl->method->init_message(ssl, cbb.get(), &body,
SSL3_MT_CERTIFICATE_STATUS) ||
!CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
!CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
!CBB_add_bytes(
&ocsp_response,
CRYPTO_BUFFER_data(hs->credential->ocsp_response.get()),
CRYPTO_BUFFER_len(hs->credential->ocsp_response.get())) ||