/
ClientHello.java
1468 lines (1300 loc) · 60.2 KB
/
ClientHello.java
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) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.ssl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLProtocolException;
import static sun.security.ssl.ClientAuthType.CLIENT_AUTH_REQUIRED;
import sun.security.ssl.SSLHandshake.HandshakeMessage;
import sun.security.ssl.SupportedVersionsExtension.CHSupportedVersionsSpec;
/**
* Pack of the ClientHello handshake message.
*/
final class ClientHello {
static final SSLProducer kickstartProducer =
new ClientHelloKickstartProducer();
static final SSLConsumer handshakeConsumer =
new ClientHelloConsumer();
static final HandshakeProducer handshakeProducer =
new ClientHelloProducer();
private static final HandshakeConsumer t12HandshakeConsumer =
new T12ClientHelloConsumer();
private static final HandshakeConsumer t13HandshakeConsumer =
new T13ClientHelloConsumer();
private static final HandshakeConsumer d12HandshakeConsumer =
new D12ClientHelloConsumer();
private static final HandshakeConsumer d13HandshakeConsumer =
new D13ClientHelloConsumer();
/**
* The ClientHello handshake message.
*
* See RFC 5264/4346/2246/6347 for the specifications.
*/
static final class ClientHelloMessage extends HandshakeMessage {
private final boolean isDTLS;
final int clientVersion;
final RandomCookie clientRandom;
final SessionId sessionId;
private byte[] cookie; // DTLS only
final int[] cipherSuiteIds;
final List<CipherSuite> cipherSuites; // known cipher suites only
final byte[] compressionMethod;
final SSLExtensions extensions;
private static final byte[] NULL_COMPRESSION = new byte[] {0};
ClientHelloMessage(HandshakeContext handshakeContext,
int clientVersion, SessionId sessionId,
List<CipherSuite> cipherSuites, SecureRandom generator) {
super(handshakeContext);
this.isDTLS = handshakeContext.sslContext.isDTLS();
this.clientVersion = clientVersion;
this.clientRandom = new RandomCookie(generator);
this.sessionId = sessionId;
if (isDTLS) {
this.cookie = new byte[0];
} else {
this.cookie = null;
}
this.cipherSuites = cipherSuites;
this.cipherSuiteIds = getCipherSuiteIds(cipherSuites);
this.extensions = new SSLExtensions(this);
// Don't support compression.
this.compressionMethod = NULL_COMPRESSION;
}
/* Read up to the binders in the PSK extension. After this method
* returns, the ByteBuffer position will be at end of the message
* fragment that should be hashed to produce the PSK binder values.
* The client of this method can use this position to determine the
* message fragment and produce the binder values.
*/
static void readPartial(TransportContext tc,
ByteBuffer m) throws IOException {
boolean isDTLS = tc.sslContext.isDTLS();
// version
Record.getInt16(m);
new RandomCookie(m);
// session ID
Record.getBytes8(m);
// DTLS cookie
if (isDTLS) {
Record.getBytes8(m);
}
// cipher suite IDs
Record.getBytes16(m);
// compression method
Record.getBytes8(m);
// read extensions, if present
if (m.remaining() >= 2) {
int remaining = Record.getInt16(m);
while (remaining > 0) {
int id = Record.getInt16(m);
int extLen = Record.getInt16(m);
remaining -= extLen + 4;
if (id == SSLExtension.CH_PRE_SHARED_KEY.id) {
// ensure pre_shared_key is the last extension
if (remaining > 0) {
throw tc.fatal(Alert.ILLEGAL_PARAMETER,
"pre_shared_key extension is not last");
}
// read only up to the IDs
Record.getBytes16(m);
return;
} else {
m.position(m.position() + extLen);
}
}
} // Otherwise, ignore the remaining bytes.
}
ClientHelloMessage(HandshakeContext handshakeContext, ByteBuffer m,
SSLExtension[] supportedExtensions) throws IOException {
super(handshakeContext);
this.isDTLS = handshakeContext.sslContext.isDTLS();
this.clientVersion = ((m.get() & 0xFF) << 8) | (m.get() & 0xFF);
this.clientRandom = new RandomCookie(m);
this.sessionId = new SessionId(Record.getBytes8(m));
try {
sessionId.checkLength(clientVersion);
} catch (SSLProtocolException ex) {
throw handshakeContext.conContext.fatal(
Alert.ILLEGAL_PARAMETER, ex);
}
if (isDTLS) {
this.cookie = Record.getBytes8(m);
} else {
this.cookie = null;
}
byte[] encodedIds = Record.getBytes16(m);
if (encodedIds.length == 0 || (encodedIds.length & 0x01) != 0) {
throw handshakeContext.conContext.fatal(
Alert.ILLEGAL_PARAMETER,
"Invalid ClientHello message");
}
this.cipherSuiteIds = new int[encodedIds.length >> 1];
for (int i = 0, j = 0; i < encodedIds.length; i++, j++) {
cipherSuiteIds[j] =
((encodedIds[i++] & 0xFF) << 8) | (encodedIds[i] & 0xFF);
}
this.cipherSuites = getCipherSuites(cipherSuiteIds);
this.compressionMethod = Record.getBytes8(m);
// In TLS 1.3, use of certain extensions is mandatory.
if (m.hasRemaining()) {
this.extensions =
new SSLExtensions(this, m, supportedExtensions);
} else {
this.extensions = new SSLExtensions(this);
}
}
void setHelloCookie(byte[] cookie) {
this.cookie = cookie;
}
// DTLS 1.0/1.2, for cookie generation.
byte[] getHelloCookieBytes() {
HandshakeOutStream hos = new HandshakeOutStream(null);
try {
// copied from send() method
hos.putInt8((byte)((clientVersion >>> 8) & 0xFF));
hos.putInt8((byte)(clientVersion & 0xFF));
hos.write(clientRandom.randomBytes, 0, 32);
hos.putBytes8(sessionId.getId());
// ignore cookie
hos.putBytes16(getEncodedCipherSuites());
hos.putBytes8(compressionMethod);
extensions.send(hos); // In TLS 1.3, use of certain
// extensions is mandatory.
} catch (IOException ioe) {
// unlikely
}
return hos.toByteArray();
}
// (D)TLS 1.3, for cookie generation.
byte[] getHeaderBytes() {
HandshakeOutStream hos = new HandshakeOutStream(null);
try {
// copied from send() method
hos.putInt8((byte)((clientVersion >>> 8) & 0xFF));
hos.putInt8((byte)(clientVersion & 0xFF));
hos.write(clientRandom.randomBytes, 0, 32);
hos.putBytes8(sessionId.getId());
hos.putBytes16(getEncodedCipherSuites());
hos.putBytes8(compressionMethod);
} catch (IOException ioe) {
// unlikely
}
return hos.toByteArray();
}
private static int[] getCipherSuiteIds(
List<CipherSuite> cipherSuites) {
if (cipherSuites != null) {
int[] ids = new int[cipherSuites.size()];
int i = 0;
for (CipherSuite cipherSuite : cipherSuites) {
ids[i++] = cipherSuite.id;
}
return ids;
}
return new int[0];
}
private static List<CipherSuite> getCipherSuites(int[] ids) {
List<CipherSuite> cipherSuites = new LinkedList<>();
for (int id : ids) {
CipherSuite cipherSuite = CipherSuite.valueOf(id);
if (cipherSuite != null) {
cipherSuites.add(cipherSuite);
}
}
return Collections.unmodifiableList(cipherSuites);
}
private List<String> getCipherSuiteNames() {
List<String> names = new LinkedList<>();
for (int id : cipherSuiteIds) {
names.add(CipherSuite.nameOf(id) +
"(" + Utilities.byte16HexString(id) + ")"); }
return names;
}
private byte[] getEncodedCipherSuites() {
byte[] encoded = new byte[cipherSuiteIds.length << 1];
int i = 0;
for (int id : cipherSuiteIds) {
encoded[i++] = (byte)(id >> 8);
encoded[i++] = (byte)id;
}
return encoded;
}
@Override
public SSLHandshake handshakeType() {
return SSLHandshake.CLIENT_HELLO;
}
@Override
public int messageLength() {
/*
* Add fixed size parts of each field...
* version + random + session + cipher + compress
*/
return (2 + 32 + 1 + 2 + 1
+ sessionId.length() /* ... + variable parts */
+ (isDTLS ? (1 + cookie.length) : 0)
+ (cipherSuiteIds.length * 2)
+ compressionMethod.length)
+ extensions.length(); // In TLS 1.3, use of certain
// extensions is mandatory.
}
@Override
public void send(HandshakeOutStream hos) throws IOException {
sendCore(hos);
extensions.send(hos); // In TLS 1.3, use of certain
// extensions is mandatory.
}
void sendCore(HandshakeOutStream hos) throws IOException {
hos.putInt8((byte) (clientVersion >>> 8));
hos.putInt8((byte) clientVersion);
hos.write(clientRandom.randomBytes, 0, 32);
hos.putBytes8(sessionId.getId());
if (isDTLS) {
hos.putBytes8(cookie);
}
hos.putBytes16(getEncodedCipherSuites());
hos.putBytes8(compressionMethod);
}
@Override
public String toString() {
if (isDTLS) {
MessageFormat messageFormat = new MessageFormat(
"\"ClientHello\": '{'\n" +
" \"client version\" : \"{0}\",\n" +
" \"random\" : \"{1}\",\n" +
" \"session id\" : \"{2}\",\n" +
" \"cookie\" : \"{3}\",\n" +
" \"cipher suites\" : \"{4}\",\n" +
" \"compression methods\" : \"{5}\",\n" +
" \"extensions\" : [\n" +
"{6}\n" +
" ]\n" +
"'}'",
Locale.ENGLISH);
Object[] messageFields = {
ProtocolVersion.nameOf(clientVersion),
Utilities.toHexString(clientRandom.randomBytes),
sessionId.toString(),
Utilities.toHexString(cookie),
getCipherSuiteNames().toString(),
Utilities.toHexString(compressionMethod),
Utilities.indent(Utilities.indent(extensions.toString()))
};
return messageFormat.format(messageFields);
} else {
MessageFormat messageFormat = new MessageFormat(
"\"ClientHello\": '{'\n" +
" \"client version\" : \"{0}\",\n" +
" \"random\" : \"{1}\",\n" +
" \"session id\" : \"{2}\",\n" +
" \"cipher suites\" : \"{3}\",\n" +
" \"compression methods\" : \"{4}\",\n" +
" \"extensions\" : [\n" +
"{5}\n" +
" ]\n" +
"'}'",
Locale.ENGLISH);
Object[] messageFields = {
ProtocolVersion.nameOf(clientVersion),
Utilities.toHexString(clientRandom.randomBytes),
sessionId.toString(),
getCipherSuiteNames().toString(),
Utilities.toHexString(compressionMethod),
Utilities.indent(Utilities.indent(extensions.toString()))
};
return messageFormat.format(messageFields);
}
}
}
/**
* The "ClientHello" handshake message kick start producer.
*/
private static final
class ClientHelloKickstartProducer implements SSLProducer {
// Prevent instantiation of this class.
private ClientHelloKickstartProducer() {
// blank
}
// Produce kickstart handshake message.
@Override
public byte[] produce(ConnectionContext context) throws IOException {
// The producing happens in client side only.
ClientHandshakeContext chc = (ClientHandshakeContext)context;
// clean up this producer
chc.handshakeProducers.remove(SSLHandshake.CLIENT_HELLO.id);
// session ID of the ClientHello message
SessionId sessionId = new SessionId(new byte[0]);
// a list of cipher suites sent by the client
List<CipherSuite> cipherSuites = chc.activeCipherSuites;
//
// Try to resume an existing session.
//
SSLSessionContextImpl ssci = (SSLSessionContextImpl)
chc.sslContext.engineGetClientSessionContext();
SSLSessionImpl session = ssci.get(
chc.conContext.transport.getPeerHost(),
chc.conContext.transport.getPeerPort());
if (session != null) {
// If unsafe server certificate change is not allowed, reserve
// current server certificates if the previous handshake is a
// session-resumption abbreviated initial handshake.
if (!ClientHandshakeContext.allowUnsafeServerCertChange &&
session.isSessionResumption()) {
try {
// If existing, peer certificate chain cannot be null.
chc.reservedServerCerts =
(X509Certificate[])session.getPeerCertificates();
} catch (SSLPeerUnverifiedException puve) {
// Maybe not certificate-based, ignore the exception.
}
}
if (!session.isRejoinable()) {
session = null;
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, the session is not rejoinable");
}
}
}
CipherSuite sessionSuite = null;
if (session != null) {
sessionSuite = session.getSuite();
if (!chc.isNegotiable(sessionSuite)) {
session = null;
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, unavailable session cipher suite");
}
}
}
ProtocolVersion sessionVersion = null;
if (session != null) {
sessionVersion = session.getProtocolVersion();
if (!chc.isNegotiable(sessionVersion)) {
session = null;
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, unavailable protocol version");
}
}
}
if (session != null &&
!sessionVersion.useTLS13PlusSpec() &&
SSLConfiguration.useExtendedMasterSecret) {
boolean isEmsAvailable = chc.sslConfig.isAvailable(
SSLExtension.CH_EXTENDED_MASTER_SECRET, sessionVersion);
if (isEmsAvailable && !session.useExtendedMasterSecret &&
!SSLConfiguration.allowLegacyResumption) {
// perform full handshake instead
//
// The client SHOULD NOT offer an abbreviated handshake
// to resume a session that does not use an extended
// master secret. Instead, it SHOULD offer a full
// handshake.
session = null;
}
if ((session != null) &&
!ClientHandshakeContext.allowUnsafeServerCertChange) {
// It is fine to move on with abbreviate handshake if
// endpoint identification is enabled.
String identityAlg = chc.sslConfig.identificationProtocol;
if (identityAlg == null || identityAlg.isEmpty()) {
if (isEmsAvailable) {
if (!session.useExtendedMasterSecret) {
// perform full handshake instead
session = null;
} // Otherwise, use extended master secret.
} else {
// The extended master secret extension does not
// apply to SSL 3.0. Perform a full handshake
// instead.
//
// Note that the useExtendedMasterSecret is
// extended to protect SSL 3.0 connections,
// by discarding abbreviate handshake.
session = null;
}
}
}
}
// ensure that the endpoint identification algorithm matches the
// one in the session
String identityAlg = chc.sslConfig.identificationProtocol;
if (session != null && identityAlg != null) {
String sessionIdentityAlg =
session.getIdentificationProtocol();
if (!identityAlg.equalsIgnoreCase(sessionIdentityAlg)) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest("Can't resume, endpoint id" +
" algorithm does not match, requested: " +
identityAlg + ", cached: " + sessionIdentityAlg);
}
session = null;
}
}
if (session != null) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest("Try resuming session", session);
}
// only set session id if session is 1.2 or earlier
if (!session.getProtocolVersion().useTLS13PlusSpec()) {
sessionId = session.getSessionId();
}
// If no new session is allowed, force use of the previous
// session ciphersuite, and add the renegotiation SCSV if
// necessary.
if (!chc.sslConfig.enableSessionCreation) {
if (!chc.conContext.isNegotiated &&
!sessionVersion.useTLS13PlusSpec() &&
cipherSuites.contains(
CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
cipherSuites = Arrays.asList(sessionSuite,
CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
} else { // otherwise, use renegotiation_info extension
cipherSuites = List.of(sessionSuite);
}
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"No new session is allowed, so try to resume " +
"the session cipher suite only", sessionSuite);
}
}
chc.isResumption = true;
chc.resumingSession = session;
}
if (session == null) {
if (!chc.sslConfig.enableSessionCreation) {
throw new SSLHandshakeException(
"No new session is allowed and " +
"no existing session can be resumed");
}
}
if (sessionId.length() == 0 &&
chc.maximumActiveProtocol.useTLS13PlusSpec() &&
SSLConfiguration.useCompatibilityMode) {
// In compatibility mode, the TLS 1.3 legacy_session_id
// field MUST be non-empty, so a client not offering a
// pre-TLS 1.3 session MUST generate a new 32-byte value.
sessionId =
new SessionId(true, chc.sslContext.getSecureRandom());
}
ProtocolVersion minimumVersion = ProtocolVersion.NONE;
for (ProtocolVersion pv : chc.activeProtocols) {
if (minimumVersion == ProtocolVersion.NONE ||
pv.compare(minimumVersion) < 0) {
minimumVersion = pv;
}
}
// exclude SCSV for secure renegotiation
if (!minimumVersion.useTLS13PlusSpec()) {
if (chc.conContext.secureRenegotiation &&
cipherSuites.contains(
CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
// The cipherSuites may be unmodifiable
cipherSuites = new LinkedList<>(cipherSuites);
cipherSuites.remove(
CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
}
}
// make sure there is a negotiable cipher suite.
boolean negotiable = false;
for (CipherSuite suite : cipherSuites) {
if (chc.isNegotiable(suite)) {
negotiable = true;
break;
}
}
if (!negotiable) {
throw new SSLHandshakeException("No negotiable cipher suite");
}
// Create the handshake message.
ProtocolVersion clientHelloVersion = chc.maximumActiveProtocol;
if (clientHelloVersion.useTLS13PlusSpec()) {
// In (D)TLS 1.3, the client indicates its version preferences
// in the "supported_versions" extension and the client_version
// (legacy_version) field MUST be set to (D)TLS 1.2.
if (clientHelloVersion.isDTLS) {
clientHelloVersion = ProtocolVersion.DTLS12;
} else {
clientHelloVersion = ProtocolVersion.TLS12;
}
}
ClientHelloMessage chm = new ClientHelloMessage(chc,
clientHelloVersion.id, sessionId, cipherSuites,
chc.sslContext.getSecureRandom());
// cache the client random number for further using
chc.clientHelloRandom = chm.clientRandom;
chc.clientHelloVersion = clientHelloVersion.id;
// Produce extensions for ClientHello handshake message.
SSLExtension[] extTypes = chc.sslConfig.getEnabledExtensions(
SSLHandshake.CLIENT_HELLO, chc.activeProtocols);
chm.extensions.produce(chc, extTypes);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Produced ClientHello handshake message", chm);
}
// Output the handshake message.
chm.write(chc.handshakeOutput);
chc.handshakeOutput.flush();
// Reserve the initial ClientHello message for the follow on
// cookie exchange if needed.
chc.initialClientHelloMsg = chm;
// What's the expected response?
chc.handshakeConsumers.put(
SSLHandshake.SERVER_HELLO.id, SSLHandshake.SERVER_HELLO);
if (chc.sslContext.isDTLS() &&
!minimumVersion.useTLS13PlusSpec()) {
chc.handshakeConsumers.put(
SSLHandshake.HELLO_VERIFY_REQUEST.id,
SSLHandshake.HELLO_VERIFY_REQUEST);
}
// The handshake message has been delivered.
return null;
}
}
private static final
class ClientHelloProducer implements HandshakeProducer {
// Prevent instantiation of this class.
private ClientHelloProducer() {
// blank
}
// Response to one of the following handshake message:
// HelloRequest (SSL 3.0/TLS 1.0/1.1/1.2)
// ServerHello(HelloRetryRequest) (TLS 1.3)
// HelloVerifyRequest (DTLS 1.0/1.2)
@Override
public byte[] produce(ConnectionContext context,
HandshakeMessage message) throws IOException {
// The producing happens in client side only.
ClientHandshakeContext chc = (ClientHandshakeContext)context;
SSLHandshake ht = message.handshakeType();
if (ht == null) {
throw new UnsupportedOperationException("Not supported yet.");
}
switch (ht) {
case HELLO_REQUEST:
// SSL 3.0/TLS 1.0/1.1/1.2
try {
chc.kickstart();
} catch (IOException ioe) {
throw chc.conContext.fatal(
Alert.HANDSHAKE_FAILURE, ioe);
}
// The handshake message has been delivered.
return null;
case HELLO_VERIFY_REQUEST:
// DTLS 1.0/1.2
//
// The HelloVerifyRequest consumer should have updated the
// ClientHello handshake message with cookie.
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Produced ClientHello(cookie) handshake message",
chc.initialClientHelloMsg);
}
// Output the handshake message.
chc.initialClientHelloMsg.write(chc.handshakeOutput);
chc.handshakeOutput.flush();
// What's the expected response?
chc.handshakeConsumers.put(SSLHandshake.SERVER_HELLO.id,
SSLHandshake.SERVER_HELLO);
ProtocolVersion minimumVersion = ProtocolVersion.NONE;
for (ProtocolVersion pv : chc.activeProtocols) {
if (minimumVersion == ProtocolVersion.NONE ||
pv.compare(minimumVersion) < 0) {
minimumVersion = pv;
}
}
if (chc.sslContext.isDTLS() &&
!minimumVersion.useTLS13PlusSpec()) {
chc.handshakeConsumers.put(
SSLHandshake.HELLO_VERIFY_REQUEST.id,
SSLHandshake.HELLO_VERIFY_REQUEST);
}
// The handshake message has been delivered.
return null;
case HELLO_RETRY_REQUEST:
// TLS 1.3
// The HelloRetryRequest consumer should have updated the
// ClientHello handshake message with cookie.
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Produced ClientHello(HRR) handshake message",
chc.initialClientHelloMsg);
}
// Output the handshake message.
chc.initialClientHelloMsg.write(chc.handshakeOutput);
chc.handshakeOutput.flush();
// What's the expected response?
chc.conContext.consumers.putIfAbsent(
ContentType.CHANGE_CIPHER_SPEC.id,
ChangeCipherSpec.t13Consumer);
chc.handshakeConsumers.put(SSLHandshake.SERVER_HELLO.id,
SSLHandshake.SERVER_HELLO);
// The handshake message has been delivered.
return null;
default:
throw new UnsupportedOperationException(
"Not supported yet.");
}
}
}
/**
* The "ClientHello" handshake message consumer.
*/
private static final class ClientHelloConsumer implements SSLConsumer {
// Prevent instantiation of this class.
private ClientHelloConsumer() {
// blank
}
@Override
public void consume(ConnectionContext context,
ByteBuffer message) throws IOException {
// The consuming happens in server side only.
ServerHandshakeContext shc = (ServerHandshakeContext)context;
// clean up this consumer
shc.handshakeConsumers.remove(SSLHandshake.CLIENT_HELLO.id);
if (!shc.handshakeConsumers.isEmpty()) {
throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"No more handshake message allowed " +
"in a ClientHello flight");
}
// Get enabled extension types in ClientHello handshake message.
SSLExtension[] enabledExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.CLIENT_HELLO);
ClientHelloMessage chm =
new ClientHelloMessage(shc, message, enabledExtensions);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Consuming ClientHello handshake message", chm);
}
shc.clientHelloVersion = chm.clientVersion;
onClientHello(shc, chm);
}
private void onClientHello(ServerHandshakeContext context,
ClientHelloMessage clientHello) throws IOException {
// Negotiate protocol version.
//
// Check and launch SupportedVersions.
SSLExtension[] extTypes = new SSLExtension[] {
SSLExtension.CH_SUPPORTED_VERSIONS
};
clientHello.extensions.consumeOnLoad(context, extTypes);
ProtocolVersion negotiatedProtocol;
CHSupportedVersionsSpec svs =
(CHSupportedVersionsSpec)context.handshakeExtensions.get(
SSLExtension.CH_SUPPORTED_VERSIONS);
if (svs != null) {
negotiatedProtocol =
negotiateProtocol(context, svs.requestedProtocols);
} else {
negotiatedProtocol =
negotiateProtocol(context, clientHello.clientVersion);
}
context.negotiatedProtocol = negotiatedProtocol;
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Negotiated protocol version: " + negotiatedProtocol.name);
}
// Consume the handshake message for the specific protocol version.
if (negotiatedProtocol.isDTLS) {
if (negotiatedProtocol.useTLS13PlusSpec()) {
d13HandshakeConsumer.consume(context, clientHello);
} else {
d12HandshakeConsumer.consume(context, clientHello);
}
} else {
if (negotiatedProtocol.useTLS13PlusSpec()) {
t13HandshakeConsumer.consume(context, clientHello);
} else {
t12HandshakeConsumer.consume(context, clientHello);
}
}
}
// Select a protocol version according to the
// ClientHello.client_version.
private ProtocolVersion negotiateProtocol(
ServerHandshakeContext context,
int clientHelloVersion) throws SSLException {
// Per TLS 1.3 specification, server MUST negotiate TLS 1.2 or prior
// even if ClientHello.client_version is 0x0304 or later.
int chv = clientHelloVersion;
if (context.sslContext.isDTLS()) {
if (chv < ProtocolVersion.DTLS12.id) {
chv = ProtocolVersion.DTLS12.id;
}
} else {
if (chv > ProtocolVersion.TLS12.id) {
chv = ProtocolVersion.TLS12.id;
}
}
// Select a protocol version from the activated protocols.
ProtocolVersion pv = ProtocolVersion.selectedFrom(
context.activeProtocols, chv);
if (pv == null || pv == ProtocolVersion.NONE ||
pv == ProtocolVersion.SSL20Hello) {
throw context.conContext.fatal(Alert.PROTOCOL_VERSION,
"Client requested protocol " +
ProtocolVersion.nameOf(clientHelloVersion) +
" is not enabled or supported in server context");
}
return pv;
}
// Select a protocol version according to the
// supported_versions extension.
private ProtocolVersion negotiateProtocol(
ServerHandshakeContext context,
int[] clientSupportedVersions) throws SSLException {
// The client supported protocol versions are present in client
// preference order. This implementation chooses to use the server
// preference of protocol versions instead.
for (ProtocolVersion spv : context.activeProtocols) {
if (spv == ProtocolVersion.SSL20Hello) {
continue;
}
for (int cpv : clientSupportedVersions) {
if (cpv == ProtocolVersion.SSL20Hello.id) {
continue;
}
if (spv.id == cpv) {
return spv;
}
}
}
// No protocol version can be negotiated.
throw context.conContext.fatal(Alert.PROTOCOL_VERSION,
"The client supported protocol versions " + Arrays.toString(
ProtocolVersion.toStringArray(clientSupportedVersions)) +
" are not accepted by server preferences " +
context.activeProtocols);
}
}
/**
* The "ClientHello" handshake message consumer for TLS 1.2 and
* prior SSL/TLS protocol versions.
*/
private static final
class T12ClientHelloConsumer implements HandshakeConsumer {
// Prevent instantiation of this class.
private T12ClientHelloConsumer() {
// blank
}
@Override
public void consume(ConnectionContext context,
HandshakeMessage message) throws IOException {
// The consuming happens in server side only.
ServerHandshakeContext shc = (ServerHandshakeContext)context;
ClientHelloMessage clientHello = (ClientHelloMessage)message;
//
// validate
//
// Reject client initiated renegotiation?
//
// If server side should reject client-initiated renegotiation,
// send an Alert.HANDSHAKE_FAILURE fatal alert, not a
// no_renegotiation warning alert (no_renegotiation must be a
// warning: RFC 2246). no_renegotiation might seem more
// natural at first, but warnings are not appropriate because
// the sending party does not know how the receiving party
// will behave. This state must be treated as a fatal server
// condition.
//
// This will not have any impact on server initiated renegotiation.
if (shc.conContext.isNegotiated) {
if (!shc.conContext.secureRenegotiation &&
!HandshakeContext.allowUnsafeRenegotiation) {
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"Unsafe renegotiation is not allowed");
}
if (ServerHandshakeContext.rejectClientInitiatedRenego &&
!shc.kickstartMessageDelivered) {
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"Client initiated renegotiation is not allowed");
}
}
// Consume a Session Ticket Extension if it exists
SSLExtension[] ext = new SSLExtension[]{
SSLExtension.CH_SESSION_TICKET
};
clientHello.extensions.consumeOnLoad(shc, ext);
// Does the client want to resume a session?
if (clientHello.sessionId.length() != 0 || shc.statelessResumption) {
SSLSessionContextImpl cache = (SSLSessionContextImpl)shc.sslContext
.engineGetServerSessionContext();
SSLSessionImpl previous;
// Use the stateless session ticket if provided
if (shc.statelessResumption) {
previous = shc.resumingSession;
} else {
previous = cache.get(clientHello.sessionId.getId());
}
boolean resumingSession =
(previous != null) && previous.isRejoinable();
if (!resumingSession) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, " +
"the existing session is not rejoinable");
}
}
// Validate the negotiated protocol version.
if (resumingSession) {
ProtocolVersion sessionProtocol =
previous.getProtocolVersion();
if (sessionProtocol != shc.negotiatedProtocol) {
resumingSession = false;
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, not the same protocol version");
}
}