summary refs log tree commit diff
path: root/crypto/src/tls/TlsClientProtocol.cs
blob: 30ad67fbe5179733542bed11cb3933af060c50bd (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
using System;
using System.Collections.Generic;
using System.IO;

using Org.BouncyCastle.Tls.Crypto;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Tls
{
    public class TlsClientProtocol
        : TlsProtocol
    {
        protected TlsClient m_tlsClient = null;
        internal TlsClientContextImpl m_tlsClientContext = null;

        protected IDictionary<int, TlsAgreement> m_clientAgreements = null;
        internal OfferedPsks.BindersConfig m_clientBinders = null;
        protected ClientHello m_clientHello = null;
        protected TlsKeyExchange m_keyExchange = null;
        protected TlsAuthentication m_authentication = null;

        protected CertificateStatus m_certificateStatus = null;
        protected CertificateRequest m_certificateRequest = null;

        /// <summary>Constructor for non-blocking mode.</summary>
        /// <remarks>
        /// When data is received, use <see cref="TlsProtocol.OfferInput(byte[])"/> to provide the received ciphertext,
        /// then use <see cref="TlsProtocol.ReadInput(byte[],int,int)"/> to read the corresponding cleartext.<br/><br/>
        /// Similarly, when data needs to be sent, use <see cref="TlsProtocol.WriteApplicationData(byte[],int,int)"/>
        /// to provide the cleartext, then use <see cref="TlsProtocol.ReadOutput(byte[],int,int)"/> to get the
        /// corresponding ciphertext.
        /// </remarks>
        public TlsClientProtocol()
            : base()
        {
        }

        /// <summary>Constructor for blocking mode.</summary>
        /// <param name="stream">The <see cref="Stream"/> of data to/from the server.</param>
        public TlsClientProtocol(Stream stream)
            : base(stream)
        {
        }

        /// <summary>Constructor for blocking mode.</summary>
        /// <param name="input">The <see cref="Stream"/> of data from the server.</param>
        /// <param name="output">The <see cref="Stream"/> of data to the server.</param>
        public TlsClientProtocol(Stream input, Stream output)
            : base(input, output)
        {
        }

        /// <summary>Initiates a TLS handshake in the role of client.</summary>
        /// <remarks>
        /// In blocking mode, this will not return until the handshake is complete. In non-blocking mode, use
        /// <see cref="TlsPeer.NotifyHandshakeComplete"/> to receive a callback when the handshake is complete.
        /// </remarks>
        /// <param name="tlsClient">The <see cref="TlsClient"/> to use for the handshake.</param>
        /// <exception cref="IOException">If in blocking mode and handshake was not successful.</exception>
        public virtual void Connect(TlsClient tlsClient)
        {
            if (tlsClient == null)
                throw new ArgumentNullException("tlsClient");
            if (m_tlsClient != null)
                throw new InvalidOperationException("'Connect' can only be called once");

            this.m_tlsClient = tlsClient;
            this.m_tlsClientContext = new TlsClientContextImpl(tlsClient.Crypto);

            tlsClient.Init(m_tlsClientContext);
            tlsClient.NotifyCloseHandle(this);

            BeginHandshake();

            if (m_blocking)
            {
                BlockForHandshake();
            }
        }

        protected override void BeginHandshake()
        {
            base.BeginHandshake();

            SendClientHello();
            this.m_connectionState = CS_CLIENT_HELLO;
        }

        protected override void CleanupHandshake()
        {
            base.CleanupHandshake();

            this.m_clientAgreements = null;
            this.m_clientBinders = null;
            this.m_clientHello = null;
            this.m_keyExchange = null;
            this.m_authentication = null;

            this.m_certificateStatus = null;
            this.m_certificateRequest = null;
        }

        protected override TlsContext Context
        {
            get { return m_tlsClientContext; }
        }

        internal override AbstractTlsContext ContextAdmin
        {
            get { return m_tlsClientContext; }
        }

        protected override TlsPeer Peer
        {
            get { return m_tlsClient; }
        }

        /// <exception cref="IOException"/>
        protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInput buf)
        {
            if (!IsTlsV13ConnectionState())
                throw new TlsFatalAlert(AlertDescription.internal_error);

            switch (type)
            {
            case HandshakeType.certificate:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_ENCRYPTED_EXTENSIONS:
                case CS_SERVER_CERTIFICATE_REQUEST:
                {
                    if (m_connectionState != CS_SERVER_CERTIFICATE_REQUEST)
                    {
                        Skip13CertificateRequest();
                    }

                    Receive13ServerCertificate(buf);
                    this.m_connectionState = CS_SERVER_CERTIFICATE;
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.certificate_request:
            {
                switch (m_connectionState)
                {
                case CS_END:
                {
                    // TODO[tls13] Permit post-handshake authentication if we sent post_handshake_auth extension
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                case CS_SERVER_ENCRYPTED_EXTENSIONS:
                {
                    Receive13CertificateRequest(buf, false);
                    this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST;
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.certificate_verify:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_CERTIFICATE:
                {
                    Receive13ServerCertificateVerify(buf);
                    buf.UpdateHash(m_handshakeHash);
                    this.m_connectionState = CS_SERVER_CERTIFICATE_VERIFY;
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.encrypted_extensions:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_HELLO:
                {
                    Receive13EncryptedExtensions(buf);
                    this.m_connectionState = CS_SERVER_ENCRYPTED_EXTENSIONS;
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.finished:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_ENCRYPTED_EXTENSIONS:
                case CS_SERVER_CERTIFICATE_REQUEST:
                case CS_SERVER_CERTIFICATE_VERIFY:
                {
                    if (m_connectionState == CS_SERVER_ENCRYPTED_EXTENSIONS)
                    {
                        Skip13CertificateRequest();
                    }
                    if (m_connectionState != CS_SERVER_CERTIFICATE_VERIFY)
                    {
                        Skip13ServerCertificate();
                    }

                    Receive13ServerFinished(buf);
                    buf.UpdateHash(m_handshakeHash);
                    this.m_connectionState = CS_SERVER_FINISHED;

                    byte[] serverFinishedTranscriptHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);

                    // See RFC 8446 D.4.
                    m_recordStream.SetIgnoreChangeCipherSpec(false);

                    /*
                     * TODO[tls13] After receiving the server's Finished message, if the server has accepted early
                     * data, an EndOfEarlyData message will be sent to indicate the key change. This message will
                     * be encrypted with the 0-RTT traffic keys.
                     */

                    if (null != m_certificateRequest)
                    {
                        TlsCredentialedSigner clientCredentials = TlsUtilities.Establish13ClientCredentials(
                            m_authentication, m_certificateRequest);

                        Certificate clientCertificate = null;
                        if (null != clientCredentials)
                        {
                            clientCertificate = clientCredentials.Certificate;
                        }

                        if (null == clientCertificate)
                        {
                            // In this calling context, certificate_request_context is length 0
                            clientCertificate = Certificate.EmptyChainTls13;
                        }

                        Send13CertificateMessage(clientCertificate);
                        this.m_connectionState = CS_CLIENT_CERTIFICATE;

                        if (null != clientCredentials)
                        {
                            DigitallySigned certificateVerify = TlsUtilities.Generate13CertificateVerify(
                                m_tlsClientContext, clientCredentials, m_handshakeHash);
                            Send13CertificateVerifyMessage(certificateVerify);
                            this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
                        }
                    }

                    Send13FinishedMessage();
                    this.m_connectionState = CS_CLIENT_FINISHED;

                    TlsUtilities.Establish13PhaseApplication(m_tlsClientContext, serverFinishedTranscriptHash,
                        m_recordStream);

                    m_recordStream.EnablePendingCipherWrite();
                    m_recordStream.EnablePendingCipherRead(false);

                    CompleteHandshake();
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.key_update:
            {
                Receive13KeyUpdate(buf);
                break;
            }
            case HandshakeType.new_session_ticket:
            {
                Receive13NewSessionTicket(buf);
                break;
            }
            case HandshakeType.server_hello:
            {
                switch (m_connectionState)
                {
                case CS_CLIENT_HELLO:
                {
                    // NOTE: Legacy handler should be dispatching initial ServerHello/HelloRetryRequest.
                    throw new TlsFatalAlert(AlertDescription.internal_error);
                }
                case CS_CLIENT_HELLO_RETRY:
                {
                    ServerHello serverHello = ReceiveServerHelloMessage(buf);
                    if (serverHello.IsHelloRetryRequest())
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);

                    Process13ServerHello(serverHello, true);
                    buf.UpdateHash(m_handshakeHash);
                    this.m_connectionState = CS_SERVER_HELLO;

                    Process13ServerHelloCoda(serverHello, true);
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.certificate_status:
            case HandshakeType.certificate_url:
            case HandshakeType.client_hello:
            case HandshakeType.client_key_exchange:
            case HandshakeType.compressed_certificate:
            case HandshakeType.end_of_early_data:
            case HandshakeType.hello_request:
            case HandshakeType.hello_verify_request:
            case HandshakeType.message_hash:
            case HandshakeType.server_hello_done:
            case HandshakeType.server_key_exchange:
            case HandshakeType.supplemental_data:
            default:
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
        }

        protected override void HandleHandshakeMessage(short type, HandshakeMessageInput buf)
        {
            SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;

            if (m_connectionState > CS_CLIENT_HELLO
                && TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
            {
                if (securityParameters.IsResumedSession)
                    throw new TlsFatalAlert(AlertDescription.internal_error);

                Handle13HandshakeMessage(type, buf);
                return;
            }

            if (!IsLegacyConnectionState())
                throw new TlsFatalAlert(AlertDescription.internal_error);

            if (securityParameters.IsResumedSession && type != HandshakeType.hello_request)
            {
                if (type != HandshakeType.finished || m_connectionState != CS_SERVER_HELLO)
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);

                ProcessFinishedMessage(buf);
                buf.UpdateHash(m_handshakeHash);
                this.m_connectionState = CS_SERVER_FINISHED;

                SendChangeCipherSpec();
                SendFinishedMessage();
                this.m_connectionState = CS_CLIENT_FINISHED;

                CompleteHandshake();
                return;
            }

            switch (type)
            {
            case HandshakeType.certificate:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_HELLO:
                case CS_SERVER_SUPPLEMENTAL_DATA:
                {
                    if (m_connectionState != CS_SERVER_SUPPLEMENTAL_DATA)
                    {
                        HandleSupplementalData(null);
                    }

                    /*
                     * NOTE: Certificate processing (including authentication) is delayed to allow for a
                     * possible CertificateStatus message.
                     */
                    m_authentication = TlsUtilities.ReceiveServerCertificate(m_tlsClientContext, m_tlsClient, buf,
                        m_serverExtensions);
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.m_connectionState = CS_SERVER_CERTIFICATE;
                break;
            }
            case HandshakeType.certificate_status:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_CERTIFICATE:
                {
                    if (securityParameters.StatusRequestVersion < 1)
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);

                    this.m_certificateStatus = CertificateStatus.Parse(m_tlsClientContext, buf);

                    AssertEmpty(buf);

                    this.m_connectionState = CS_SERVER_CERTIFICATE_STATUS;
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.finished:
            {
                switch (m_connectionState)
                {
                case CS_CLIENT_FINISHED:
                case CS_SERVER_SESSION_TICKET:
                {
                    if (m_connectionState != CS_SERVER_SESSION_TICKET)
                    {
                        /*
                         * RFC 5077 3.3. This message MUST be sent if the server included a
                         * SessionTicket extension in the ServerHello.
                         */
                        if (m_expectSessionTicket)
                            throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    ProcessFinishedMessage(buf);
                    this.m_connectionState = CS_SERVER_FINISHED;

                    CompleteHandshake();
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.server_hello:
            {
                switch (m_connectionState)
                {
                case CS_CLIENT_HELLO:
                {
                    ServerHello serverHello = ReceiveServerHelloMessage(buf);

                    // TODO[tls13] Only treat as HRR if it's TLS 1.3??
                    if (serverHello.IsHelloRetryRequest())
                    {
                        Process13HelloRetryRequest(serverHello);
                        m_handshakeHash.NotifyPrfDetermined();
                        m_handshakeHash.SealHashAlgorithms();
                        TlsUtilities.AdjustTranscriptForRetry(m_handshakeHash);
                        buf.UpdateHash(m_handshakeHash);
                        this.m_connectionState = CS_SERVER_HELLO_RETRY_REQUEST;

                        Send13ClientHelloRetry();
                        this.m_connectionState = CS_CLIENT_HELLO_RETRY;
                    }
                    else
                    {
                        ProcessServerHello(serverHello);
                        m_handshakeHash.NotifyPrfDetermined();
                        if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
                        {
                            m_handshakeHash.SealHashAlgorithms();
                        }
                        buf.UpdateHash(m_handshakeHash);
                        this.m_connectionState = CS_SERVER_HELLO;

                        if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
                        {
                            Process13ServerHelloCoda(serverHello, false);
                        }
                    }

                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.supplemental_data:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_HELLO:
                {
                    HandleSupplementalData(ReadSupplementalDataMessage(buf));
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }
            case HandshakeType.server_hello_done:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_HELLO:
                case CS_SERVER_SUPPLEMENTAL_DATA:
                case CS_SERVER_CERTIFICATE:
                case CS_SERVER_CERTIFICATE_STATUS:
                case CS_SERVER_KEY_EXCHANGE:
                case CS_SERVER_CERTIFICATE_REQUEST:
                {
                    if (m_connectionState == CS_SERVER_HELLO)
                    {
                        HandleSupplementalData(null);
                    }
                    if (m_connectionState == CS_SERVER_HELLO ||
                        m_connectionState == CS_SERVER_SUPPLEMENTAL_DATA)
                    {
                        this.m_authentication = null;
                    }
                    if (m_connectionState != CS_SERVER_KEY_EXCHANGE &&
                        m_connectionState != CS_SERVER_CERTIFICATE_REQUEST)
                    {
                        HandleServerCertificate();

                        // There was no server key exchange message; check it's OK
                        m_keyExchange.SkipServerKeyExchange();
                    }

                    AssertEmpty(buf);

                    this.m_connectionState = CS_SERVER_HELLO_DONE;

                    TlsCredentials clientAuthCredentials = null;
                    TlsCredentialedSigner clientAuthSigner = null;
                    Certificate clientAuthCertificate = null;
                    SignatureAndHashAlgorithm clientAuthAlgorithm = null;
                    TlsStreamSigner clientAuthStreamSigner = null;

                    if (m_certificateRequest != null)
                    {
                        clientAuthCredentials = TlsUtilities.EstablishClientCredentials(m_authentication,
                            m_certificateRequest);
                        if (clientAuthCredentials != null)
                        {
                            clientAuthCertificate = clientAuthCredentials.Certificate;

                            if (clientAuthCredentials is TlsCredentialedSigner)
                            {
                                clientAuthSigner = (TlsCredentialedSigner)clientAuthCredentials;
                                clientAuthAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
                                    securityParameters.NegotiatedVersion, clientAuthSigner);
                                clientAuthStreamSigner = clientAuthSigner.GetStreamSigner();

                                if (ProtocolVersion.TLSv12.Equals(securityParameters.NegotiatedVersion))
                                {
                                    TlsUtilities.VerifySupportedSignatureAlgorithm(securityParameters.ServerSigAlgs,
                                        clientAuthAlgorithm, AlertDescription.internal_error);

                                    if (clientAuthStreamSigner == null)
                                    {
                                        TlsUtilities.TrackHashAlgorithmClient(m_handshakeHash, clientAuthAlgorithm);
                                    }
                                }

                                if (clientAuthStreamSigner != null)
                                {
                                    m_handshakeHash.ForceBuffering();
                                }
                            }
                        }
                    }

                    m_handshakeHash.SealHashAlgorithms();

                    if (clientAuthCredentials == null)
                    {
                        m_keyExchange.SkipClientCredentials();
                    }
                    else
                    {
                        m_keyExchange.ProcessClientCredentials(clientAuthCredentials);                    
                    }

                    var clientSupplementalData = m_tlsClient.GetClientSupplementalData();
                    if (clientSupplementalData != null)
                    {
                        SendSupplementalDataMessage(clientSupplementalData);
                        this.m_connectionState = CS_CLIENT_SUPPLEMENTAL_DATA;
                    }

                    if (m_certificateRequest != null)
                    {
                        SendCertificateMessage(clientAuthCertificate, null);
                        this.m_connectionState = CS_CLIENT_CERTIFICATE;                    
                    }

                    SendClientKeyExchange();
                    this.m_connectionState = CS_CLIENT_KEY_EXCHANGE;

                    bool isSsl = TlsUtilities.IsSsl(m_tlsClientContext);
                    if (isSsl)
                    {
                        // NOTE: For SSLv3 (only), master_secret needed to calculate session hash
                        EstablishMasterSecret(m_tlsClientContext, m_keyExchange);
                    }

                    securityParameters.m_sessionHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);

                    if (!isSsl)
                    {
                        // NOTE: For (D)TLS, session hash potentially needed for extended_master_secret
                        EstablishMasterSecret(m_tlsClientContext, m_keyExchange);
                    }

                    m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsClientContext));

                    if (clientAuthSigner != null)
                    {
                        DigitallySigned certificateVerify = TlsUtilities.GenerateCertificateVerifyClient(
                            m_tlsClientContext, clientAuthSigner, clientAuthAlgorithm, clientAuthStreamSigner,
                            m_handshakeHash);
                        SendCertificateVerifyMessage(certificateVerify);
                        this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
                    }

                    m_handshakeHash.StopTracking();

                    SendChangeCipherSpec();
                    SendFinishedMessage();
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.m_connectionState = CS_CLIENT_FINISHED;
                break;
            }
            case HandshakeType.server_key_exchange:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_HELLO:
                case CS_SERVER_SUPPLEMENTAL_DATA:
                case CS_SERVER_CERTIFICATE:
                case CS_SERVER_CERTIFICATE_STATUS:
                {
                    if (m_connectionState == CS_SERVER_HELLO)
                    {
                        HandleSupplementalData(null);
                    }
                    if (m_connectionState != CS_SERVER_CERTIFICATE &&
                        m_connectionState != CS_SERVER_CERTIFICATE_STATUS)
                    {
                        this.m_authentication = null;
                    }

                    HandleServerCertificate();

                    m_keyExchange.ProcessServerKeyExchange(buf);

                    AssertEmpty(buf);
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.m_connectionState = CS_SERVER_KEY_EXCHANGE;
                break;
            }
            case HandshakeType.certificate_request:
            {
                switch (m_connectionState)
                {
                case CS_SERVER_CERTIFICATE:
                case CS_SERVER_CERTIFICATE_STATUS:
                case CS_SERVER_KEY_EXCHANGE:
                {
                    if (m_connectionState != CS_SERVER_KEY_EXCHANGE)
                    {
                        HandleServerCertificate();

                        // There was no server key exchange message; check it's OK
                        m_keyExchange.SkipServerKeyExchange();
                    }

                    ReceiveCertificateRequest(buf);

                    TlsUtilities.EstablishServerSigAlgs(securityParameters, m_certificateRequest);
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST;
                break;
            }
            case HandshakeType.new_session_ticket:
            {
                switch (m_connectionState)
                {
                case CS_CLIENT_FINISHED:
                {
                    if (!m_expectSessionTicket)
                    {
                        /*
                         * RFC 5077 3.3. This message MUST NOT be sent if the server did not include a
                         * SessionTicket extension in the ServerHello.
                         */
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    /*
                     * RFC 5077 3.4. If the client receives a session ticket from the server, then it
                     * discards any Session ID that was sent in the ServerHello.
                     */
                    securityParameters.m_sessionID = TlsUtilities.EmptyBytes;
                    InvalidateSession();
                    this.m_tlsSession = TlsUtilities.ImportSession(securityParameters.SessionID, null);

                    ReceiveNewSessionTicket(buf);
                    break;
                }
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.m_connectionState = CS_SERVER_SESSION_TICKET;
                break;
            }
            case HandshakeType.hello_request:
            {
                AssertEmpty(buf);

                /*
                 * RFC 2246 7.4.1.1 Hello request This message will be ignored by the client if the
                 * client is currently negotiating a session. This message may be ignored by the client
                 * if it does not wish to renegotiate a session, or the client may, if it wishes,
                 * respond with a no_renegotiation alert.
                 */
                if (IsApplicationDataReady)
                {
                    RefuseRenegotiation();
                }
                break;
            }

            case HandshakeType.certificate_url:
            case HandshakeType.certificate_verify:
            case HandshakeType.client_hello:
            case HandshakeType.client_key_exchange:
            case HandshakeType.compressed_certificate:
            case HandshakeType.encrypted_extensions:
            case HandshakeType.end_of_early_data:
            case HandshakeType.hello_verify_request:
            case HandshakeType.key_update:
            case HandshakeType.message_hash:
            default:
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
        }

        /// <exception cref="IOException"/>
        protected virtual void HandleServerCertificate()
        {
            TlsUtilities.ProcessServerCertificate(m_tlsClientContext, m_certificateStatus, m_keyExchange,
                m_authentication, m_clientExtensions, m_serverExtensions);
        }

        /// <exception cref="IOException"/>
        protected virtual void HandleSupplementalData(IList<SupplementalDataEntry> serverSupplementalData)
        {
            m_tlsClient.ProcessServerSupplementalData(serverSupplementalData);
            this.m_connectionState = CS_SERVER_SUPPLEMENTAL_DATA;

            this.m_keyExchange = TlsUtilities.InitKeyExchangeClient(m_tlsClientContext, m_tlsClient);
        }

        /// <exception cref="IOException"/>
        protected virtual void Process13HelloRetryRequest(ServerHello helloRetryRequest)
        {
            ProtocolVersion legacy_record_version = ProtocolVersion.TLSv12;
            m_recordStream.SetWriteVersion(legacy_record_version);

            SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;

            /*
             * RFC 8446 4.1.4. Upon receipt of a HelloRetryRequest, the client MUST check the
             * legacy_version, legacy_session_id_echo, cipher_suite, and legacy_compression_method as
             * specified in Section 4.1.3 and then process the extensions, starting with determining the
             * version using "supported_versions".
             */
            ProtocolVersion legacy_version = helloRetryRequest.Version;
            byte[] legacy_session_id_echo = helloRetryRequest.SessionID;
            int cipherSuite = helloRetryRequest.CipherSuite;
            // NOTE: legacy_compression_method checked during ServerHello parsing

            if (!ProtocolVersion.TLSv12.Equals(legacy_version) ||
                !Arrays.AreEqual(m_clientHello.SessionID, legacy_session_id_echo) ||
                !TlsUtilities.IsValidCipherSuiteSelection(m_clientHello.CipherSuites, cipherSuite))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            var extensions = helloRetryRequest.Extensions;
            if (null == extensions)
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);

            TlsUtilities.CheckExtensionData13(extensions, HandshakeType.hello_retry_request,
                AlertDescription.illegal_parameter);

            {
                /*
                 * RFC 8446 4.2. Implementations MUST NOT send extension responses if the remote
                 * endpoint did not send the corresponding extension requests, with the exception of the
                 * "cookie" extension in the HelloRetryRequest. Upon receiving such an extension, an
                 * endpoint MUST abort the handshake with an "unsupported_extension" alert.
                 */
                foreach (int extType in extensions.Keys)
                {
                    if (ExtensionType.cookie == extType)
                        continue;

                    if (null == TlsUtilities.GetExtensionData(m_clientExtensions, extType))
                        throw new TlsFatalAlert(AlertDescription.unsupported_extension);
                }
            }

            ProtocolVersion server_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer(extensions);
            if (null == server_version)
                throw new TlsFatalAlert(AlertDescription.missing_extension);

            if (!ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(server_version) ||
                !ProtocolVersion.Contains(m_tlsClientContext.ClientSupportedVersions, server_version) ||
                !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, server_version))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            if (null != m_clientBinders)
            {
                if (!Arrays.Contains(m_clientBinders.m_pskKeyExchangeModes, PskKeyExchangeMode.psk_dhe_ke))
                {
                    this.m_clientBinders = null;

                    m_tlsClient.NotifySelectedPsk(null);
                }
            }

            /*
             * RFC 8446 4.2.8. Upon receipt of this [Key Share] extension in a HelloRetryRequest, the
             * client MUST verify that (1) the selected_group field corresponds to a group which was
             * provided in the "supported_groups" extension in the original ClientHello and (2) the
             * selected_group field does not correspond to a group which was provided in the "key_share"
             * extension in the original ClientHello. If either of these checks fails, then the client
             * MUST abort the handshake with an "illegal_parameter" alert.
             */
            int selected_group = TlsExtensionsUtilities.GetKeyShareHelloRetryRequest(extensions);

            if (!TlsUtilities.IsValidKeyShareSelection(server_version, securityParameters.ClientSupportedGroups,
                m_clientAgreements, selected_group))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            byte[] cookie = TlsExtensionsUtilities.GetCookieExtension(extensions);



            securityParameters.m_negotiatedVersion = server_version;
            TlsUtilities.NegotiatedVersionTlsClient(m_tlsClientContext, m_tlsClient);

            securityParameters.m_resumedSession = false;
            securityParameters.m_sessionID = TlsUtilities.EmptyBytes;
            m_tlsClient.NotifySessionID(TlsUtilities.EmptyBytes);

            TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
            m_tlsClient.NotifySelectedCipherSuite(cipherSuite);

            this.m_clientAgreements = null;
            this.m_retryCookie = cookie;
            this.m_retryGroup = selected_group;
        }

        /// <exception cref="IOException"/>
        protected virtual void Process13ServerHello(ServerHello serverHello, bool afterHelloRetryRequest)
        {
            SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;

            ProtocolVersion legacy_version = serverHello.Version;
            byte[] legacy_session_id_echo = serverHello.SessionID;
            int cipherSuite = serverHello.CipherSuite;
            // NOTE: legacy_compression_method checked during ServerHello parsing

            if (!ProtocolVersion.TLSv12.Equals(legacy_version) ||
                !Arrays.AreEqual(m_clientHello.SessionID, legacy_session_id_echo))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            var extensions = serverHello.Extensions;
            if (null == extensions)
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);

            TlsUtilities.CheckExtensionData13(extensions, HandshakeType.server_hello,
                AlertDescription.illegal_parameter);

            if (afterHelloRetryRequest)
            {
                ProtocolVersion server_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer(extensions);
                if (null == server_version)
                    throw new TlsFatalAlert(AlertDescription.missing_extension);

                if (!securityParameters.NegotiatedVersion.Equals(server_version) ||
                    securityParameters.CipherSuite != cipherSuite)
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }
            }
            else
            {
                if (!TlsUtilities.IsValidCipherSuiteSelection(m_clientHello.CipherSuites, cipherSuite) ||
                    !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, securityParameters.NegotiatedVersion))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                securityParameters.m_resumedSession = false;
                securityParameters.m_sessionID = TlsUtilities.EmptyBytes;
                m_tlsClient.NotifySessionID(TlsUtilities.EmptyBytes);

                TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
                m_tlsClient.NotifySelectedCipherSuite(cipherSuite);
            }

            this.m_clientHello = null;

            // NOTE: Apparently downgrade marker mechanism not used for TLS 1.3+?
            securityParameters.m_serverRandom = serverHello.Random;

            securityParameters.m_secureRenegotiation = false;

            /*
             * RFC 8446 Appendix D. Because TLS 1.3 always hashes in the transcript up to the server
             * Finished, implementations which support both TLS 1.3 and earlier versions SHOULD indicate
             * the use of the Extended Master Secret extension in their APIs whenever TLS 1.3 is used.
             */
            securityParameters.m_extendedMasterSecret = true;

            /*
             * TODO[tls13] RFC 8446 4.4.2.1. OCSP Status and SCT Extensions.
             * 
             * OCSP information is carried in an extension for a CertificateEntry.
             */
            securityParameters.m_statusRequestVersion =
                m_clientExtensions.ContainsKey(ExtensionType.status_request) ? 1 : 0;

            TlsSecret pskEarlySecret = null;
            {
                int selected_identity = TlsExtensionsUtilities.GetPreSharedKeyServerHello(extensions);
                TlsPsk selectedPsk = null;

                if (selected_identity >= 0)
                {
                    if (null == m_clientBinders || selected_identity >= m_clientBinders.m_psks.Length)
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);

                    selectedPsk = m_clientBinders.m_psks[selected_identity];
                    if (selectedPsk.PrfAlgorithm != securityParameters.PrfAlgorithm)
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);

                    pskEarlySecret = m_clientBinders.m_earlySecrets[selected_identity];

                    this.m_selectedPsk13 = true;
                }

                m_tlsClient.NotifySelectedPsk(selectedPsk);
            }

            TlsSecret sharedSecret = null;
            {
                KeyShareEntry keyShareEntry = TlsExtensionsUtilities.GetKeyShareServerHello(extensions);
                if (null == keyShareEntry)
                {
                    if (afterHelloRetryRequest
                        || null == pskEarlySecret
                        || !Arrays.Contains(m_clientBinders.m_pskKeyExchangeModes, PskKeyExchangeMode.psk_ke))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }
                }
                else
                {
                    if (null != pskEarlySecret
                        && !Arrays.Contains(m_clientBinders.m_pskKeyExchangeModes, PskKeyExchangeMode.psk_dhe_ke))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }

                    if (!m_clientAgreements.TryGetValue(keyShareEntry.NamedGroup, out var agreement))
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);

                    agreement.ReceivePeerValue(keyShareEntry.KeyExchange);
                    sharedSecret = agreement.CalculateSecret();
                }
            }

            this.m_clientAgreements = null;
            this.m_clientBinders = null;

            TlsUtilities.Establish13PhaseSecrets(m_tlsClientContext, pskEarlySecret, sharedSecret);

            InvalidateSession();
            this.m_tlsSession = TlsUtilities.ImportSession(securityParameters.SessionID, null);
        }

        /// <exception cref="IOException"/>
        protected virtual void Process13ServerHelloCoda(ServerHello serverHello, bool afterHelloRetryRequest)
        {
            byte[] serverHelloTranscriptHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);

            TlsUtilities.Establish13PhaseHandshake(m_tlsClientContext, serverHelloTranscriptHash, m_recordStream);

            // See RFC 8446 D.4.
            if (!afterHelloRetryRequest)
            {
                m_recordStream.SetIgnoreChangeCipherSpec(true);

                /*
                 * TODO[tls13] If offering early_data, the record is placed immediately after the first
                 * ClientHello.
                 */
                /*
                 * TODO[tls13] Ideally wait until just after Server Finished received, but then we'd need to defer
                 * the enabling of the pending write cipher
                 */
                SendChangeCipherSpecMessage();
            }

            m_recordStream.EnablePendingCipherWrite();
            m_recordStream.EnablePendingCipherRead(false);
        }

        /// <exception cref="IOException"/>
        protected virtual void ProcessServerHello(ServerHello serverHello)
        {
            var serverHelloExtensions = serverHello.Extensions;

            ProtocolVersion legacy_version = serverHello.Version;
            ProtocolVersion supported_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer(
                serverHelloExtensions);

            ProtocolVersion server_version;
            if (null == supported_version)
            {
                server_version = legacy_version;
            }
            else
            {
                if (!ProtocolVersion.TLSv12.Equals(legacy_version) ||
                    !ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(supported_version))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                server_version = supported_version;
            }

            SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;

            // NOT renegotiating
            {
                if (!ProtocolVersion.Contains(m_tlsClientContext.ClientSupportedVersions, server_version))
                    throw new TlsFatalAlert(AlertDescription.protocol_version);

                ProtocolVersion legacy_record_version = server_version.IsLaterVersionOf(ProtocolVersion.TLSv12)
                    ? ProtocolVersion.TLSv12
                    : server_version;

                m_recordStream.SetWriteVersion(legacy_record_version);
                securityParameters.m_negotiatedVersion = server_version;
            }

            TlsUtilities.NegotiatedVersionTlsClient(m_tlsClientContext, m_tlsClient);

            if (ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(server_version))
            {
                Process13ServerHello(serverHello, false);
                return;
            }

            int[] offeredCipherSuites = m_clientHello.CipherSuites;

            this.m_clientHello = null;
            this.m_retryCookie = null;
            this.m_retryGroup = -1;

            securityParameters.m_serverRandom = serverHello.Random;

            if (!m_tlsClientContext.ClientVersion.Equals(server_version))
            {
                TlsUtilities.CheckDowngradeMarker(server_version, securityParameters.ServerRandom);
            }

            {
                byte[] selectedSessionID = serverHello.SessionID;
                securityParameters.m_sessionID = selectedSessionID;
                m_tlsClient.NotifySessionID(selectedSessionID);
                securityParameters.m_resumedSession = selectedSessionID.Length > 0 && m_tlsSession != null
                    && Arrays.AreEqual(selectedSessionID, m_tlsSession.SessionID);

                if (securityParameters.IsResumedSession)
                {
                    if (serverHello.CipherSuite != m_sessionParameters.CipherSuite ||
                        !securityParameters.NegotiatedVersion.Equals(m_sessionParameters.NegotiatedVersion))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter,
                            "ServerHello parameters do not match resumed session");
                    }
                }
            }

            /*
             * Find out which CipherSuite the server has chosen and check that it was one of the offered
             * ones, and is a valid selection for the negotiated version.
             */
            {
                int cipherSuite = serverHello.CipherSuite;

                if (!TlsUtilities.IsValidCipherSuiteSelection(offeredCipherSuites, cipherSuite) ||
                    !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, securityParameters.NegotiatedVersion))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter,
                        "ServerHello selected invalid cipher suite");
                }

                TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
                m_tlsClient.NotifySelectedCipherSuite(cipherSuite);
            }

            /*
             * RFC 3546 2.2 Note that the extended server hello message is only sent in response to an
             * extended client hello message.
             * 
             * However, see RFC 5746 exception below. We always include the SCSV, so an Extended Server
             * Hello is always allowed.
             */
            this.m_serverExtensions = serverHelloExtensions;
            if (serverHelloExtensions != null)
            {
                foreach (int extType in serverHelloExtensions.Keys)
                {
                    /*
                     * RFC 5746 3.6. Note that sending a "renegotiation_info" extension in response to a
                     * ClientHello containing only the SCSV is an explicit exception to the prohibition
                     * in RFC 5246, Section 7.4.1.4, on the server sending unsolicited extensions and is
                     * only allowed because the client is signaling its willingness to receive the
                     * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
                     */
                    if (ExtensionType.renegotiation_info == extType)
                        continue;

                    /*
                     * RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the
                     * same extension type appeared in the corresponding ClientHello. If a client
                     * receives an extension type in ServerHello that it did not request in the
                     * associated ClientHello, it MUST abort the handshake with an unsupported_extension
                     * fatal alert.
                     */
                    if (null == TlsUtilities.GetExtensionData(m_clientExtensions, extType))
                        throw new TlsFatalAlert(AlertDescription.unsupported_extension);

                    /*
                     * RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore
                     * extensions appearing in the client hello, and send a server hello containing no
                     * extensions[.]
                     */
                    if (securityParameters.IsResumedSession)
                    {
                        // TODO[compat-gnutls] GnuTLS test server sends server extensions e.g. ec_point_formats
                        // TODO[compat-openssl] OpenSSL test server sends server extensions e.g. ec_point_formats
                        // TODO[compat-polarssl] PolarSSL test server sends server extensions e.g. ec_point_formats
    //                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }
                }
            }

            byte[] renegExtData = TlsUtilities.GetExtensionData(serverHelloExtensions, ExtensionType.renegotiation_info);

            // NOT renegotiating
            {
                /*
                 * RFC 5746 3.4. Client Behavior: Initial Handshake (both full and session-resumption)
                 */

                /*
                 * When a ServerHello is received, the client MUST check if it includes the
                 * "renegotiation_info" extension:
                 */
                if (renegExtData == null)
                {
                    /*
                     * If the extension is not present, the server does not support secure
                     * renegotiation; set secure_renegotiation flag to FALSE. In this case, some clients
                     * may want to terminate the handshake instead of continuing; see Section 4.1 for
                     * discussion.
                     */
                    securityParameters.m_secureRenegotiation = false;
                }
                else
                {
                    /*
                     * If the extension is present, set the secure_renegotiation flag to TRUE. The
                     * client MUST then verify that the length of the "renegotiated_connection"
                     * field is zero, and if it is not, MUST abort the handshake (by sending a fatal
                     * handshake_failure alert).
                     */
                    securityParameters.m_secureRenegotiation = true;

                    if (!Arrays.FixedTimeEquals(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                        throw new TlsFatalAlert(AlertDescription.handshake_failure);
                }
            }

            // TODO[compat-gnutls] GnuTLS test server fails to send renegotiation_info extension when resuming
            m_tlsClient.NotifySecureRenegotiation(securityParameters.IsSecureRenegotiation);

            // extended_master_secret
            {
                bool negotiatedEms = false;

                if (TlsExtensionsUtilities.HasExtendedMasterSecretExtension(m_clientExtensions))
                {
                    negotiatedEms = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(serverHelloExtensions);

                    if (TlsUtilities.IsExtendedMasterSecretOptional(server_version))
                    {
                        if (!negotiatedEms &&
                            m_tlsClient.RequiresExtendedMasterSecret())
                        {
                            throw new TlsFatalAlert(AlertDescription.handshake_failure,
                                "Extended Master Secret extension is required");
                        }
                    }
                    else
                    {
                        if (negotiatedEms)
                        {
                            throw new TlsFatalAlert(AlertDescription.illegal_parameter,
                                "Server sent an unexpected extended_master_secret extension negotiating " + server_version);
                        }
                    }
                }

                securityParameters.m_extendedMasterSecret = negotiatedEms;
            }

            if (securityParameters.IsResumedSession &&
                securityParameters.IsExtendedMasterSecret != m_sessionParameters.IsExtendedMasterSecret)
            {
                throw new TlsFatalAlert(AlertDescription.handshake_failure,
                    "Server resumed session with mismatched extended_master_secret negotiation");
            }

            /*
             * RFC 7301 3.1. When session resumption or session tickets [...] are used, the previous
             * contents of this extension are irrelevant, and only the values in the new handshake
             * messages are considered.
             */
            securityParameters.m_applicationProtocol = TlsExtensionsUtilities.GetAlpnExtensionServer(
                serverHelloExtensions);
            securityParameters.m_applicationProtocolSet = true;

            var sessionClientExtensions = m_clientExtensions;
            var sessionServerExtensions = serverHelloExtensions;
            if (securityParameters.IsResumedSession)
            {
                if (securityParameters.CipherSuite != m_sessionParameters.CipherSuite
                    || !server_version.Equals(m_sessionParameters.NegotiatedVersion))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                sessionClientExtensions = null;
                sessionServerExtensions = m_sessionParameters.ReadServerExtensions();
            }

            if (sessionServerExtensions != null && sessionServerExtensions.Count > 0)
            {
                {
                    /*
                     * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
                     * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
                     * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
                     * client.
                     */
                    bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(
                        sessionServerExtensions);
                    if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(securityParameters.CipherSuite))
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);

                    securityParameters.m_encryptThenMac = serverSentEncryptThenMAC;
                }

                securityParameters.m_maxFragmentLength = TlsUtilities.ProcessMaxFragmentLengthExtension(
                    sessionClientExtensions, sessionServerExtensions, AlertDescription.illegal_parameter);

                securityParameters.m_truncatedHmac = TlsExtensionsUtilities.HasTruncatedHmacExtension(
                    sessionServerExtensions);

                /*
                 * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in
                 * a session resumption handshake.
                 */
                if (!securityParameters.IsResumedSession)
                {
                    // TODO[tls13] See RFC 8446 4.4.2.1
                    if (TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions,
                        ExtensionType.status_request_v2, AlertDescription.illegal_parameter))
                    {
                        securityParameters.m_statusRequestVersion = 2;
                    }
                    else if (TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions,
                        ExtensionType.status_request, AlertDescription.illegal_parameter))
                    {
                        securityParameters.m_statusRequestVersion = 1;
                    }

                    this.m_expectSessionTicket = TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions,
                        ExtensionType.session_ticket, AlertDescription.illegal_parameter);
                }
            }

            if (sessionClientExtensions != null)
            {
                m_tlsClient.ProcessServerExtensions(sessionServerExtensions);
            }

            ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength);

            if (securityParameters.IsResumedSession)
            {
                securityParameters.m_masterSecret = m_sessionMasterSecret;
                m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsClientContext));
            }
            else
            {
                InvalidateSession();
                this.m_tlsSession = TlsUtilities.ImportSession(securityParameters.SessionID, null);
            }
        }

        /// <exception cref="IOException"/>
        protected virtual void Receive13CertificateRequest(MemoryStream buf, bool postHandshakeAuth)
        {
            // TODO[tls13] Support for post_handshake_auth
            if (postHandshakeAuth)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            /* 
             * RFC 8446 4.3.2. A server which is authenticating with a certificate MAY optionally
             * request a certificate from the client.
             */

            if (m_selectedPsk13)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);

            CertificateRequest certificateRequest = CertificateRequest.Parse(m_tlsClientContext, buf);

            AssertEmpty(buf);

            if (!certificateRequest.HasCertificateRequestContext(TlsUtilities.EmptyBytes))
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);

            this.m_certificateRequest = certificateRequest;

            m_tlsClientContext.SecurityParameters.m_clientCertificateType =
                TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(m_serverExtensions,
                    CertificateType.X509);

            TlsUtilities.EstablishServerSigAlgs(m_tlsClientContext.SecurityParameters, certificateRequest);
        }

        /// <exception cref="IOException"/>
        protected virtual void Receive13EncryptedExtensions(MemoryStream buf)
        {
            byte[] extBytes = TlsUtilities.ReadOpaque16(buf);

            AssertEmpty(buf);


            this.m_serverExtensions = ReadExtensionsData13(HandshakeType.encrypted_extensions, extBytes);

            {
                /*
                 * RFC 8446 4.2. Implementations MUST NOT send extension responses if the remote
                 * endpoint did not send the corresponding extension requests, with the exception of the
                 * "cookie" extension in the HelloRetryRequest. Upon receiving such an extension, an
                 * endpoint MUST abort the handshake with an "unsupported_extension" alert.
                 */
                foreach (int extType in m_serverExtensions.Keys)
                {
                    if (null == TlsUtilities.GetExtensionData(m_clientExtensions, extType))
                        throw new TlsFatalAlert(AlertDescription.unsupported_extension);
                }
            }


            SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
            ProtocolVersion negotiatedVersion = securityParameters.NegotiatedVersion;

            securityParameters.m_applicationProtocol = TlsExtensionsUtilities.GetAlpnExtensionServer(
                m_serverExtensions);
            securityParameters.m_applicationProtocolSet = true;

            var sessionClientExtensions = m_clientExtensions;
            var sessionServerExtensions = m_serverExtensions;
            if (securityParameters.IsResumedSession)
            {
                if (securityParameters.CipherSuite != m_sessionParameters.CipherSuite
                    || !negotiatedVersion.Equals(m_sessionParameters.NegotiatedVersion))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                sessionClientExtensions = null;
                sessionServerExtensions = m_sessionParameters.ReadServerExtensions();
            }

            securityParameters.m_maxFragmentLength = TlsUtilities.ProcessMaxFragmentLengthExtension(
                sessionClientExtensions, sessionServerExtensions, AlertDescription.illegal_parameter);

            securityParameters.m_encryptThenMac = false;
            securityParameters.m_truncatedHmac = false;

            /*
             * TODO[tls13] RFC 8446 4.4.2.1. OCSP Status and SCT Extensions.
             * 
             * OCSP information is carried in an extension for a CertificateEntry.
             */
            securityParameters.m_statusRequestVersion =
                m_clientExtensions.ContainsKey(ExtensionType.status_request) ? 1 : 0;

            this.m_expectSessionTicket = false;

            if (null != sessionClientExtensions)
            {
                m_tlsClient.ProcessServerExtensions(m_serverExtensions);
            }

            ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength);
        }

        /// <exception cref="IOException"/>
        protected virtual void Receive13NewSessionTicket(MemoryStream buf)
        {
            if (!IsApplicationDataReady)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);

            // TODO[tls13] Do something more than just ignore them

    //        struct {
    //            uint32 ticket_lifetime;
    //            uint32 ticket_age_add;
    //            opaque ticket_nonce<0..255>;
    //            opaque ticket<1..2^16-1>;
    //            Extension extensions<0..2^16-2>;
    //        } NewSessionTicket;

            TlsUtilities.ReadUint32(buf);
            TlsUtilities.ReadUint32(buf);
            TlsUtilities.ReadOpaque8(buf);
            TlsUtilities.ReadOpaque16(buf);
            TlsUtilities.ReadOpaque16(buf);
            AssertEmpty(buf);
        }

        /// <exception cref="IOException"/>
        protected virtual void Receive13ServerCertificate(MemoryStream buf)
        {
            if (m_selectedPsk13)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);

            m_authentication = TlsUtilities.Receive13ServerCertificate(m_tlsClientContext, m_tlsClient, buf,
                m_serverExtensions);

            // NOTE: In TLS 1.3 we don't have to wait for a possible CertificateStatus message.
            HandleServerCertificate();
        }

        /// <exception cref="IOException"/>
        protected virtual void Receive13ServerCertificateVerify(MemoryStream buf)
        {
            Certificate serverCertificate = m_tlsClientContext.SecurityParameters.PeerCertificate;
            if (null == serverCertificate || serverCertificate.IsEmpty)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            CertificateVerify certificateVerify = CertificateVerify.Parse(m_tlsClientContext, buf);

            AssertEmpty(buf);

            TlsUtilities.Verify13CertificateVerifyServer(m_tlsClientContext, m_handshakeHash, certificateVerify);
        }

        /// <exception cref="IOException"/>
        protected virtual void Receive13ServerFinished(MemoryStream buf)
        {
            Process13FinishedMessage(buf);
        }

        /// <exception cref="IOException"/>
        protected virtual void ReceiveCertificateRequest(MemoryStream buf)
        {
            if (null == m_authentication)
            {
                /*
                 * RFC 2246 7.4.4. It is a fatal handshake_failure alert for an anonymous server to
                 * request client identification.
                 */
                throw new TlsFatalAlert(AlertDescription.handshake_failure);
            }

            CertificateRequest certificateRequest = CertificateRequest.Parse(m_tlsClientContext, buf);

            AssertEmpty(buf);

            m_certificateRequest = TlsUtilities.ValidateCertificateRequest(certificateRequest, m_keyExchange);

            m_tlsClientContext.SecurityParameters.m_clientCertificateType =
                TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(m_serverExtensions,
                    CertificateType.X509);
        }

        /// <exception cref="IOException"/>
        protected virtual void ReceiveNewSessionTicket(MemoryStream buf)
        {
            NewSessionTicket newSessionTicket = NewSessionTicket.Parse(buf);

            AssertEmpty(buf);

            m_tlsClient.NotifyNewSessionTicket(newSessionTicket);
        }

        /// <exception cref="IOException"/>
        protected virtual ServerHello ReceiveServerHelloMessage(MemoryStream buf)
        {
            return ServerHello.Parse(buf);
        }

        /// <exception cref="IOException"/>
        protected virtual void Send13ClientHelloRetry()
        {
            var clientHelloExtensions = m_clientHello.Extensions;

            clientHelloExtensions.Remove(ExtensionType.cookie);
            clientHelloExtensions.Remove(ExtensionType.early_data);
            clientHelloExtensions.Remove(ExtensionType.key_share);
            clientHelloExtensions.Remove(ExtensionType.pre_shared_key);

            /*
             * RFC 4.2.2. When sending the new ClientHello, the client MUST copy the contents of the
             * extension received in the HelloRetryRequest into a "cookie" extension in the new
             * ClientHello.
             */
            if (null != m_retryCookie)
            {
                /*
                 * - Including a "cookie" extension if one was provided in the HelloRetryRequest.
                 */
                TlsExtensionsUtilities.AddCookieExtension(clientHelloExtensions, m_retryCookie);
                this.m_retryCookie = null;
            }

            /*
             * - Updating the "pre_shared_key" extension if present by recomputing the "obfuscated_ticket_age"
             * and binder values and (optionally) removing any PSKs which are incompatible with the server's
             * indicated cipher suite.
             */
            if (null != m_clientBinders)
            {
                this.m_clientBinders = TlsUtilities.AddPreSharedKeyToClientHelloRetry(m_tlsClientContext,
                    m_clientBinders, clientHelloExtensions);
                if (null == m_clientBinders)
                {
                    m_tlsClient.NotifySelectedPsk(null);
                }
            }

            /*
             * RFC 8446 4.2.8. [..] when sending the new ClientHello, the client MUST replace the
             * original "key_share" extension with one containing only a new KeyShareEntry for the group
             * indicated in the selected_group field of the triggering HelloRetryRequest.
             */
            if (m_retryGroup < 0)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            /*
             * - If a "key_share" extension was supplied in the HelloRetryRequest, replacing the list of shares
             * with a list containing a single KeyShareEntry from the indicated group
             */
            this.m_clientAgreements = TlsUtilities.AddKeyShareToClientHelloRetry(m_tlsClientContext,
                clientHelloExtensions, m_retryGroup);

            /*
             * TODO[tls13] Optionally adding, removing, or changing the length of the "padding"
             * extension [RFC7685].
             */

            // See RFC 8446 D.4.
            {
                m_recordStream.SetIgnoreChangeCipherSpec(true);

                /*
                 * TODO[tls13] If offering early_data, the record is placed immediately after the first
                 * ClientHello.
                 */
                SendChangeCipherSpecMessage();
            }

            SendClientHelloMessage();
        }

        /// <exception cref="IOException"/>
        protected virtual void SendCertificateVerifyMessage(DigitallySigned certificateVerify)
        {
            HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.certificate_verify);
            certificateVerify.Encode(message);
            message.Send(this);
        }

        /// <exception cref="IOException"/>
        protected virtual void SendClientHello()
        {
            SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;

            ProtocolVersion[] supportedVersions;
            ProtocolVersion earliestVersion, latestVersion;

            // NOT renegotiating
            {
                supportedVersions = m_tlsClient.GetProtocolVersions();

                if (ProtocolVersion.Contains(supportedVersions, ProtocolVersion.SSLv3))
                {
                    // TODO[tls13] Prevent offering SSLv3 AND TLSv13?
                    m_recordStream.SetWriteVersion(ProtocolVersion.SSLv3);
                }
                else
                {
                    m_recordStream.SetWriteVersion(ProtocolVersion.TLSv10);
                }

                earliestVersion = ProtocolVersion.GetEarliestTls(supportedVersions);
                latestVersion = ProtocolVersion.GetLatestTls(supportedVersions);

                if (!ProtocolVersion.IsSupportedTlsVersionClient(latestVersion))
                    throw new TlsFatalAlert(AlertDescription.internal_error);

                m_tlsClientContext.SetClientVersion(latestVersion);
            }

            m_tlsClientContext.SetClientSupportedVersions(supportedVersions);

            bool offeringTlsV12Minus = ProtocolVersion.TLSv12.IsEqualOrLaterVersionOf(earliestVersion);
            bool offeringTlsV13Plus = ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(latestVersion);

            {
                bool useGmtUnixTime = !offeringTlsV13Plus && m_tlsClient.ShouldUseGmtUnixTime();

                securityParameters.m_clientRandom = CreateRandomBlock(useGmtUnixTime, m_tlsClientContext);
            }

            TlsSession sessionToResume = offeringTlsV12Minus ? m_tlsClient.GetSessionToResume() : null;

            bool fallback = m_tlsClient.IsFallback();

            int[] offeredCipherSuites = m_tlsClient.GetCipherSuites();

            this.m_clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(m_tlsClient.GetClientExtensions());

            bool shouldUseEms = m_tlsClient.ShouldUseExtendedMasterSecret();

            EstablishSession(sessionToResume);

            byte[] legacy_session_id = TlsUtilities.GetSessionID(m_tlsSession);

            if (legacy_session_id.Length > 0)
            {
                if (!Arrays.Contains(offeredCipherSuites, m_sessionParameters.CipherSuite))
                {
                    legacy_session_id = TlsUtilities.EmptyBytes;
                }
            }

            ProtocolVersion sessionVersion = null;
            if (legacy_session_id.Length > 0)
            {
                sessionVersion = m_sessionParameters.NegotiatedVersion;

                if (!ProtocolVersion.Contains(supportedVersions, sessionVersion))
                {
                    legacy_session_id = TlsUtilities.EmptyBytes;
                }
            }

            if (legacy_session_id.Length > 0 && TlsUtilities.IsExtendedMasterSecretOptional(sessionVersion))
            {
                if (shouldUseEms)
                {
                    if (!m_sessionParameters.IsExtendedMasterSecret &&
                        !m_tlsClient.AllowLegacyResumption())
                    {
                        legacy_session_id = TlsUtilities.EmptyBytes;
                    }
                }
                else
                {
                    if (m_sessionParameters.IsExtendedMasterSecret)
                    {
                        legacy_session_id = TlsUtilities.EmptyBytes;
                    }
                }
            }

            if (legacy_session_id.Length < 1)
            {
                CancelSession();
            }

            m_tlsClient.NotifySessionToResume(m_tlsSession);

            ProtocolVersion legacy_version = latestVersion;
            if (offeringTlsV13Plus)
            {
                legacy_version = ProtocolVersion.TLSv12;

                TlsExtensionsUtilities.AddSupportedVersionsExtensionClient(m_clientExtensions, supportedVersions);

                /*
                 * RFC 8446 4.2.1. In compatibility mode [..], this field MUST be non-empty, so a client
                 * not offering a pre-TLS 1.3 session MUST generate a new 32-byte value.
                 */
                if (legacy_session_id.Length < 1 && TlsUtilities.ShouldUseCompatibilityMode(m_tlsClient))
                {
                    legacy_session_id = m_tlsClientContext.NonceGenerator.GenerateNonce(32);
                }
            }

            m_tlsClientContext.SetRsaPreMasterSecretVersion(legacy_version);

            securityParameters.m_clientServerNames = TlsExtensionsUtilities.GetServerNameExtensionClient(
                m_clientExtensions);

            if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(latestVersion))
            {
                TlsUtilities.EstablishClientSigAlgs(securityParameters, m_clientExtensions);
            }

            securityParameters.m_clientSupportedGroups = TlsExtensionsUtilities.GetSupportedGroupsExtension(
                m_clientExtensions);

            this.m_clientBinders = TlsUtilities.AddPreSharedKeyToClientHello(m_tlsClientContext, m_tlsClient,
                m_clientExtensions, offeredCipherSuites);

            // TODO[tls13-psk] Perhaps don't add key_share if external PSK(s) offered and 'psk_dhe_ke' not offered  
            this.m_clientAgreements = TlsUtilities.AddKeyShareToClientHello(m_tlsClientContext, m_tlsClient,
                m_clientExtensions);

            if (shouldUseEms && TlsUtilities.IsExtendedMasterSecretOptional(supportedVersions))
            {
                TlsExtensionsUtilities.AddExtendedMasterSecretExtension(this.m_clientExtensions);
            }
            else
            {
                this.m_clientExtensions.Remove(ExtensionType.extended_master_secret);
            }

            // NOT renegotiating
            {
                /*
                 * RFC 5746 3.4. Client Behavior: Initial Handshake (both full and session-resumption)
                 */

                /*
                 * The client MUST include either an empty "renegotiation_info" extension, or the
                 * TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the ClientHello.
                 * Including both is NOT RECOMMENDED.
                 */
                bool noRenegExt = (null == TlsUtilities.GetExtensionData(m_clientExtensions,
                    ExtensionType.renegotiation_info));
                bool noRenegScsv = !Arrays.Contains(offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);

                if (noRenegExt && noRenegScsv)
                {
                    // TODO[tls13] Probably want to not add this if no pre-TLSv13 versions offered?
                    offeredCipherSuites = Arrays.Append(offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
                }
            }

            /*
             * (Fallback SCSV)
             * RFC 7507 4. If a client sends a ClientHello.client_version containing a lower value
             * than the latest (highest-valued) version supported by the client, it SHOULD include
             * the TLS_FALLBACK_SCSV cipher suite value in ClientHello.cipher_suites [..]. (The
             * client SHOULD put TLS_FALLBACK_SCSV after all cipher suites that it actually intends
             * to negotiate.)
             */
            if (fallback && !Arrays.Contains(offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV))
            {
                offeredCipherSuites = Arrays.Append(offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV);
            }



            int bindersSize = null == m_clientBinders ? 0 : m_clientBinders.m_bindersSize;

            this.m_clientHello = new ClientHello(legacy_version, securityParameters.ClientRandom, legacy_session_id,
                cookie: null, offeredCipherSuites, m_clientExtensions, bindersSize);

            SendClientHelloMessage();
        }

        /// <exception cref="IOException"/>
        protected virtual void SendClientHelloMessage()
        {
            HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.client_hello);
            m_clientHello.Encode(m_tlsClientContext, message);

            message.PrepareClientHello(m_handshakeHash, m_clientHello.BindersSize);

            if (null != m_clientBinders)
            {
                OfferedPsks.EncodeBinders(message, m_tlsClientContext.Crypto, m_handshakeHash, m_clientBinders);
            }

            message.SendClientHello(this, m_handshakeHash, m_clientHello.BindersSize);
        }

        /// <exception cref="IOException"/>
        protected virtual void SendClientKeyExchange()
        {
            HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.client_key_exchange);
            m_keyExchange.GenerateClientKeyExchange(message);
            message.Send(this);
        }

        /// <exception cref="IOException"/>
        protected virtual void Skip13CertificateRequest()
        {
            this.m_certificateRequest = null;
        }

        /// <exception cref="IOException"/>
        protected virtual void Skip13ServerCertificate()
        {
            if (!m_selectedPsk13)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);

            this.m_authentication = TlsUtilities.Skip13ServerCertificate(m_tlsClientContext);
        }
    }
}