summary refs log tree commit diff
path: root/crypto/src/crypto/tls/TlsProtocolHandler.cs
blob: d40e179aa4cfb41d2d0a4d5697c4edb26491d569 (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
using System;
using System.Collections;
using System.IO;
using System.Text;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Agreement.Srp;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Date;

namespace Org.BouncyCastle.Crypto.Tls
{
    /// <remarks>An implementation of all high level protocols in TLS 1.0.</remarks>
    public class TlsProtocolHandler
    {
        /*
        * Our Connection states
        */
        private const short CS_CLIENT_HELLO_SEND = 1;
        private const short CS_SERVER_HELLO_RECEIVED = 2;
        private const short CS_SERVER_CERTIFICATE_RECEIVED = 3;
        private const short CS_SERVER_KEY_EXCHANGE_RECEIVED = 4;
        private const short CS_CERTIFICATE_REQUEST_RECEIVED = 5;
        private const short CS_SERVER_HELLO_DONE_RECEIVED = 6;
        private const short CS_CLIENT_KEY_EXCHANGE_SEND = 7;
        private const short CS_CERTIFICATE_VERIFY_SEND = 8;
        private const short CS_CLIENT_CHANGE_CIPHER_SPEC_SEND = 9;
        private const short CS_CLIENT_FINISHED_SEND = 10;
        private const short CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED = 11;
        private const short CS_DONE = 12;

        private static readonly string TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack";

        /*
        * Queues for data from some protocols.
        */

        private ByteQueue applicationDataQueue = new ByteQueue();
        private ByteQueue alertQueue = new ByteQueue(2);
        private ByteQueue handshakeQueue = new ByteQueue();

        /*
        * The Record Stream we use
        */
        private RecordStream rs;
        private SecureRandom random;

        private TlsStream tlsStream = null;

        private bool closed = false;
        private bool failedWithError = false;
        private bool appDataReady = false;
        private IDictionary clientExtensions;

        private SecurityParameters securityParameters = null;

        private TlsClientContextImpl tlsClientContext = null;
        private TlsClient tlsClient = null;
        private int[] offeredCipherSuites = null;
        private byte[] offeredCompressionMethods = null;
        private TlsKeyExchange keyExchange = null;
        private TlsAuthentication authentication = null;
        private CertificateRequest certificateRequest = null;

        private short connection_state = 0;

        private static SecureRandom CreateSecureRandom()
        {
            /*
             * We use our threaded seed generator to generate a good random seed. If the user
             * has a better random seed, he should use the constructor with a SecureRandom.
             *
             * Hopefully, 20 bytes in fast mode are good enough.
             */
            byte[] seed = new ThreadedSeedGenerator().GenerateSeed(20, true);

            return new SecureRandom(seed);
        }

        public TlsProtocolHandler(
            Stream s)
            : this(s, s)
        {
        }

        public TlsProtocolHandler(
            Stream			s,
            SecureRandom	sr)
            : this(s, s, sr)
        {
        }

        /// <remarks>Both streams can be the same object</remarks>
        public TlsProtocolHandler(
            Stream	inStr,
            Stream	outStr)
            : this(inStr, outStr, CreateSecureRandom())
        {
        }

        /// <remarks>Both streams can be the same object</remarks>
        public TlsProtocolHandler(
            Stream			inStr,
            Stream			outStr,
            SecureRandom	sr)
        {
            this.rs = new RecordStream(this, inStr, outStr);
            this.random = sr;
        }

        internal void ProcessData(
            byte    contentType,
            byte[]	buf,
            int		offset,
            int		len)
        {
            /*
            * Have a look at the protocol type, and add it to the correct queue.
            */
            switch (contentType)
            {
                case ContentType.change_cipher_spec:
                    ProcessChangeCipherSpec(buf, offset, len);
                    break;
                case ContentType.alert:
                    alertQueue.AddData(buf, offset, len);
                    ProcessAlert();
                    break;
                case ContentType.handshake:
                    handshakeQueue.AddData(buf, offset, len);
                    ProcessHandshake();
                    break;
                case ContentType.application_data:
                    if (!appDataReady)
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    }
                    applicationDataQueue.AddData(buf, offset, len);
                    ProcessApplicationData();
                    break;
                default:
                    /*
                    * Uh, we don't know this protocol.
                    *
                    * RFC2246 defines on page 13, that we should ignore this.
                    */
                    break;
            }
        }

        private void ProcessHandshake()
        {
            bool read;
            do
            {
                read = false;

                /*
                * We need the first 4 bytes, they contain type and length of
                * the message.
                */
                if (handshakeQueue.Available >= 4)
                {
                    byte[] beginning = new byte[4];
                    handshakeQueue.Read(beginning, 0, 4, 0);
                    MemoryStream bis = new MemoryStream(beginning, false);
                    byte handshakeType = TlsUtilities.ReadUint8(bis);
                    int len = TlsUtilities.ReadUint24(bis);

                    /*
                    * Check if we have enough bytes in the buffer to read
                    * the full message.
                    */
                    if (handshakeQueue.Available >= (len + 4))
                    {
                        /*
                        * Read the message.
                        */
                        byte[] buf = handshakeQueue.RemoveData(len, 4);

                        /*
                         * RFC 2246 7.4.9. The value handshake_messages includes all
                         * handshake messages starting at client hello up to, but not
                         * including, this finished message. [..] Note: [Also,] Hello Request
                         * messages are omitted from handshake hashes.
                         */
                        switch (handshakeType)
                        {
                            case HandshakeType.hello_request:
                            case HandshakeType.finished:
                                break;
                            default:
                                rs.UpdateHandshakeData(beginning, 0, 4);
                                rs.UpdateHandshakeData(buf, 0, len);
                                break;
                        }

                        /*
                        * Now, parse the message.
                        */
                        ProcessHandshakeMessage(handshakeType, buf);
                        read = true;
                    }
                }
            }
            while (read);
        }

        private void ProcessHandshakeMessage(byte handshakeType, byte[] buf)
        {
            MemoryStream inStr = new MemoryStream(buf, false);

            /*
            * Check the type.
            */
            switch (handshakeType)
            {
                case HandshakeType.certificate:
                {
                    switch (connection_state)
                    {
                        case CS_SERVER_HELLO_RECEIVED:
                        {
                            // Parse the Certificate message and send to cipher suite

                            Certificate serverCertificate = Certificate.Parse(inStr);

                            AssertEmpty(inStr);

                            this.keyExchange.ProcessServerCertificate(serverCertificate);

                            this.authentication = tlsClient.GetAuthentication();
                            this.authentication.NotifyServerCertificate(serverCertificate);

                            break;
                        }
                        default:
                            this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                            break;
                    }

                    connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
                    break;
                }
                case HandshakeType.finished:
                    switch (connection_state)
                    {
                        case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
                            /*
                             * Read the checksum from the finished message, it has always 12 bytes.
                             */
                            byte[] serverVerifyData = new byte[12];
                            TlsUtilities.ReadFully(serverVerifyData, inStr);

                            AssertEmpty(inStr);

                            /*
                             * Calculate our own checksum.
                             */
                            byte[] expectedServerVerifyData = TlsUtilities.PRF(
                                securityParameters.masterSecret, "server finished",
                                rs.GetCurrentHash(), 12);

                            /*
                             * Compare both checksums.
                             */
                            if (!Arrays.ConstantTimeAreEqual(expectedServerVerifyData, serverVerifyData))
                            {
                                /*
                                 * Wrong checksum in the finished message.
                                 */
                                this.FailWithError(AlertLevel.fatal, AlertDescription.decrypt_error);
                            }

                            connection_state = CS_DONE;

                            /*
                            * We are now ready to receive application data.
                            */
                            this.appDataReady = true;
                            break;
                        default:
                            this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                            break;
                    }
                    break;
                case HandshakeType.server_hello:
                    switch (connection_state)
                    {
                        case CS_CLIENT_HELLO_SEND:
                            /*
                             * Read the server hello message
                             */
                            TlsUtilities.CheckVersion(inStr);

                            /*
                             * Read the server random
                             */
                            securityParameters.serverRandom = new byte[32];
                            TlsUtilities.ReadFully(securityParameters.serverRandom, inStr);

                            byte[] sessionID = TlsUtilities.ReadOpaque8(inStr);
                            if (sessionID.Length > 32)
                            {
                                this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                            }

                            this.tlsClient.NotifySessionID(sessionID);

                            /*
                             * Find out which CipherSuite the server has chosen and check that
                             * it was one of the offered ones.
                             */
                            int selectedCipherSuite = TlsUtilities.ReadUint16(inStr);
                            if (!ArrayContains(offeredCipherSuites, selectedCipherSuite)
                                || selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
                            {
                                this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                            }

                            this.tlsClient.NotifySelectedCipherSuite(selectedCipherSuite);

                            /*
                             * Find out which CompressionMethod the server has chosen and check that
                             * it was one of the offered ones.
                             */
                            byte selectedCompressionMethod = TlsUtilities.ReadUint8(inStr);
                            if (!ArrayContains(offeredCompressionMethods, selectedCompressionMethod))
                            {
                                this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                            }

                            this.tlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod);

                            /*
                             * RFC3546 2.2 The extended server hello message format MAY be
                             * sent in place of the server hello message when the client has
                             * requested extended functionality via the extended client hello
                             * message specified in Section 2.1.
                             * ...
                             * Note that the extended server hello message is only sent in response
                             * to an extended client hello message.  This prevents the possibility
                             * that the extended server hello message could "break" existing TLS 1.0
                             * clients.
                             */

                            /*
                             * TODO 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.
                             */

                            // Int32 -> byte[]
                            IDictionary serverExtensions = Platform.CreateHashtable();

                            if (inStr.Position < inStr.Length)
                            {
                                // Process extensions from extended server hello
                                byte[] extBytes = TlsUtilities.ReadOpaque16(inStr);

                                MemoryStream ext = new MemoryStream(extBytes, false);
                                while (ext.Position < ext.Length)
                                {
                                    int extType = TlsUtilities.ReadUint16(ext);
                                    byte[] extValue = TlsUtilities.ReadOpaque16(ext);

                                    // Note: RFC 5746 makes a special case for EXT_RenegotiationInfo
                                    if (extType != ExtensionType.renegotiation_info
                                        && !clientExtensions.Contains(extType))
                                    {
                                        /*
                                         * RFC 3546 2.3
                                         * Note that for all extension types (including those defined in
                                         * future), the extension type MUST NOT appear in the extended server
                                         * hello unless the same extension type appeared in the corresponding
                                         * client hello.  Thus clients MUST abort the handshake if they receive
                                         * an extension type in the extended server hello that they did not
                                         * request in the associated (extended) client hello.
                                         */
                                        this.FailWithError(AlertLevel.fatal, AlertDescription.unsupported_extension);
                                    }

                                    if (serverExtensions.Contains(extType))
                                    {
                                        /*
                                         * RFC 3546 2.3
                                         * Also note that when multiple extensions of different types are
                                         * present in the extended client hello or the extended server hello,
                                         * the extensions may appear in any order. There MUST NOT be more than
                                         * one extension of the same type.
                                         */
                                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                                    }

                                    serverExtensions.Add(extType, extValue);
                                }
                            }

                            AssertEmpty(inStr);

                            /*
                             * RFC 5746 3.4. When a ServerHello is received, the client MUST check if it
                             * includes the "renegotiation_info" extension:
                             */
                            {
                                bool secure_negotiation = serverExtensions.Contains(ExtensionType.renegotiation_info);

                                /*
                                 * 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).
                                 */
                                if (secure_negotiation)
                                {
                                    byte[] renegExtValue = (byte[])serverExtensions[ExtensionType.renegotiation_info];

                                    if (!Arrays.ConstantTimeAreEqual(renegExtValue,
                                        CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                                    {
                                        this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                                    }
                                }

                                tlsClient.NotifySecureRenegotiation(secure_negotiation);
                            }

                            if (clientExtensions != null)
                            {
                                tlsClient.ProcessServerExtensions(serverExtensions);
                            }

                            this.keyExchange = tlsClient.GetKeyExchange();

                            connection_state = CS_SERVER_HELLO_RECEIVED;
                            break;
                        default:
                            this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                            break;
                    }
                    break;
                case HandshakeType.server_hello_done:
                    switch (connection_state)
                    {
                        case CS_SERVER_HELLO_RECEIVED:
                        case CS_SERVER_CERTIFICATE_RECEIVED:
                        case CS_SERVER_KEY_EXCHANGE_RECEIVED:
                        case CS_CERTIFICATE_REQUEST_RECEIVED:

                            // NB: Original code used case label fall-through

                            if (connection_state == CS_SERVER_HELLO_RECEIVED)
                            {
                                // There was no server certificate message; check it's OK
                                this.keyExchange.SkipServerCertificate();
                                this.authentication = null;

                                // There was no server key exchange message; check it's OK
                                this.keyExchange.SkipServerKeyExchange();
                            }
                            else if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED)
                            {
                                // There was no server key exchange message; check it's OK
                                this.keyExchange.SkipServerKeyExchange();
                            }

                            AssertEmpty(inStr);

                            connection_state = CS_SERVER_HELLO_DONE_RECEIVED;

                            TlsCredentials clientCreds = null;
                            if (certificateRequest == null)
                            {
                                this.keyExchange.SkipClientCredentials();
                            }
                            else
                            {
                                clientCreds = this.authentication.GetClientCredentials(certificateRequest);

                                Certificate clientCert;
                                if (clientCreds == null)
                                {
                                    this.keyExchange.SkipClientCredentials();
                                    clientCert = Certificate.EmptyChain;
                                }
                                else
                                {
                                    this.keyExchange.ProcessClientCredentials(clientCreds);
                                    clientCert = clientCreds.Certificate;
                                }

                                SendClientCertificate(clientCert);
                            }

                            /*
                             * Send the client key exchange message, depending on the key
                             * exchange we are using in our CipherSuite.
                             */
                            SendClientKeyExchange();

                            connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;

                            if (clientCreds != null && clientCreds is TlsSignerCredentials)
                            {
                                TlsSignerCredentials signerCreds = (TlsSignerCredentials)clientCreds;
                                byte[] md5andsha1 = rs.GetCurrentHash();
                                byte[] clientCertificateSignature = signerCreds.GenerateCertificateSignature(
                                    md5andsha1);
                                SendCertificateVerify(clientCertificateSignature);

                                connection_state = CS_CERTIFICATE_VERIFY_SEND;
                            }
                    
                            /*
                            * Now, we send change cipher state
                            */
                            byte[] cmessage = new byte[1];
                            cmessage[0] = 1;
                            rs.WriteMessage(ContentType.change_cipher_spec, cmessage, 0, cmessage.Length);

                            connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;

                            /*
                             * Calculate the master_secret
                             */
                            byte[] pms = this.keyExchange.GeneratePremasterSecret();

                            securityParameters.masterSecret = TlsUtilities.PRF(pms, "master secret",
                                TlsUtilities.Concat(securityParameters.clientRandom, securityParameters.serverRandom),
                                48);

                            // TODO Is there a way to ensure the data is really overwritten?
                            /*
                             * RFC 2246 8.1. The pre_master_secret should be deleted from
                             * memory once the master_secret has been computed.
                             */
                            Array.Clear(pms, 0, pms.Length);

                            /*
                             * Initialize our cipher suite
                             */
                            rs.ClientCipherSpecDecided(tlsClient.GetCompression(), tlsClient.GetCipher());

                            /*
                             * Send our finished message.
                             */
                            byte[] clientVerifyData = TlsUtilities.PRF(securityParameters.masterSecret,
                                "client finished", rs.GetCurrentHash(), 12);

                            MemoryStream bos = new MemoryStream();
                            TlsUtilities.WriteUint8((byte)HandshakeType.finished, bos);
                            TlsUtilities.WriteOpaque24(clientVerifyData, bos);
                            byte[] message = bos.ToArray();

                            rs.WriteMessage(ContentType.handshake, message, 0, message.Length);

                            this.connection_state = CS_CLIENT_FINISHED_SEND;
                            break;
                        default:
                            this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                            break;
                    }
                    break;
                case HandshakeType.server_key_exchange:
                {
                    switch (connection_state)
                    {
                        case CS_SERVER_HELLO_RECEIVED:
                        case CS_SERVER_CERTIFICATE_RECEIVED:
                        {
                            // NB: Original code used case label fall-through
                            if (connection_state == CS_SERVER_HELLO_RECEIVED)
                            {
                                // There was no server certificate message; check it's OK
                                this.keyExchange.SkipServerCertificate();
                                this.authentication = null;
                            }

                            this.keyExchange.ProcessServerKeyExchange(inStr);

                            AssertEmpty(inStr);
                            break;
                        }
                        default:
                            this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                            break;
                    }

                    this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
                    break;
                }
                case HandshakeType.certificate_request:
                    switch (connection_state)
                    {
                        case CS_SERVER_CERTIFICATE_RECEIVED:
                        case CS_SERVER_KEY_EXCHANGE_RECEIVED:
                        {
                            // NB: Original code used case label fall-through
                            if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED)
                            {
                                // There was no server key exchange message; check it's OK
                                this.keyExchange.SkipServerKeyExchange();
                            }

                            if (this.authentication == null)
                            {
                                /*
                                 * RFC 2246 7.4.4. It is a fatal handshake_failure alert
                                 * for an anonymous server to request client identification.
                                 */
                                this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                            }

                            this.certificateRequest = CertificateRequest.Parse(//getContext(),
                                inStr);

                            AssertEmpty(inStr);

                            this.keyExchange.ValidateCertificateRequest(this.certificateRequest);

                            break;
                        }
                        default:
                            this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                            break;
                    }

                    this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
                    break;
                case HandshakeType.hello_request:
                    /*
                     * 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 (connection_state == CS_DONE)
                    {
                        // Renegotiation not supported yet
                        SendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
                    }
                    break;
                case HandshakeType.client_key_exchange:
                case HandshakeType.certificate_verify:
                case HandshakeType.client_hello:
                default:
                    // We do not support this!
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
            }
        }

        private void ProcessApplicationData()
        {
            /*
            * There is nothing we need to do here.
            *
            * This function could be used for callbacks when application
            * data arrives in the future.
            */
        }

        private void ProcessAlert()
        {
            while (alertQueue.Available >= 2)
            {
                /*
                * An alert is always 2 bytes. Read the alert.
                */
                byte[] tmp = alertQueue.RemoveData(2, 0);
                byte level = tmp[0];
                byte description = tmp[1];
                if (level == (byte)AlertLevel.fatal)
                {
                    this.failedWithError = true;
                    this.closed = true;
                    /*
                    * Now try to Close the stream, ignore errors.
                    */
                    try
                    {
                        rs.Close();
                    }
                    catch (Exception)
                    {
                    }
                    throw new IOException(TLS_ERROR_MESSAGE);
                }
                else
                {
                    if (description == (byte)AlertDescription.close_notify)
                    {
                        HandleClose(false);
                    }

                    /*
                    * If it is just a warning, we continue.
                    */
                }
            }
        }

        /**
        * This method is called, when a change cipher spec message is received.
        *
        * @throws IOException If the message has an invalid content or the
        *                     handshake is not in the correct state.
        */
        private void ProcessChangeCipherSpec(byte[] buf, int off, int len)
        {
            for (int i = 0; i < len; ++i)
            {
                if (buf[off + i] != 1)
                {
                    this.FailWithError(AlertLevel.fatal, AlertDescription.decode_error);
                }

                /*
                 * Check if we are in the correct connection state.
                 */
                if (this.connection_state != CS_CLIENT_FINISHED_SEND)
                {
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                }

                rs.ServerClientSpecReceived();

                this.connection_state = CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED;
            }
        }

        private void SendClientCertificate(Certificate clientCert)
        {
            MemoryStream bos = new MemoryStream();
            TlsUtilities.WriteUint8((byte)HandshakeType.certificate, bos);

            // Reserve space for length
            TlsUtilities.WriteUint24(0, bos);

            clientCert.Encode(bos);
            byte[] message = bos.ToArray();

            // Patch actual length back in
            TlsUtilities.WriteUint24(message.Length - 4, message, 1);

            rs.WriteMessage(ContentType.handshake, message, 0, message.Length);
        }

        private void SendClientKeyExchange()
        {
            MemoryStream bos = new MemoryStream();
            TlsUtilities.WriteUint8((byte)HandshakeType.client_key_exchange, bos);

            // Reserve space for length
            TlsUtilities.WriteUint24(0, bos);

            this.keyExchange.GenerateClientKeyExchange(bos);
            byte[] message = bos.ToArray();

            // Patch actual length back in
            TlsUtilities.WriteUint24(message.Length - 4, message, 1);

            rs.WriteMessage(ContentType.handshake, message, 0, message.Length);
        }

        private void SendCertificateVerify(byte[] data)
        {
            /*
             * Send signature of handshake messages so far to prove we are the owner of
             * the cert See RFC 2246 sections 4.7, 7.4.3 and 7.4.8
             */
            MemoryStream bos = new MemoryStream();
            TlsUtilities.WriteUint8((byte)HandshakeType.certificate_verify, bos);
            TlsUtilities.WriteUint24(data.Length + 2, bos);
            TlsUtilities.WriteOpaque16(data, bos);
            byte[] message = bos.ToArray();

            rs.WriteMessage(ContentType.handshake, message, 0, message.Length);
        }

        /// <summary>Connects to the remote system.</summary>
        /// <param name="verifyer">Will be used when a certificate is received to verify
        /// that this certificate is accepted by the client.</param>
        /// <exception cref="IOException">If handshake was not successful</exception>
        [Obsolete("Use version taking TlsClient")]
        public virtual void Connect(
            ICertificateVerifyer verifyer)
        {
            this.Connect(new LegacyTlsClient(verifyer));
        }

        public virtual void Connect(TlsClient tlsClient)
        {
            if (tlsClient == null)
                throw new ArgumentNullException("tlsClient");
            if (this.tlsClient != null)
                throw new InvalidOperationException("Connect can only be called once");

            /*
             * Send Client hello
             *
             * First, generate some random data.
             */
            this.securityParameters = new SecurityParameters();
            this.securityParameters.clientRandom = CreateRandomBlock(tlsClient.ShouldUseGmtUnixTime(), random,
                ExporterLabel.client_random);

            this.tlsClientContext = new TlsClientContextImpl(random, securityParameters);
            this.tlsClient = tlsClient;
            this.tlsClient.Init(tlsClientContext);

            MemoryStream outStr = new MemoryStream();
            TlsUtilities.WriteVersion(outStr);
            outStr.Write(securityParameters.clientRandom, 0, 32);

            /*
            * Length of Session id
            */
            TlsUtilities.WriteUint8(0, outStr);

            this.offeredCipherSuites = this.tlsClient.GetCipherSuites();

            // Int32 -> byte[]
            this.clientExtensions = this.tlsClient.GetClientExtensions();

            // Cipher Suites (and SCSV)
            {
                /*
                 * RFC 5746 3.4.
                 * 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 = clientExtensions == null
                    || !clientExtensions.Contains(ExtensionType.renegotiation_info);

                int count = offeredCipherSuites.Length;
                if (noRenegExt)
                {
                    // Note: 1 extra slot for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
                    ++count;
                }

                TlsUtilities.WriteUint16(2 * count, outStr);

                for (int i = 0; i < offeredCipherSuites.Length; ++i)
                {
                    TlsUtilities.WriteUint16((int)offeredCipherSuites[i], outStr);
                }

                if (noRenegExt)
                {
                    TlsUtilities.WriteUint16((int)CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV, outStr);
                }
            }

            /*
             * Compression methods, just the null method.
             */
            this.offeredCompressionMethods = tlsClient.GetCompressionMethods();

            {
                TlsUtilities.WriteUint8((byte)offeredCompressionMethods.Length, outStr);
                for (int i = 0; i < offeredCompressionMethods.Length; ++i)
                {
                    TlsUtilities.WriteUint8(offeredCompressionMethods[i], outStr);
                }
            }

            // Extensions
            if (clientExtensions != null)
            {
                MemoryStream ext = new MemoryStream();

                foreach (int extType in clientExtensions.Keys)
                {
                    WriteExtension(ext, extType, (byte[])clientExtensions[extType]);
                }

                TlsUtilities.WriteOpaque16(ext.ToArray(), outStr);
            }

            MemoryStream bos = new MemoryStream();
            TlsUtilities.WriteUint8((byte)HandshakeType.client_hello, bos);
            TlsUtilities.WriteUint24((int)outStr.Length, bos);
            byte[] outBytes = outStr.ToArray();
            bos.Write(outBytes, 0, outBytes.Length);
            byte[] message = bos.ToArray();
            SafeWriteMessage(ContentType.handshake, message, 0, message.Length);
            connection_state = CS_CLIENT_HELLO_SEND;

            /*
            * We will now read data, until we have completed the handshake.
            */
            while (connection_state != CS_DONE)
            {
                SafeReadData();
            }

            this.tlsStream = new TlsStream(this);
        }

        /**
        * Read data from the network. The method will return immediately, if there is
        * still some data left in the buffer, or block until some application
        * data has been read from the network.
        *
        * @param buf    The buffer where the data will be copied to.
        * @param offset The position where the data will be placed in the buffer.
        * @param len    The maximum number of bytes to read.
        * @return The number of bytes read.
        * @throws IOException If something goes wrong during reading data.
        */
        internal int ReadApplicationData(byte[] buf, int offset, int len)
        {
            while (applicationDataQueue.Available == 0)
            {
                if (this.closed)
                {
                    /*
                    * We need to read some data.
                    */
                    if (this.failedWithError)
                    {
                        /*
                        * Something went terribly wrong, we should throw an IOException
                        */
                        throw new IOException(TLS_ERROR_MESSAGE);
                    }

                    /*
                    * Connection has been closed, there is no more data to read.
                    */
                    return 0;
                }

                SafeReadData();
            }
            len = System.Math.Min(len, applicationDataQueue.Available);
            applicationDataQueue.RemoveData(buf, offset, len, 0);
            return len;
        }

        private void SafeReadData()
        {
            try
            {
                rs.ReadData();
            }
            catch (TlsFatalAlert e)
            {
                if (!this.closed)
                {
                    this.FailWithError(AlertLevel.fatal, e.AlertDescription);
                }
                throw e;
            }
            catch (IOException e)
            {
                if (!this.closed)
                {
                    this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error);
                }
                throw e;
            }
            catch (Exception e)
            {
                if (!this.closed)
                {
                    this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error);
                }
                throw e;
            }
        }

        private void SafeWriteMessage(byte type, byte[] buf, int offset, int len)
        {
            try
            {
                rs.WriteMessage(type, buf, offset, len);
            }
            catch (TlsFatalAlert e)
            {
                if (!this.closed)
                {
                    this.FailWithError(AlertLevel.fatal, e.AlertDescription);
                }
                throw e;
            }
            catch (IOException e)
            {
                if (!closed)
                {
                    this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error);
                }
                throw e;
            }
            catch (Exception e)
            {
                if (!closed)
                {
                    this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error);
                }
                throw e;
            }
        }

        /**
        * Send some application data to the remote system.
        * <p/>
        * The method will handle fragmentation internally.
        *
        * @param buf    The buffer with the data.
        * @param offset The position in the buffer where the data is placed.
        * @param len    The length of the data.
        * @throws IOException If something goes wrong during sending.
        */
        internal void WriteData(byte[] buf, int offset, int len)
        {
            if (this.closed)
            {
                if (this.failedWithError)
                    throw new IOException(TLS_ERROR_MESSAGE);

                throw new IOException("Sorry, connection has been closed, you cannot write more data");
            }

            while (len > 0)
            {
                /*
                 * RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are
                 * potentially useful as a traffic analysis countermeasure.
                 * 
                 * NOTE: Actually, implementations appear to have settled on 1/n-1 record splitting.
                 */

                //if (this.splitApplicationDataRecords)
                {
                    /*
                     * Protect against known IV attack!
                     * 
                     * DO NOT REMOVE THIS CODE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE.
                     */
                    SafeWriteMessage(ContentType.application_data, buf, offset, 1);
                    ++offset;
                    --len;
                }

                if (len > 0)
                {
                    // Fragment data according to the current fragment limit.
                    //int toWrite = System.Math.Min(len, recordStream.GetPlaintextLimit());
                    int toWrite = System.Math.Min(len, 1 << 14);
                    SafeWriteMessage(ContentType.application_data, buf, offset, toWrite);
                    offset += toWrite;
                    len -= toWrite;
                }
            }
        }

        /// <summary>A Stream which can be used to send data.</summary>
        [Obsolete("Use 'Stream' property instead")]
        public virtual Stream OutputStream
        {
            get { return this.tlsStream; }
        }

        /// <summary>A Stream which can be used to read data.</summary>
        [Obsolete("Use 'Stream' property instead")]
        public virtual Stream InputStream
        {
            get { return this.tlsStream; }
        }

        /// <summary>The secure bidirectional stream for this connection</summary>
        public virtual Stream Stream
        {
            get { return this.tlsStream; }
        }

        /**
        * Terminate this connection with an alert.
        * <p/>
        * Can be used for normal closure too.
        *
        * @param alertLevel       The level of the alert, an be AlertLevel.fatal or AL_warning.
        * @param alertDescription The exact alert message.
        * @throws IOException If alert was fatal.
        */
        private void FailWithError(byte alertLevel, byte alertDescription)
        {
            /*
            * Check if the connection is still open.
            */
            if (!closed)
            {
                /*
                * Prepare the message
                */
                this.closed = true;

                if (alertLevel == AlertLevel.fatal)
                {
                    /*
                    * This is a fatal message.
                    */
                    this.failedWithError = true;
                }
                SendAlert(alertLevel, alertDescription);
                rs.Close();
                if (alertLevel == AlertLevel.fatal)
                {
                    throw new IOException(TLS_ERROR_MESSAGE);
                }
            }
            else
            {
                throw new IOException(TLS_ERROR_MESSAGE);
            }
        }

        internal void SendAlert(byte alertLevel, byte alertDescription)
        {
            byte[] error = new byte[] { alertLevel, alertDescription };

            rs.WriteMessage(ContentType.alert, error, 0, 2);
        }

        /// <summary>Closes this connection</summary>
        /// <exception cref="IOException">If something goes wrong during closing.</exception>
        public virtual void Close()
        {
            HandleClose(true);
        }

        protected virtual void HandleClose(bool user_canceled)
        {
            if (!closed)
            {
                if (user_canceled && !appDataReady)
                {
                    SendAlert(AlertLevel.warning, AlertDescription.user_canceled);
                }
                this.FailWithError(AlertLevel.warning, AlertDescription.close_notify);
            }
        }

        /**
        * Make sure the Stream is now empty. Fail otherwise.
        *
        * @param is The Stream to check.
        * @throws IOException If is is not empty.
        */
        protected internal static void AssertEmpty(
            MemoryStream inStr)
        {
            if (inStr.Position < inStr.Length)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }
        }

        protected static byte[] CreateRandomBlock(bool useGMTUnixTime, SecureRandom random, string asciiLabel)
        {
            /*
             * We use the TLS 1.0 PRF on the SecureRandom output, to guard against RNGs where the raw
             * output could be used to recover the internal state.
             */
            byte[] secret = new byte[32];
            random.NextBytes(secret);

            byte[] seed = new byte[8];
            // TODO Use high-resolution timer
            TlsUtilities.WriteUint64(DateTimeUtilities.CurrentUnixMs(), seed, 0);

            byte[] result = TlsUtilities.PRF(secret, asciiLabel, seed, 32);

            if (useGMTUnixTime)
            {
                TlsUtilities.WriteGmtUnixTime(result, 0);
            }

            return result;
        }

        internal void Flush()
        {
            rs.Flush();
        }

        internal bool IsClosed
        {
            get { return closed; }
        }

        private static bool ArrayContains(byte[] a, byte n)
        {
            for (int i = 0; i < a.Length; ++i)
            {
                if (a[i] == n)
                    return true;
            }
            return false;
        }

        private static bool ArrayContains(int[] a, int n)
        {
            for (int i = 0; i < a.Length; ++i)
            {
                if (a[i] == n)
                    return true;
            }
            return false;
        }

        private static byte[] CreateRenegotiationInfo(byte[] renegotiated_connection)
        {
            MemoryStream buf = new MemoryStream();
            TlsUtilities.WriteOpaque8(renegotiated_connection, buf);
            return buf.ToArray();
        }

        private static void WriteExtension(Stream output, int extType, byte[] extValue)
        {
            TlsUtilities.WriteUint16(extType, output);
            TlsUtilities.WriteOpaque16(extValue, output);
        }
    }
}