-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathServerHello.java
More file actions
1476 lines (1287 loc) · 61.7 KB
/
Copy pathServerHello.java
File metadata and controls
1476 lines (1287 loc) · 61.7 KB
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, 2025, 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.AlgorithmConstraints;
import java.security.GeneralSecurityException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLProtocolException;
import sun.security.ssl.CipherSuite.KeyExchange;
import sun.security.ssl.ClientHello.ClientHelloMessage;
import sun.security.ssl.SSLCipher.SSLReadCipher;
import sun.security.ssl.SSLCipher.SSLWriteCipher;
import sun.security.ssl.SSLHandshake.HandshakeMessage;
import sun.security.ssl.SupportedVersionsExtension.SHSupportedVersionsSpec;
/**
* Pack of the ServerHello/HelloRetryRequest handshake message.
*/
final class ServerHello {
static final SSLConsumer handshakeConsumer =
new ServerHelloConsumer();
static final HandshakeProducer t12HandshakeProducer =
new T12ServerHelloProducer();
static final HandshakeProducer t13HandshakeProducer =
new T13ServerHelloProducer();
static final HandshakeProducer hrrHandshakeProducer =
new T13HelloRetryRequestProducer();
static final HandshakeProducer hrrReproducer =
new T13HelloRetryRequestReproducer();
private static final HandshakeConsumer t12HandshakeConsumer =
new T12ServerHelloConsumer();
private static final HandshakeConsumer t13HandshakeConsumer =
new T13ServerHelloConsumer();
private static final HandshakeConsumer d12HandshakeConsumer =
new T12ServerHelloConsumer();
private static final HandshakeConsumer d13HandshakeConsumer =
new T13ServerHelloConsumer();
private static final HandshakeConsumer t13HrrHandshakeConsumer =
new T13HelloRetryRequestConsumer();
private static final HandshakeConsumer d13HrrHandshakeConsumer =
new T13HelloRetryRequestConsumer();
/**
* The ServerHello handshake message.
*/
static final class ServerHelloMessage extends HandshakeMessage {
final ProtocolVersion serverVersion; // TLS 1.3 legacy
final RandomCookie serverRandom;
final SessionId sessionId; // TLS 1.3 legacy
final CipherSuite cipherSuite;
final byte compressionMethod; // TLS 1.3 legacy
final SSLExtensions extensions;
// The HelloRetryRequest producer needs to use the ClientHello message
// for cookie generation. Please don't use this field for other
// purpose unless it is really necessary.
final ClientHelloMessage clientHello;
// Reserved for HelloRetryRequest consumer. Please don't use this
// field for other purpose unless it is really necessary.
final ByteBuffer handshakeRecord;
ServerHelloMessage(HandshakeContext context,
ProtocolVersion serverVersion, SessionId sessionId,
CipherSuite cipherSuite, RandomCookie serverRandom,
ClientHelloMessage clientHello) {
super(context);
this.serverVersion = serverVersion;
this.serverRandom = serverRandom;
this.sessionId = sessionId;
this.cipherSuite = cipherSuite;
this.compressionMethod = 0x00; // Don't support compression.
this.extensions = new SSLExtensions(this);
// Reserve the ClientHello message for cookie generation.
this.clientHello = clientHello;
// The handshakeRecord field is used for HelloRetryRequest consumer
// only. It's fine to set it to null for generating side of the
// ServerHello/HelloRetryRequest message.
this.handshakeRecord = null;
}
ServerHelloMessage(HandshakeContext context,
ByteBuffer m) throws IOException {
super(context);
// Reserve for HelloRetryRequest consumer if needed.
this.handshakeRecord = m.duplicate();
byte major = m.get();
byte minor = m.get();
this.serverVersion = ProtocolVersion.valueOf(major, minor);
if (this.serverVersion == null) {
// The client should only request for known protocol versions.
throw context.conContext.fatal(Alert.PROTOCOL_VERSION,
"Unsupported protocol version: " +
ProtocolVersion.nameOf(major, minor));
}
this.serverRandom = new RandomCookie(m);
this.sessionId = new SessionId(Record.getBytes8(m));
try {
sessionId.checkLength(serverVersion.id);
} catch (SSLProtocolException ex) {
throw handshakeContext.conContext.fatal(
Alert.ILLEGAL_PARAMETER, ex);
}
int cipherSuiteId = Record.getInt16(m);
this.cipherSuite = CipherSuite.valueOf(cipherSuiteId);
if (cipherSuite == null || !context.isNegotiable(cipherSuite)) {
throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER,
"Server selected improper ciphersuite " +
CipherSuite.nameOf(cipherSuiteId));
}
this.compressionMethod = m.get();
if (compressionMethod != 0) {
throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER,
"compression type not supported, " + compressionMethod);
}
SSLExtension[] supportedExtensions;
if (serverRandom.isHelloRetryRequest()) {
supportedExtensions = context.sslConfig.getEnabledExtensions(
SSLHandshake.HELLO_RETRY_REQUEST);
} else {
supportedExtensions = context.sslConfig.getEnabledExtensions(
SSLHandshake.SERVER_HELLO);
}
if (m.hasRemaining()) {
this.extensions =
new SSLExtensions(this, m, supportedExtensions);
} else {
this.extensions = new SSLExtensions(this);
}
// The clientHello field is used for HelloRetryRequest producer
// only. It's fine to set it to null for receiving side of
// ServerHello/HelloRetryRequest message.
this.clientHello = null; // not used, let it be null;
}
@Override
public SSLHandshake handshakeType() {
return serverRandom.isHelloRetryRequest() ?
SSLHandshake.HELLO_RETRY_REQUEST : SSLHandshake.SERVER_HELLO;
}
@Override
public int messageLength() {
// almost fixed header size, except session ID and extensions:
// major + minor = 2
// random = 32
// session ID len field = 1
// cipher suite = 2
// compression = 1
// extensions: if present, 2 + length of extensions
// In TLS 1.3, use of certain extensions is mandatory.
return 38 + sessionId.length() + extensions.length();
}
@Override
public void send(HandshakeOutStream hos) throws IOException {
hos.putInt8(serverVersion.major);
hos.putInt8(serverVersion.minor);
hos.write(serverRandom.randomBytes);
hos.putBytes8(sessionId.getId());
hos.putInt8((cipherSuite.id >> 8) & 0xFF);
hos.putInt8(cipherSuite.id & 0xff);
hos.putInt8(compressionMethod);
extensions.send(hos); // In TLS 1.3, use of certain
// extensions is mandatory.
}
@Override
public String toString() {
MessageFormat messageFormat = new MessageFormat(
"\"{0}\": '{'\n" +
" \"server version\" : \"{1}\",\n" +
" \"random\" : \"{2}\",\n" +
" \"session id\" : \"{3}\",\n" +
" \"cipher suite\" : \"{4}\",\n" +
" \"compression methods\" : \"{5}\",\n" +
" \"extensions\" : [\n" +
"{6}\n" +
" ]\n" +
"'}'",
Locale.ENGLISH);
Object[] messageFields = {
serverRandom.isHelloRetryRequest() ?
"HelloRetryRequest" : "ServerHello",
serverVersion.name,
Utilities.toHexString(serverRandom.randomBytes),
sessionId.toString(),
cipherSuite.name + "(" +
Utilities.byte16HexString(cipherSuite.id) + ")",
Utilities.toHexString(compressionMethod),
Utilities.indent(extensions.toString(), " ")
};
return messageFormat.format(messageFields);
}
}
/**
* The "ServerHello" handshake message producer.
*/
private static final class T12ServerHelloProducer
implements HandshakeProducer {
// Prevent instantiation of this class.
private T12ServerHelloProducer() {
// blank
}
@Override
public byte[] produce(ConnectionContext context,
HandshakeMessage message) throws IOException {
// The producing happens in server side only.
ServerHandshakeContext shc = (ServerHandshakeContext)context;
ClientHelloMessage clientHello = (ClientHelloMessage)message;
// If client hasn't specified a session we can resume, start a
// new one and choose its cipher suite and compression options,
// unless new session creation is disabled for this connection!
if (!shc.isResumption || shc.resumingSession == null) {
if (!shc.sslConfig.enableSessionCreation) {
throw new SSLException(
"Not resumption, and no new session is allowed");
}
SSLSessionImpl session =
new SSLSessionImpl(shc, CipherSuite.C_NULL);
session.setMaximumPacketSize(shc.sslConfig.maximumPacketSize);
shc.handshakeSession = session;
// consider the handshake extension impact
SSLExtension[] enabledExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.CLIENT_HELLO, shc.negotiatedProtocol);
clientHello.extensions.consumeOnTrade(shc, enabledExtensions);
// negotiate the cipher suite.
KeyExchangeProperties credentials =
chooseCipherSuite(shc, clientHello);
if (credentials == null) {
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"no cipher suites in common");
}
shc.negotiatedCipherSuite = credentials.cipherSuite;
shc.handshakeKeyExchange = credentials.keyExchange;
shc.handshakeSession.setSuite(credentials.cipherSuite);
shc.handshakePossessions.addAll(
Arrays.asList(credentials.possessions));
shc.handshakeHash.determine(
shc.negotiatedProtocol, shc.negotiatedCipherSuite);
// Check the incoming OCSP stapling extensions and attempt
// to get responses. If the resulting stapleParams is non
// null, it implies that stapling is enabled on the server side.
shc.stapleParams = StatusResponseManager.processStapling(shc);
shc.staplingActive = (shc.stapleParams != null);
// update the responders
SSLKeyExchange ke = credentials.keyExchange;
if (ke != null) {
for (Map.Entry<Byte, HandshakeProducer> me :
ke.getHandshakeProducers(shc)) {
shc.handshakeProducers.put(
me.getKey(), me.getValue());
}
}
if ((ke != null) &&
(shc.sslConfig.clientAuthType !=
ClientAuthType.CLIENT_AUTH_NONE) &&
!shc.negotiatedCipherSuite.isAnonymous()) {
for (SSLHandshake hs :
ke.getRelatedHandshakers(shc)) {
if (hs == SSLHandshake.CERTIFICATE) {
shc.handshakeProducers.put(
SSLHandshake.CERTIFICATE_REQUEST.id,
SSLHandshake.CERTIFICATE_REQUEST);
break;
}
}
}
shc.handshakeProducers.put(SSLHandshake.SERVER_HELLO_DONE.id,
SSLHandshake.SERVER_HELLO_DONE);
} else {
shc.handshakeSession = shc.resumingSession;
shc.negotiatedProtocol =
shc.resumingSession.getProtocolVersion();
shc.negotiatedCipherSuite = shc.resumingSession.getSuite();
shc.handshakeHash.determine(
shc.negotiatedProtocol, shc.negotiatedCipherSuite);
}
// Generate the ServerHello handshake message.
ServerHelloMessage shm = new ServerHelloMessage(shc,
shc.negotiatedProtocol,
shc.handshakeSession.getSessionId(),
shc.negotiatedCipherSuite,
new RandomCookie(shc),
clientHello);
shc.serverHelloRandom = shm.serverRandom;
// Produce extensions for ServerHello handshake message.
SSLExtension[] serverHelloExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.SERVER_HELLO, shc.negotiatedProtocol);
shm.extensions.produce(shc, serverHelloExtensions);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Produced ServerHello handshake message", shm);
}
// Output the handshake message.
shm.write(shc.handshakeOutput);
shc.handshakeOutput.flush();
if (shc.isResumption && shc.resumingSession != null) {
SSLTrafficKeyDerivation kdg =
SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol);
if (kdg == null) {
// unlikely
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
"Not supported key derivation: " +
shc.negotiatedProtocol);
} else {
shc.handshakeKeyDerivation = kdg.createKeyDerivation(
shc, shc.resumingSession.getMasterSecret());
}
// update the responders
shc.handshakeProducers.put(SSLHandshake.FINISHED.id,
SSLHandshake.FINISHED);
}
// The handshake message has been delivered.
return null;
}
private static KeyExchangeProperties chooseCipherSuite(
ServerHandshakeContext shc,
ClientHelloMessage clientHello) throws IOException {
List<CipherSuite> preferred;
List<CipherSuite> proposed;
if (shc.sslConfig.preferLocalCipherSuites) {
preferred = shc.activeCipherSuites;
proposed = clientHello.cipherSuites;
} else {
preferred = clientHello.cipherSuites;
proposed = shc.activeCipherSuites;
}
List<CipherSuite> legacySuites = new LinkedList<>();
for (CipherSuite cs : preferred) {
if (!HandshakeContext.isNegotiable(
proposed, shc.negotiatedProtocol, cs)) {
continue;
}
if (shc.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED) {
if ((cs.keyExchange == KeyExchange.K_DH_ANON) ||
(cs.keyExchange == KeyExchange.K_ECDH_ANON)) {
continue;
}
}
SSLKeyExchange ke = SSLKeyExchange.valueOf(
cs.keyExchange, shc.negotiatedProtocol);
if (ke == null) {
continue;
}
if (!ServerHandshakeContext.legacyAlgorithmConstraints.permits(
null, cs.name, null)) {
legacySuites.add(cs);
continue;
}
SSLPossession[] hcds = ke.createPossessions(shc);
if ((hcds == null) || (hcds.length == 0)) {
continue;
}
// The cipher suite has been negotiated.
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("use cipher suite " + cs.name);
}
return new KeyExchangeProperties(cs, ke, hcds);
}
for (CipherSuite cs : legacySuites) {
SSLKeyExchange ke = SSLKeyExchange.valueOf(
cs.keyExchange, shc.negotiatedProtocol);
if (ke != null) {
SSLPossession[] hcds = ke.createPossessions(shc);
if ((hcds != null) && (hcds.length != 0)) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.warning(
"use legacy cipher suite " + cs.name);
}
return new KeyExchangeProperties(cs, ke, hcds);
}
}
}
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"no cipher suites in common");
}
private static final class KeyExchangeProperties {
final CipherSuite cipherSuite;
final SSLKeyExchange keyExchange;
final SSLPossession[] possessions;
private KeyExchangeProperties(CipherSuite cipherSuite,
SSLKeyExchange keyExchange, SSLPossession[] possessions) {
this.cipherSuite = cipherSuite;
this.keyExchange = keyExchange;
this.possessions = possessions;
}
}
}
/**
* The "ServerHello" handshake message producer.
*/
private static final
class T13ServerHelloProducer implements HandshakeProducer {
// Prevent instantiation of this class.
private T13ServerHelloProducer() {
// blank
}
@Override
public byte[] produce(ConnectionContext context,
HandshakeMessage message) throws IOException {
// The producing happens in server side only.
ServerHandshakeContext shc = (ServerHandshakeContext)context;
ClientHelloMessage clientHello = (ClientHelloMessage)message;
// If client hasn't specified a session we can resume, start a
// new one and choose its cipher suite and compression options,
// unless new session creation is disabled for this connection!
if (!shc.isResumption || shc.resumingSession == null) {
if (!shc.sslConfig.enableSessionCreation) {
throw new SSLException(
"Not resumption, and no new session is allowed");
}
SSLSessionImpl session =
new SSLSessionImpl(shc, CipherSuite.C_NULL);
session.setMaximumPacketSize(shc.sslConfig.maximumPacketSize);
shc.handshakeSession = session;
// consider the handshake extension impact
SSLExtension[] enabledExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.CLIENT_HELLO, shc.negotiatedProtocol);
clientHello.extensions.consumeOnTrade(shc, enabledExtensions);
// negotiate the cipher suite.
CipherSuite cipherSuite = chooseCipherSuite(shc, clientHello);
if (cipherSuite == null) {
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"no cipher suites in common");
}
shc.negotiatedCipherSuite = cipherSuite;
shc.handshakeSession.setSuite(cipherSuite);
shc.handshakeHash.determine(
shc.negotiatedProtocol, shc.negotiatedCipherSuite);
} else {
shc.handshakeSession = shc.resumingSession;
// consider the handshake extension impact
SSLExtension[] enabledExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.CLIENT_HELLO, shc.negotiatedProtocol);
clientHello.extensions.consumeOnTrade(shc, enabledExtensions);
shc.negotiatedProtocol =
shc.resumingSession.getProtocolVersion();
shc.negotiatedCipherSuite = shc.resumingSession.getSuite();
shc.handshakeHash.determine(
shc.negotiatedProtocol, shc.negotiatedCipherSuite);
setUpPskKD(shc,
shc.resumingSession.consumePreSharedKey());
}
// update the responders
shc.handshakeProducers.put(SSLHandshake.ENCRYPTED_EXTENSIONS.id,
SSLHandshake.ENCRYPTED_EXTENSIONS);
shc.handshakeProducers.put(SSLHandshake.FINISHED.id,
SSLHandshake.FINISHED);
// Generate the ServerHello handshake message.
ServerHelloMessage shm = new ServerHelloMessage(shc,
ProtocolVersion.TLS12, // use legacy version
clientHello.sessionId, // echo back
shc.negotiatedCipherSuite,
new RandomCookie(shc),
clientHello);
shc.serverHelloRandom = shm.serverRandom;
// Produce extensions for ServerHello handshake message.
SSLExtension[] serverHelloExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.SERVER_HELLO, shc.negotiatedProtocol);
shm.extensions.produce(shc, serverHelloExtensions);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Produced ServerHello handshake message", shm);
}
// Output the handshake message.
shm.write(shc.handshakeOutput);
shc.handshakeOutput.flush();
// Change client/server handshake traffic secrets.
// Refresh handshake hash
shc.handshakeHash.update();
// Change client/server handshake traffic secrets.
SSLKeyExchange ke = shc.handshakeKeyExchange;
if (ke == null) {
// unlikely
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
"Not negotiated key shares");
}
SSLKeyDerivation handshakeKD = ke.createKeyDerivation(shc);
SecretKey handshakeSecret = handshakeKD.deriveKey(
"TlsHandshakeSecret", null);
SSLTrafficKeyDerivation kdg =
SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol);
if (kdg == null) {
// unlikely
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
"Not supported key derivation: " +
shc.negotiatedProtocol);
}
SSLKeyDerivation kd =
new SSLSecretDerivation(shc, handshakeSecret);
// update the handshake traffic read keys.
SecretKey readSecret = kd.deriveKey(
"TlsClientHandshakeTrafficSecret", null);
SSLKeyDerivation readKD =
kdg.createKeyDerivation(shc, readSecret);
SecretKey readKey = readKD.deriveKey(
"TlsKey", null);
SecretKey readIvSecret = readKD.deriveKey(
"TlsIv", null);
IvParameterSpec readIv =
new IvParameterSpec(readIvSecret.getEncoded());
SSLReadCipher readCipher;
try {
readCipher =
shc.negotiatedCipherSuite.bulkCipher.createReadCipher(
Authenticator.valueOf(shc.negotiatedProtocol),
shc.negotiatedProtocol, readKey, readIv,
shc.sslContext.getSecureRandom());
} catch (GeneralSecurityException gse) {
// unlikely
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"Missing cipher algorithm", gse);
}
if (readCipher == null) {
throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
"Illegal cipher suite (" + shc.negotiatedCipherSuite +
") and protocol version (" + shc.negotiatedProtocol +
")");
}
shc.baseReadSecret = readSecret;
shc.conContext.inputRecord.changeReadCiphers(readCipher);
// update the handshake traffic write secret.
SecretKey writeSecret = kd.deriveKey(
"TlsServerHandshakeTrafficSecret", null);
SSLKeyDerivation writeKD =
kdg.createKeyDerivation(shc, writeSecret);
SecretKey writeKey = writeKD.deriveKey(
"TlsKey", null);
SecretKey writeIvSecret = writeKD.deriveKey(
"TlsIv", null);
IvParameterSpec writeIv =
new IvParameterSpec(writeIvSecret.getEncoded());
SSLWriteCipher writeCipher;
try {
writeCipher =
shc.negotiatedCipherSuite.bulkCipher.createWriteCipher(
Authenticator.valueOf(shc.negotiatedProtocol),
shc.negotiatedProtocol, writeKey, writeIv,
shc.sslContext.getSecureRandom());
} catch (GeneralSecurityException gse) {
// unlikely
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"Missing cipher algorithm", gse);
}
if (writeCipher == null) {
throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
"Illegal cipher suite (" + shc.negotiatedCipherSuite +
") and protocol version (" + shc.negotiatedProtocol +
")");
}
shc.baseWriteSecret = writeSecret;
shc.conContext.outputRecord.changeWriteCiphers(
writeCipher, (clientHello.sessionId.length() != 0));
// Update the context for master key derivation.
shc.handshakeKeyDerivation = kd;
// The handshake message has been delivered.
return null;
}
private static CipherSuite chooseCipherSuite(
ServerHandshakeContext shc,
ClientHelloMessage clientHello) throws IOException {
List<CipherSuite> preferred;
List<CipherSuite> proposed;
if (shc.sslConfig.preferLocalCipherSuites) {
preferred = shc.activeCipherSuites;
proposed = clientHello.cipherSuites;
} else {
preferred = clientHello.cipherSuites;
proposed = shc.activeCipherSuites;
}
CipherSuite legacySuite = null;
AlgorithmConstraints legacyConstraints =
ServerHandshakeContext.legacyAlgorithmConstraints;
for (CipherSuite cs : preferred) {
if (!HandshakeContext.isNegotiable(
proposed, shc.negotiatedProtocol, cs)) {
continue;
}
if ((legacySuite == null) &&
!legacyConstraints.permits(null, cs.name, null)) {
legacySuite = cs;
continue;
}
// The cipher suite has been negotiated.
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("use cipher suite " + cs.name);
}
return cs;
}
if (legacySuite != null) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.warning(
"use legacy cipher suite " + legacySuite.name);
}
return legacySuite;
}
// no cipher suites in common
return null;
}
}
/**
* The "HelloRetryRequest" handshake message producer.
*/
private static final
class T13HelloRetryRequestProducer implements HandshakeProducer {
// Prevent instantiation of this class.
private T13HelloRetryRequestProducer() {
// blank
}
@Override
public byte[] produce(ConnectionContext context,
HandshakeMessage message) throws IOException {
ServerHandshakeContext shc = (ServerHandshakeContext) context;
ClientHelloMessage clientHello = (ClientHelloMessage) message;
// negotiate the cipher suite.
CipherSuite cipherSuite =
T13ServerHelloProducer.chooseCipherSuite(shc, clientHello);
if (cipherSuite == null) {
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"no cipher suites in common for hello retry request");
}
ServerHelloMessage hhrm = new ServerHelloMessage(shc,
ProtocolVersion.TLS12, // use legacy version
clientHello.sessionId, // echo back
cipherSuite,
RandomCookie.hrrRandom,
clientHello
);
shc.negotiatedCipherSuite = cipherSuite;
shc.handshakeHash.determine(
shc.negotiatedProtocol, shc.negotiatedCipherSuite);
// Produce extensions for HelloRetryRequest handshake message.
SSLExtension[] serverHelloExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.HELLO_RETRY_REQUEST, shc.negotiatedProtocol);
hhrm.extensions.produce(shc, serverHelloExtensions);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Produced HelloRetryRequest handshake message", hhrm);
}
// Output the handshake message.
hhrm.write(shc.handshakeOutput);
shc.handshakeOutput.flush();
// In TLS1.3 middlebox compatibility mode the server sends a
// dummy change_cipher_spec record immediately after its
// first handshake message. This may either be after
// a ServerHello or a HelloRetryRequest.
// (RFC 8446, Appendix D.4)
shc.conContext.outputRecord.changeWriteCiphers(
SSLWriteCipher.nullTlsWriteCipher(),
(clientHello.sessionId.length() != 0));
// Stateless, shall we clean up the handshake context as well?
shc.handshakeHash.finish(); // forgot about the handshake hash
shc.handshakeExtensions.clear();
// What's the expected response?
shc.handshakeConsumers.put(
SSLHandshake.CLIENT_HELLO.id, SSLHandshake.CLIENT_HELLO);
// The handshake message has been delivered.
return null;
}
}
/**
* The "HelloRetryRequest" handshake message reproducer.
*/
private static final
class T13HelloRetryRequestReproducer implements HandshakeProducer {
// Prevent instantiation of this class.
private T13HelloRetryRequestReproducer() {
// blank
}
@Override
public byte[] produce(ConnectionContext context,
HandshakeMessage message) throws IOException {
ServerHandshakeContext shc = (ServerHandshakeContext) context;
ClientHelloMessage clientHello = (ClientHelloMessage) message;
// negotiate the cipher suite.
CipherSuite cipherSuite = shc.negotiatedCipherSuite;
ServerHelloMessage hhrm = new ServerHelloMessage(shc,
ProtocolVersion.TLS12, // use legacy version
clientHello.sessionId, // echo back
cipherSuite,
RandomCookie.hrrRandom,
clientHello
);
// Produce extensions for HelloRetryRequest handshake message.
SSLExtension[] serverHelloExtensions =
shc.sslConfig.getEnabledExtensions(
SSLHandshake.MESSAGE_HASH, shc.negotiatedProtocol);
hhrm.extensions.produce(shc, serverHelloExtensions);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Reproduced HelloRetryRequest handshake message", hhrm);
}
HandshakeOutStream hos = new HandshakeOutStream(null);
hhrm.write(hos);
return hos.toByteArray();
}
}
/**
* The "ServerHello" handshake message consumer.
*/
private static final
class ServerHelloConsumer implements SSLConsumer {
// Prevent instantiation of this class.
private ServerHelloConsumer() {
// blank
}
@Override
public void consume(ConnectionContext context,
ByteBuffer message) throws IOException {
// The consuming happens in client side only.
ClientHandshakeContext chc = (ClientHandshakeContext)context;
// clean up this consumer
chc.handshakeConsumers.remove(SSLHandshake.SERVER_HELLO.id);
if (!chc.handshakeConsumers.isEmpty()) {
// DTLS 1.0/1.2
chc.handshakeConsumers.remove(
SSLHandshake.HELLO_VERIFY_REQUEST.id);
}
if (!chc.handshakeConsumers.isEmpty()) {
throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"No more message expected before ServerHello is processed");
}
ServerHelloMessage shm = new ServerHelloMessage(chc, message);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Consuming ServerHello handshake message", shm);
}
if (shm.serverRandom.isHelloRetryRequest()) {
onHelloRetryRequest(chc, shm);
} else {
onServerHello(chc, shm);
}
}
private void onHelloRetryRequest(ClientHandshakeContext chc,
ServerHelloMessage helloRetryRequest) throws IOException {
// Negotiate protocol version.
//
// Check and launch SupportedVersions.
SSLExtension[] extTypes = new SSLExtension[] {
SSLExtension.HRR_SUPPORTED_VERSIONS
};
helloRetryRequest.extensions.consumeOnLoad(chc, extTypes);
ProtocolVersion serverVersion;
SHSupportedVersionsSpec svs =
(SHSupportedVersionsSpec)chc.handshakeExtensions.get(
SSLExtension.HRR_SUPPORTED_VERSIONS);
if (svs != null) {
serverVersion = // could be null
ProtocolVersion.valueOf(svs.selectedVersion);
} else {
serverVersion = helloRetryRequest.serverVersion;
}
if (!chc.activeProtocols.contains(serverVersion)) {
throw chc.conContext.fatal(Alert.PROTOCOL_VERSION,
"The server selected protocol version " + serverVersion +
" is not accepted by client preferences " +
chc.activeProtocols);
}
if (!serverVersion.useTLS13PlusSpec()) {
throw chc.conContext.fatal(Alert.PROTOCOL_VERSION,
"Unexpected HelloRetryRequest for " + serverVersion.name);
}
chc.negotiatedProtocol = serverVersion;
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Negotiated protocol version: " + serverVersion.name);
}
// Protocol version is negotiated, update locally supported
// signature schemes according to the protocol being used.
SignatureScheme.updateHandshakeLocalSupportedAlgs(chc);
// TLS 1.3 key share extension may have produced client
// possessions for TLS 1.3 key exchanges.
//
// Clean up before producing new client key share possessions.
chc.handshakePossessions.clear();
if (serverVersion.isDTLS) {
d13HrrHandshakeConsumer.consume(chc, helloRetryRequest);
} else {
t13HrrHandshakeConsumer.consume(chc, helloRetryRequest);
}
}
private void onServerHello(ClientHandshakeContext chc,
ServerHelloMessage serverHello) throws IOException {
// Negotiate protocol version.
//
// Check and launch SupportedVersions.
SSLExtension[] extTypes = new SSLExtension[] {
SSLExtension.SH_SUPPORTED_VERSIONS
};
serverHello.extensions.consumeOnLoad(chc, extTypes);
ProtocolVersion serverVersion;
SHSupportedVersionsSpec svs =
(SHSupportedVersionsSpec)chc.handshakeExtensions.get(
SSLExtension.SH_SUPPORTED_VERSIONS);
if (svs != null) {
serverVersion = // could be null
ProtocolVersion.valueOf(svs.selectedVersion);
} else {
serverVersion = serverHello.serverVersion;
}
if (!chc.activeProtocols.contains(serverVersion)) {
throw chc.conContext.fatal(Alert.PROTOCOL_VERSION,
"The server selected protocol version " + serverVersion +
" is not accepted by client preferences " +
chc.activeProtocols);
}
chc.negotiatedProtocol = serverVersion;
if (!chc.conContext.isNegotiated) {
chc.conContext.protocolVersion = chc.negotiatedProtocol;
chc.conContext.outputRecord.setVersion(chc.negotiatedProtocol);
}
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Negotiated protocol version: " + serverVersion.name);
}
// Protocol version is negotiated, update locally supported
// signature schemes according to the protocol being used.
SignatureScheme.updateHandshakeLocalSupportedAlgs(chc);
if (serverHello.serverRandom.isVersionDowngrade(chc)) {
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
"A potential protocol version downgrade attack");
}
// Consume the handshake message for the specific protocol version.
if (serverVersion.isDTLS) {
if (serverVersion.useTLS13PlusSpec()) {
d13HandshakeConsumer.consume(chc, serverHello);
} else {
// TLS 1.3 key share extension may have produced client
// possessions for TLS 1.3 key exchanges.
chc.handshakePossessions.clear();
d12HandshakeConsumer.consume(chc, serverHello);
}
} else {
if (serverVersion.useTLS13PlusSpec()) {
t13HandshakeConsumer.consume(chc, serverHello);
} else {
// TLS 1.3 key share extension may have produced client
// possessions for TLS 1.3 key exchanges.
chc.handshakePossessions.clear();
t12HandshakeConsumer.consume(chc, serverHello);
}
}
}
}
private static final