forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTlsClientStream.cs
More file actions
2157 lines (1921 loc) · 95.7 KB
/
TlsClientStream.cs
File metadata and controls
2157 lines (1921 loc) · 95.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if !DNXCORE50
#region License
// The PostgreSQL License
//
// Copyright (C) 2015 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
#undef CHECK_ARGUMENTS
//using AsyncRewriter;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TlsClientStream
{
internal partial class TlsClientStream : Stream
{
const TlsVersion HighestTlsVersionSupported = TlsVersion.TLSv1_2;
const int MaxEncryptedRecordLen = (1 << 14) /* data */ + 16 + 64 + 256 /* iv + mac + padding (accept long CBC mode padding) */;
// Buffer data
byte[] _buf = new byte[5 /* header */ + MaxEncryptedRecordLen];
int _readStart;
int _readEnd;
int _packetLen;
Stream _baseStream;
// Connection states
// Read connection state is for the purpose when we have sent ChangeCipherSpec but the server hasn't yet
ConnectionState _connState;
ConnectionState _readConnState;
ConnectionState _pendingConnState;
RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
// Info about the current message in the buffer
ContentType _contentType;
int _plaintextLen;
int _plaintextStart;
// Temp buffer to hold sequence number
byte[] _tempBuf8 = new byte[8];
// Temp buffer for GCM
byte[] _temp512;
// Holds buffered handshake messages that will be dequeued as soon as a proper final message has been received (ServerHelloDone or Finished)
HandshakeMessagesBuffer _handshakeMessagesBuffer = new HandshakeMessagesBuffer();
HandshakeData _handshakeData;
// User parameters
bool _noRenegotiationExtensionSupportIsFatal = false;
string _hostName = null;
X509CertificateCollection _clientCertificates;
System.Net.Security.RemoteCertificateValidationCallback _remoteCertificationValidationCallback;
bool _checkCertificateRevocation;
bool _waitingForChangeCipherSpec;
bool _waitingForFinished;
// When renegotiating we use another buffer to avoid overwriting the normal one
byte[] _renegotiationTempWriteBuf;
// Used in Read and Write methods to keep track of position
int _writePos;
int _decryptedReadPos;
int _decryptedReadEnd;
// When we write in the middle of a handshake, we must block until the handshake is completed before
// we can actually write the data, due to a bug in OpenSSL. If we at the same time receive data from
// the server, we must buffer it so it can be delivered to the application later.
// Note that this is quite uncommon, since one normally drains the read buffer before writing.
const int MaxBufferedReadData = 10 * (1 << 20); // 10 MB
Queue<byte[]> _bufferedReadData;
int _posBufferedReadData;
int _lenBufferedReadData;
// Stream state
bool _eof;
bool _closed;
/// <summary>
/// Creates a new TlsClientStream with the given underlying stream.
/// The handshake must be manually initiated with the method PerformInitialHandshake.
/// </summary>
/// <param name="baseStream">Base stream</param>
public TlsClientStream(Stream baseStream)
{
_connState = new ConnectionState() { TlsVersion = TlsVersion.TLSv1_0 };
_readConnState = _connState;
_baseStream = baseStream;
}
#region Record layer
/// <summary>
/// Makes sure there is at least one full record available at _readStart.
/// Also sets _packetLen (does not include packet header of 5 bytes).
/// </summary>
/// <returns>True on success, false on End Of Stream.</returns>
//[RewriteAsync]
bool ReadRecord()
{
int packetLength = -1;
while (true)
{
if (packetLength == -1 && _readEnd - _readStart >= 5)
{
// We have at least a header in our buffer, so extract the length
packetLength = (_buf[_readStart + 3] << 8) | _buf[_readStart + 4];
if (packetLength > MaxEncryptedRecordLen)
{
SendAlertFatal(AlertDescription.RecordOverflow);
}
}
if (packetLength != -1 && 5 + packetLength <= _readEnd - _readStart)
{
// The whole record fits in the buffer. We are done.
_packetLen = packetLength;
return true;
}
if (_readEnd - _readStart > 0 && _readStart > 0)
{
// We only have a partial record in the buffer,
// move that to the beginning to be able to read as much as possible from the network.
Buffer.BlockCopy(_buf, _readStart, _buf, 0, _readEnd - _readStart);
_readEnd -= _readStart;
_readStart = 0;
}
if (packetLength == -1 || _readEnd < 5 + packetLength)
{
if (_readStart == _readEnd)
{
// The read buffer is empty, so start reading at the start of the buffer
_readStart = 0;
_readEnd = 0;
}
int read = _baseStream.Read(_buf, _readEnd, _buf.Length - _readEnd);
if (read == 0)
{
return false;
}
_readEnd += read;
}
}
}
// ReadRecord should be called first.
// Sets _contentType, _plaintextStart and _plaintextLength, and increments _readStart
void Decrypt()
{
_contentType = (ContentType)_buf[_readStart];
if (_readConnState.CipherSuite == null)
{
_plaintextStart = _readStart + 5;
_plaintextLen = _packetLen;
}
else if (_readConnState.CipherSuite.AesMode == AesMode.CBC)
{
var minPlaintextBytes = _readConnState.MacLen + 1;
var minEncryptedBlocks = (minPlaintextBytes + _readConnState.BlockLen - 1) / _readConnState.BlockLen;
var minEncryptedBytes = minEncryptedBlocks * _readConnState.BlockLen;
if (_packetLen < _readConnState.IvLen + minEncryptedBytes || (_packetLen - _readConnState.IvLen) % _readConnState.BlockLen != 0)
SendAlertFatal(AlertDescription.BadRecordMac);
Buffer.BlockCopy(_buf, _readStart + 5, _readConnState.ReadIv, 0, _readConnState.IvLen);
_readConnState.ReadAes.IV = _readConnState.ReadIv;
int cipherStartPos = _readStart + 5 + _readConnState.IvLen;
int cipherLen = _packetLen - _readConnState.IvLen;
if (_readConnState.TlsVersion == TlsVersion.TLSv1_0)
{
// Save the last ciphertext block to become the IV for the next record
Buffer.BlockCopy(_buf, cipherStartPos + cipherLen - _readConnState.BlockLen, _readConnState.ReadIv, 0, _readConnState.BlockLen);
}
using (var decryptor = _readConnState.ReadAes.CreateDecryptor())
{
decryptor.TransformBlock(_buf, cipherStartPos, cipherLen, _buf, cipherStartPos);
}
int paddingLen = _buf[cipherStartPos + cipherLen - 1];
bool paddingFail = false;
if (paddingLen > cipherLen - 1 - _readConnState.MacLen)
{
// We have found illegal padding. Instead of just send fatal alert directly,
// still do the mac computation and let it fail to deal with timing attacks.
paddingLen = 0;
paddingFail = true;
}
int plaintextLen = cipherLen - 1 - paddingLen - _readConnState.MacLen;
// We don't need the IV anymore in the buffer, so overwrite it with seq_num + header to calculate MAC
/*Buffer.BlockCopy(_buf, _readStart, _buf, cipherStartPos - 5, 3);
Utils.WriteUInt16(_buf, cipherStartPos - 2, (ushort)plaintextLen);
Utils.WriteUInt64(_buf, cipherStartPos - 5 - 8, _readConnState.ReadSeqNum);*/
// We should use the plaintext len, not the encrypted len for the MAC
_readConnState.ReadMac.Initialize();
Utils.WriteUInt64(_tempBuf8, 0, _readConnState.ReadSeqNum);
_readConnState.ReadMac.TransformBlock(_tempBuf8, 0, 8);
Utils.WriteUInt16(_buf, _readStart + 3, (ushort)plaintextLen);
_readConnState.ReadMac.TransformBlock(_buf, _readStart, 5);
_readConnState.ReadMac.TransformBlock(_buf, cipherStartPos, plaintextLen);
_readConnState.ReadMac.TransformFinalBlock(_tempBuf8, 0, 0);
var hmac = _readConnState.ReadMac.Hash;
if (!Utils.ArraysEqual(hmac, 0, _buf, cipherStartPos + plaintextLen, hmac.Length))
SendAlertFatal(AlertDescription.BadRecordMac);
// Verify that the padding bytes contain the correct value (paddingLen)
for (int i = 0; i < paddingLen; i++)
if (_buf[cipherStartPos + cipherLen - 2 - i] != paddingLen)
SendAlertFatal(AlertDescription.BadRecordMac);
// Very unlikely MAC didn't catch this
if (paddingFail)
SendAlertFatal(AlertDescription.BadRecordMac);
_plaintextStart = cipherStartPos;
_plaintextLen = plaintextLen;
}
else if (_readConnState.CipherSuite.AesMode == AesMode.GCM)
{
Buffer.BlockCopy(_buf, _readStart + 5, _readConnState.ReadIv, 4, _readConnState.IvLen);
var cipherStartPos = _readStart + 5 + _readConnState.IvLen;
var plaintextLen = _packetLen - 16 - _readConnState.IvLen;
if (plaintextLen < 0)
SendAlertFatal(AlertDescription.BadRecordMac);
var ok = GaloisCounterMode.GCMAD(_readConnState.ReadAesECB, _readConnState.ReadIv, _buf, cipherStartPos, plaintextLen, _readConnState.ReadSeqNum, (byte)_contentType, _readConnState.ReadGCMTable, _temp512);
if (!ok)
SendAlertFatal(AlertDescription.BadRecordMac);
_plaintextStart = cipherStartPos;
_plaintextLen = plaintextLen;
}
_readStart += 5 + _packetLen;
_readConnState.ReadSeqNum++;
}
// startPos: at content type, len: plaintext length without header
// updates seq num
/// <summary>
/// Encrypts a record.
/// A header should be at startPos containing TLS record type and version.
/// At startPos + 5 + ivLen the plaintext should start.
/// </summary>
/// <param name="startPos">Should point to the beginning of the record (content type)</param>
/// <param name="len">Plaintext length (without header)</param>
/// <returns>The byte position after the last byte in this encrypted record</returns>
int Encrypt(int startPos, int len)
{
if (_connState.CipherSuite != null && _connState.CipherSuite.AesMode == AesMode.CBC)
{
// Update length first with plaintext length
Utils.WriteUInt16(_buf, startPos + 3, (ushort)len);
Utils.WriteUInt64(_tempBuf8, 0, _connState.WriteSeqNum++);
_connState.WriteMac.Initialize();
_connState.WriteMac.TransformBlock(_tempBuf8, 0, 8);
_connState.WriteMac.TransformBlock(_buf, startPos, 5);
_connState.WriteMac.TransformBlock(_buf, startPos + 5 + _connState.IvLen, len);
_connState.WriteMac.TransformFinalBlock(_buf, 0, 0);
var mac = _connState.WriteMac.Hash;
Buffer.BlockCopy(mac, 0, _buf, startPos + 5 + _connState.IvLen + len, mac.Length);
Utils.ClearArray(mac);
var paddingLen = _connState.BlockLen - (len + _connState.MacLen + 1) % _connState.BlockLen;
for (var i = 0; i < paddingLen + 1; i++)
_buf[startPos + 5 + _connState.IvLen + len + _connState.MacLen + i] = (byte)paddingLen;
int encryptedLen = len + _connState.MacLen + paddingLen + 1;
// Update length now with encrypted length
Utils.WriteUInt16(_buf, startPos + 3, (ushort)(_connState.IvLen + encryptedLen));
if (_connState.TlsVersion != TlsVersion.TLSv1_0)
{
_rng.GetBytes(_connState.WriteIv);
Buffer.BlockCopy(_connState.WriteIv, 0, _buf, startPos + 5, _connState.WriteIv.Length);
}
_connState.WriteAes.IV = _connState.WriteIv;
using (var encryptor = _connState.WriteAes.CreateEncryptor())
{
encryptor.TransformBlock(_buf, startPos + 5 + _connState.IvLen, encryptedLen, _buf, startPos + 5 + _connState.IvLen);
}
if (_connState.TlsVersion == TlsVersion.TLSv1_0)
{
// Save last ciphertext block as the next IV
Buffer.BlockCopy(_buf, startPos + 5 + encryptedLen - _connState.BlockLen, _connState.WriteIv, 0, _connState.BlockLen);
}
return startPos + 5 + _connState.IvLen + encryptedLen;
}
else if (_connState.CipherSuite != null && _connState.CipherSuite.AesMode == AesMode.GCM)
{
Utils.WriteUInt64(_connState.WriteIv, 4, _connState.WriteSeqNum);
Utils.WriteUInt64(_buf, startPos + 5, _connState.WriteSeqNum);
GaloisCounterMode.GCMAE(_connState.WriteAesECB, _connState.WriteIv, _buf, startPos + 5 + _connState.IvLen, len, _connState.WriteSeqNum++, _buf[startPos], _connState.WriteGCMTable, _temp512);
Utils.WriteUInt16(_buf, startPos + 3, (ushort)(_connState.IvLen + len + 16));
return startPos + 5 + _connState.IvLen + len + 16;
}
else // Null cipher
{
// Update length
Utils.WriteUInt16(_buf, startPos + 3, (ushort)len);
return startPos + 5 + len;
}
}
#endregion
#region Handshake infrastructure
void UpdateHandshakeHash(byte[] buf, int offset, int len)
{
// .NET hash api does not allow us to clone hash states ...
if (_handshakeData.HandshakeHash1 != null)
_handshakeData.HandshakeHash1.TransformBlock(buf, offset, len);
if (_handshakeData.HandshakeHash1_384 != null)
_handshakeData.HandshakeHash1_384.TransformBlock(buf, offset, len);
if (_handshakeData.HandshakeHash2 != null)
_handshakeData.HandshakeHash2.TransformBlock(buf, offset, len);
if (_handshakeData.HandshakeHash2_384 != null)
_handshakeData.HandshakeHash2_384.TransformBlock(buf, offset, len);
if (_handshakeData.HandshakeHash1_MD5SHA1 != null)
_handshakeData.HandshakeHash1_MD5SHA1.TransformBlock(buf, offset, len);
if (_handshakeData.HandshakeHash2_MD5SHA1 != null)
_handshakeData.HandshakeHash2_MD5SHA1.TransformBlock(buf, offset, len);
if (_handshakeData.CertificateVerifyHash_MD5 != null)
_handshakeData.CertificateVerifyHash_MD5.TransformBlock(buf, offset, len);
if (_handshakeData.CertificateVerifyHash_SHA1 != null)
_handshakeData.CertificateVerifyHash_SHA1.TransformBlock(buf, offset, len);
}
//[RewriteAsync]
void GetInitialHandshakeMessages(bool allowApplicationData = false)
{
while (!_handshakeMessagesBuffer.HasServerHelloDone)
{
if (!ReadRecord())
throw new IOException("Connection EOF in initial handshake");
Decrypt();
switch (_contentType)
{
case ContentType.Alert:
HandleAlertMessage();
break;
case ContentType.Handshake:
_handshakeMessagesBuffer.AddBytes(_buf, _plaintextStart, _plaintextLen, HandshakeMessagesBuffer.IgnoreHelloRequestsSettings.IgnoreHelloRequests);
if (_handshakeMessagesBuffer.Messages.Count > 5)
{
// There can never be more than 5 handshake messages in a handshake
SendAlertFatal(AlertDescription.UnexpectedMessage);
}
break;
case ContentType.ApplicationData:
EnqueueReadData(allowApplicationData);
break;
default:
SendAlertFatal(AlertDescription.UnexpectedMessage);
break;
}
}
var responseLen = TraverseHandshakeMessages();
_baseStream.Write(_buf, 0, responseLen);
_baseStream.Flush();
ResetWritePos();
_waitingForChangeCipherSpec = true;
}
int TraverseHandshakeMessages()
{
HandshakeType lastType = 0;
int responseLen = 0;
for (var i = 0; i < _handshakeMessagesBuffer.Messages.Count; i++)
{
int pos = 0;
var buf = _handshakeMessagesBuffer.Messages[i];
UpdateHandshakeHash(buf, 0, buf.Length);
HandshakeType msgType = (HandshakeType)buf[pos++];
int msgLen = Utils.ReadUInt24(buf, ref pos);
switch (msgType)
{
case HandshakeType.ServerHello:
if (lastType != 0)
SendAlertFatal(AlertDescription.UnexpectedMessage);
ParseServerHelloMessage(buf, ref pos, pos + msgLen);
break;
case HandshakeType.Certificate:
if (lastType != HandshakeType.ServerHello)
SendAlertFatal(AlertDescription.UnexpectedMessage);
ParseCertificateMessage(buf, ref pos);
break;
case HandshakeType.ServerKeyExchange:
if (lastType != HandshakeType.Certificate)
SendAlertFatal(AlertDescription.UnexpectedMessage);
ParseServerKeyExchangeMessage(buf, ref pos);
break;
case HandshakeType.CertificateRequest:
if (lastType != HandshakeType.Certificate && lastType != HandshakeType.ServerKeyExchange)
SendAlertFatal(AlertDescription.UnexpectedMessage);
ParseCertificateRequest(buf, ref pos);
break;
case HandshakeType.ServerHelloDone:
if (msgLen != 0)
SendAlertFatal(AlertDescription.DecodeError);
if ((lastType != HandshakeType.Certificate && lastType != HandshakeType.ServerKeyExchange && lastType != HandshakeType.CertificateRequest)
|| i != _handshakeMessagesBuffer.Messages.Count - 1)
SendAlertFatal(AlertDescription.UnexpectedMessage);
responseLen = GenerateHandshakeResponse();
break;
default:
SendAlertFatal(AlertDescription.UnexpectedMessage);
break;
}
if (pos != 4 + msgLen)
SendAlertFatal(AlertDescription.DecodeError);
lastType = msgType;
}
_handshakeMessagesBuffer.ClearMessages();
return responseLen;
}
// Here we send all client messages in response to server hello
int GenerateHandshakeResponse()
{
int offset = 0;
var ivLen = _connState.IvLen;
if (_handshakeData.CertificateTypes != null) // Certificate request has been sent by the server
{
SendHandshakeMessage(SendClientCertificate, ref offset, ivLen);
}
switch (_pendingConnState.CipherSuite.KeyExchange)
{
case KeyExchange.DHE_RSA:
case KeyExchange.DHE_DSS:
SendHandshakeMessage(SendClientKeyExchangeDhe, ref offset, ivLen);
break;
case KeyExchange.ECDHE_RSA:
case KeyExchange.ECDHE_ECDSA:
SendHandshakeMessage(SendClientKeyExchangeEcdhe, ref offset, ivLen);
break;
case KeyExchange.ECDH_ECDSA:
case KeyExchange.ECDH_RSA:
SendHandshakeMessage(SendClientKeyExchangeEcdh, ref offset, ivLen);
break;
case KeyExchange.RSA:
SendHandshakeMessage(SendClientKeyExchangeRsa, ref offset, ivLen);
break;
default:
throw new InvalidOperationException();
}
if (_handshakeData.CertificateTypes != null && _handshakeData.SelectedClientCertificate != null)
{
SendHandshakeMessage(SendCertificateVerify, ref offset, ivLen);
}
var cipherSpecStart = offset;
SendChangeCipherSpec(ref offset, ivLen);
offset = Encrypt(cipherSpecStart, 1);
// Key generation from Master Secret
var mode = _pendingConnState.CipherSuite.AesMode;
var isCbc = mode == AesMode.CBC;
var isGcm = mode == AesMode.GCM;
var concRandom = new byte[_pendingConnState.ServerRandom.Length + _pendingConnState.ClientRandom.Length];
Buffer.BlockCopy(_pendingConnState.ServerRandom, 0, concRandom, 0, _pendingConnState.ServerRandom.Length);
Buffer.BlockCopy(_pendingConnState.ClientRandom, 0, concRandom, _pendingConnState.ServerRandom.Length, _pendingConnState.ClientRandom.Length);
var macLen = isCbc ? _pendingConnState.CipherSuite.MACLen / 8 : 0;
var aesKeyLen = _pendingConnState.CipherSuite.AesKeyLen / 8;
var IVLen = isGcm ? 4 : _pendingConnState.TlsVersion != TlsVersion.TLSv1_0 ? 0 : _pendingConnState.BlockLen;
var keyBlock = Utils.PRF(_pendingConnState.PRFAlgorithm, _pendingConnState.MasterSecret, "key expansion", concRandom, macLen * 2 + aesKeyLen * 2 + IVLen * 2);
byte[] writeMac = new byte[macLen], readMac = new byte[macLen], writeKey = new byte[aesKeyLen], readKey = new byte[aesKeyLen];
Buffer.BlockCopy(keyBlock, 0, writeMac, 0, macLen);
Buffer.BlockCopy(keyBlock, macLen, readMac, 0, macLen);
Buffer.BlockCopy(keyBlock, macLen * 2, writeKey, 0, aesKeyLen);
Buffer.BlockCopy(keyBlock, macLen * 2 + aesKeyLen, readKey, 0, aesKeyLen);
if (isCbc)
{
_pendingConnState.WriteMac = _pendingConnState.CipherSuite.CreateHMAC(writeMac);
_pendingConnState.ReadMac = _pendingConnState.CipherSuite.CreateHMAC(readMac);
}
if (IVLen != 0)
{
// For GCM we make it bigger to later fill in sequence numbers
var writeIv = new byte[isGcm ? 16 : IVLen];
var readIv = new byte[isGcm ? 16 : IVLen];
Buffer.BlockCopy(keyBlock, macLen * 2 + aesKeyLen * 2, writeIv, 0, IVLen);
Buffer.BlockCopy(keyBlock, macLen * 2 + aesKeyLen * 2 + IVLen, readIv, 0, IVLen);
_pendingConnState.WriteIv = writeIv;
_pendingConnState.ReadIv = readIv;
}
else
{
_pendingConnState.ReadIv = _pendingConnState.WriteIv = new byte[_pendingConnState.BlockLen];
}
_pendingConnState.WriteAes = new AesCryptoServiceProvider() { Key = writeKey, Mode = isCbc ? CipherMode.CBC : CipherMode.ECB, Padding = PaddingMode.None };
_pendingConnState.ReadAes = new AesCryptoServiceProvider() { Key = readKey, Mode = isCbc ? CipherMode.CBC : CipherMode.ECB, Padding = PaddingMode.None };
// int tmpOffset = macLen * 2 + aesKeyLen * 2;
if (isGcm)
{
_pendingConnState.WriteAesECB = _pendingConnState.WriteAes.CreateEncryptor(writeKey, null);
_pendingConnState.ReadAesECB = _pendingConnState.ReadAes.CreateEncryptor(readKey, null);
_pendingConnState.WriteGCMTable = GaloisCounterMode.GetH(_pendingConnState.WriteAesECB);
_pendingConnState.ReadGCMTable = GaloisCounterMode.GetH(_pendingConnState.ReadAesECB);
if (_temp512 == null)
_temp512 = new byte[512];
}
Utils.ClearArray(writeMac);
Utils.ClearArray(readMac);
Utils.ClearArray(writeKey);
Utils.ClearArray(readKey);
ivLen = _pendingConnState.IvLen;
_connState = _pendingConnState;
SendHandshakeMessage(SendFinished, ref offset, ivLen);
_handshakeData.HandshakeHash2.TransformFinalBlock(_buf, 0, 0);
// _buf is now ready to be written to the base stream, from pos 0 to offset
return offset;
}
delegate HandshakeType SendHandshakeMessageDelegate(ref int offset);
void SendHandshakeMessage(SendHandshakeMessageDelegate func, ref int offset, int ivLen)
{
int start = offset;
int messageStart = start + 5 + ivLen;
_buf[offset++] = (byte)ContentType.Handshake;
// Highest version supported
offset += Utils.WriteUInt16(_buf, offset, (ushort)_connState.TlsVersion);
// Record length to be filled in later
offset += 2;
offset += ivLen;
int handshakeTypePos = offset;
// Type and length filled in below
offset += 4;
var handshakeType = func(ref offset);
var messageLen = offset - (handshakeTypePos + 4);
_buf[handshakeTypePos] = (byte)handshakeType;
Utils.WriteUInt24(_buf, handshakeTypePos + 1, messageLen);
UpdateHandshakeHash(_buf, messageStart, offset - messageStart);
offset = Encrypt(start, offset - messageStart);
}
//[RewriteAsync]
void WaitForHandshakeCompleted(bool initialHandshake)
{
for (; ; )
{
if (!ReadRecord())
{
_eof = true;
throw new IOException("Unexpected connection EOF in handshake");
}
Decrypt();
if (_contentType != ContentType.ChangeCipherSpec)
{
EnqueueReadData(!initialHandshake);
}
else
{
ParseChangeCipherSpec();
_waitingForChangeCipherSpec = false;
break;
}
}
while (_handshakeMessagesBuffer.Messages.Count == 0)
{
if (!ReadRecord())
{
_eof = true;
throw new IOException("Unexpected connection EOF in handshake");
}
Decrypt();
if (_contentType != ContentType.Handshake)
{
EnqueueReadData(!initialHandshake);
}
else
{
_handshakeMessagesBuffer.AddBytes(_buf, _plaintextStart, _plaintextLen, HandshakeMessagesBuffer.IgnoreHelloRequestsSettings.IgnoreHelloRequestsUntilFinished);
}
}
if ((HandshakeType)_handshakeMessagesBuffer.Messages[0][0] == HandshakeType.Finished)
{
ParseFinishedMessage(_handshakeMessagesBuffer.Messages[0]);
_handshakeMessagesBuffer.RemoveFirst(); // Leave possible hello requests after this position
}
else
{
SendAlertFatal(AlertDescription.UnexpectedMessage);
}
}
#endregion
#region Handshake messages
HandshakeType SendClientHello(ref int offset)
{
_pendingConnState = new ConnectionState();
_handshakeData = new HandshakeData();
_handshakeData.HandshakeHash1 = new SHA256CryptoServiceProvider();
_handshakeData.HandshakeHash2 = new SHA256CryptoServiceProvider();
_handshakeData.HandshakeHash1_384 = new SHA384CryptoServiceProvider();
_handshakeData.HandshakeHash2_384 = new SHA384CryptoServiceProvider();
_handshakeData.HandshakeHash1_MD5SHA1 = new MD5SHA1();
_handshakeData.HandshakeHash2_MD5SHA1 = new MD5SHA1();
_handshakeData.CertificateVerifyHash_MD5 = new MD5CryptoServiceProvider();
_handshakeData.CertificateVerifyHash_SHA1 = new SHA1CryptoServiceProvider();
// Highest version supported
offset += Utils.WriteUInt16(_buf, offset, (ushort)HighestTlsVersionSupported);
// Client random
var timestamp = (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
_pendingConnState.ClientRandom = new byte[32];
_rng.GetBytes(_pendingConnState.ClientRandom);
Utils.WriteUInt32(_pendingConnState.ClientRandom, 0, timestamp);
Buffer.BlockCopy(_pendingConnState.ClientRandom, 0, _buf, offset, 32);
offset += 32;
// No session id
_buf[offset++] = 0;
// Cipher suites
var supportedCipherSuites = CipherSuiteInfo.Supported;
/*
if (HighestTlsVersionSupported != TlsVersion.TLSv1_2)
supportedCipherSuites = supportedCipherSuites.Where(cs => cs.IsAllowedBefore1_2).ToArray();
*/
offset += Utils.WriteUInt16(_buf, offset, (ushort)(supportedCipherSuites.Length * sizeof(ushort)));
foreach (var suite in supportedCipherSuites)
{
offset += Utils.WriteUInt16(_buf, offset, (ushort)suite.Id);
}
// Compression methods
_buf[offset++] = 1; // Length
_buf[offset++] = 0; // "null" compression method
// Extensions length, fill in later
var extensionLengthOffset = offset;
offset += 2;
// Renegotiation extension
offset += Utils.WriteUInt16(_buf, offset, (ushort)ExtensionType.RenegotiationInfo);
if (_connState.SecureRenegotiation)
{
// Extension length
offset += Utils.WriteUInt16(_buf, offset, 13);
// Renegotiated connection length
_buf[offset++] = 12;
// Renegotiated connection data
Buffer.BlockCopy(_connState.ClientVerifyData, 0, _buf, offset, 12);
offset += 12;
}
else
{
// Extension length
offset += Utils.WriteUInt16(_buf, offset, 1);
// Renegotiated connection length
_buf[offset++] = 0;
}
// SNI extension
if (_hostName != null)
{
// TODO: IDN Unicode -> Punycode
// NOTE: IP addresses should not use SNI extension, per specification.
System.Net.IPAddress ip;
if (!System.Net.IPAddress.TryParse(_hostName, out ip))
{
offset += Utils.WriteUInt16(_buf, offset, (ushort)ExtensionType.ServerName);
var byteLen = Encoding.ASCII.GetBytes(_hostName, 0, _hostName.Length, _buf, offset + 7);
offset += Utils.WriteUInt16(_buf, offset, (ushort)(5 + byteLen));
offset += Utils.WriteUInt16(_buf, offset, (ushort)(3 + byteLen));
_buf[offset++] = 0; // host_name
offset += Utils.WriteUInt16(_buf, offset, (ushort)byteLen);
offset += byteLen;
}
}
if (HighestTlsVersionSupported == TlsVersion.TLSv1_2)
{
// Signature algorithms extension. At least IIS 7.5 needs this or it immediately resets the connection.
// Used to specify what kind of server certificate hash/signature algorithms we can use to verify it.
offset += Utils.WriteUInt16(_buf, offset, (ushort)ExtensionType.SignatureAlgorithms);
offset += Utils.WriteUInt16(_buf, offset, 20);
offset += Utils.WriteUInt16(_buf, offset, 18);
_buf[offset++] = (byte)TLSHashAlgorithm.SHA1;
_buf[offset++] = (byte)SignatureAlgorithm.ECDSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA256;
_buf[offset++] = (byte)SignatureAlgorithm.ECDSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA384;
_buf[offset++] = (byte)SignatureAlgorithm.ECDSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA512;
_buf[offset++] = (byte)SignatureAlgorithm.ECDSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA1;
_buf[offset++] = (byte)SignatureAlgorithm.RSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA256;
_buf[offset++] = (byte)SignatureAlgorithm.RSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA384;
_buf[offset++] = (byte)SignatureAlgorithm.RSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA512;
_buf[offset++] = (byte)SignatureAlgorithm.RSA;
_buf[offset++] = (byte)TLSHashAlgorithm.SHA1;
_buf[offset++] = (byte)SignatureAlgorithm.DSA;
}
if (supportedCipherSuites.Any(s => s.KeyExchange == KeyExchange.ECDHE_RSA || s.KeyExchange == KeyExchange.ECDHE_ECDSA))
{
// Supported Elliptic Curves Extension
offset += Utils.WriteUInt16(_buf, offset, (ushort)ExtensionType.SupportedEllipticCurves);
offset += Utils.WriteUInt16(_buf, offset, 8);
offset += Utils.WriteUInt16(_buf, offset, 6);
offset += Utils.WriteUInt16(_buf, offset, (ushort)NamedCurve.secp256r1);
offset += Utils.WriteUInt16(_buf, offset, (ushort)NamedCurve.secp384r1);
offset += Utils.WriteUInt16(_buf, offset, (ushort)NamedCurve.secp521r1);
// Supported Point Formats Extension
offset += Utils.WriteUInt16(_buf, offset, (ushort)ExtensionType.SupportedPointFormats);
offset += Utils.WriteUInt16(_buf, offset, 2);
_buf[offset++] = 1; // Length
_buf[offset++] = 0; // Uncompressed
}
Utils.WriteUInt16(_buf, extensionLengthOffset, (ushort)(offset - (extensionLengthOffset + 2)));
return HandshakeType.ClientHello;
}
void ParseServerHelloMessage(byte[] buf, ref int pos, int endPos)
{
var renegotiating = _connState.ReadAes != null;
var version = (TlsVersion)Utils.ReadUInt16(buf, ref pos);
if (version < TlsVersion.TLSv1_0 || version > TlsVersion.TLSv1_2)
{
SendAlertFatal(AlertDescription.ProtocolVersion);
}
_connState.TlsVersion = version;
_pendingConnState.TlsVersion = version;
_pendingConnState.ServerRandom = new byte[32];
Buffer.BlockCopy(buf, pos, _pendingConnState.ServerRandom, 0, 32);
pos += 32;
// Skip session id
var sessionIDLength = buf[pos++];
pos += sessionIDLength;
var cipherSuite = (CipherSuite)Utils.ReadUInt16(buf, ref pos);
var compressionMethod = buf[pos++];
_pendingConnState.CipherSuite = CipherSuiteInfo.Supported.FirstOrDefault(s => s.Id == cipherSuite);
if (_pendingConnState.CipherSuite == null || !_pendingConnState.CipherSuite.IsAllowedBefore1_2 && version != TlsVersion.TLSv1_2 || compressionMethod != 0)
{
SendAlertFatal(AlertDescription.IllegalParameter);
}
if (_pendingConnState.TlsVersion == TlsVersion.TLSv1_2)
{
switch (_pendingConnState.CipherSuite.PRFAlgorithm)
{
case PRFAlgorithm.TLSPrfSHA256:
_handshakeData.HandshakeHash1_384.Clear();
_handshakeData.HandshakeHash1_384 = null;
_handshakeData.HandshakeHash2_384.Clear();
_handshakeData.HandshakeHash2_384 = null;
break;
case PRFAlgorithm.TLSPrfSHA384:
_handshakeData.HandshakeHash1.Clear();
_handshakeData.HandshakeHash1 = _handshakeData.HandshakeHash1_384;
_handshakeData.HandshakeHash1_384 = null;
_handshakeData.HandshakeHash2.Clear();
_handshakeData.HandshakeHash2 = _handshakeData.HandshakeHash2_384;
_handshakeData.HandshakeHash2_384 = null;
break;
default:
throw new InvalidOperationException();
}
_handshakeData.HandshakeHash1_MD5SHA1.Clear();
_handshakeData.HandshakeHash1_MD5SHA1 = null;
_handshakeData.HandshakeHash2_MD5SHA1.Clear();
_handshakeData.HandshakeHash2_MD5SHA1 = null;
_handshakeData.CertificateVerifyHash_MD5.Clear();
_handshakeData.CertificateVerifyHash_MD5 = null;
}
else
{
_handshakeData.HandshakeHash1.Clear();
_handshakeData.HandshakeHash1 = null;
_handshakeData.HandshakeHash2.Clear();
_handshakeData.HandshakeHash2 = null;
_handshakeData.HandshakeHash1_384.Clear();
_handshakeData.HandshakeHash1_384 = null;
_handshakeData.HandshakeHash2_384.Clear();
_handshakeData.HandshakeHash2_384 = null;
_handshakeData.HandshakeHash1 = _handshakeData.HandshakeHash1_MD5SHA1;
_handshakeData.HandshakeHash1_MD5SHA1 = null;
_handshakeData.HandshakeHash2 = _handshakeData.HandshakeHash2_MD5SHA1;
_handshakeData.HandshakeHash2_MD5SHA1 = null;
}
// If no extensions present, return
if (pos == endPos)
return;
var processedRenegotiationInfo = false;
var extensionLength = Utils.ReadUInt16(buf, ref pos);
var extensionsEnd = pos + extensionLength;
while (pos < extensionsEnd)
{
var extensionId = (ExtensionType)Utils.ReadUInt16(buf, ref pos);
switch (extensionId)
{
case ExtensionType.RenegotiationInfo:
if (processedRenegotiationInfo)
SendAlertFatal(AlertDescription.HandshakeFailure);
processedRenegotiationInfo = true;
var lengthFull = Utils.ReadUInt16(buf, ref pos);
var length = buf[pos++];
if (length + 1 != lengthFull)
SendAlertFatal(AlertDescription.HandshakeFailure);
if (!renegotiating)
{
if (length != 0)
SendAlertFatal(AlertDescription.HandshakeFailure);
}
if (renegotiating)
{
if (!_connState.SecureRenegotiation)
SendAlertFatal(AlertDescription.HandshakeFailure);
if (length != 24)
SendAlertFatal(AlertDescription.HandshakeFailure);
for (var j = 0; j < 12; j++)
{
if (_connState.ClientVerifyData[j] != buf[pos++])
SendAlertFatal(AlertDescription.HandshakeFailure);
}
for (var j = 0; j < 12; j++)
{
if (_connState.ServerVerifyData[j] != buf[pos++])
SendAlertFatal(AlertDescription.HandshakeFailure);
}
}
_pendingConnState.SecureRenegotiation = true;
break;
case ExtensionType.SupportedEllipticCurves:
var len = Utils.ReadUInt16(buf, ref pos);
// Contains in what formats the server can parse. Ignore it.
pos += len;
break;
case ExtensionType.SupportedPointFormats:
var length1 = Utils.ReadUInt16(buf, ref pos);
// Contains in what formats the server can parse. Ignore it.
pos += length1;
break;
case ExtensionType.ServerName:
var length2 = Utils.ReadUInt16(buf, ref pos);
pos += length2;
if (length2 != 0)
SendAlertFatal(AlertDescription.IllegalParameter);
break;
default:
SendAlertFatal(AlertDescription.IllegalParameter);
break;
}
}
if (!processedRenegotiationInfo && (!renegotiating && _noRenegotiationExtensionSupportIsFatal || renegotiating && _connState.SecureRenegotiation))
{
SendAlertFatal(AlertDescription.HandshakeFailure);
}
}
void ParseCertificateMessage(byte[] buf, ref int pos)
{
_handshakeData.CertList = new List<X509Certificate2>();
_handshakeData.CertChain = new X509Chain();
_handshakeData.CertChain.ChainPolicy.RevocationMode = _checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
var errors = System.Net.Security.SslPolicyErrors.None;
var totalLen = Utils.ReadUInt24(buf, ref pos);
if (totalLen == 0)
SendAlertFatal(AlertDescription.IllegalParameter);
int endPos = pos + totalLen;
while (pos < endPos)
{
var certLen = Utils.ReadUInt24(buf, ref pos);
var certBytes = new byte[certLen];
Buffer.BlockCopy(buf, pos, certBytes, 0, certLen);
pos += certLen;
try
{
var cert = new X509Certificate2(certBytes);
if (_handshakeData.CertList.Count != 0)
_handshakeData.CertChain.ChainPolicy.ExtraStore.Add(cert);
_handshakeData.CertList.Add(cert);
}
catch (CryptographicException e)
{
SendAlertFatal(AlertDescription.BadCertificate, e.Message);
}
}
if (_handshakeData.CertList.Count == 0)
{
SendAlertFatal(AlertDescription.CertificateUnknown, "No certificate was provided by the server");
}
// Validate certificate
_handshakeData.CertChain.Build(_handshakeData.CertList[0]);
var hostnameError = false;
if (!string.IsNullOrEmpty(_hostName))
{
hostnameError = !Utils.HostnameInCertificate(_handshakeData.CertList[0], _hostName);
if (hostnameError)
errors |= System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch;
}
var hasChainStatus = _handshakeData.CertChain.ChainStatus != null;
if (hasChainStatus && _handshakeData.CertChain.ChainStatus.Length > 0)
{
errors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
}
bool success = _remoteCertificationValidationCallback != null
? _remoteCertificationValidationCallback(this, _handshakeData.CertList[0], _handshakeData.CertChain, errors)
: errors == System.Net.Security.SslPolicyErrors.None;
if (!success)
{
if (hasChainStatus && _handshakeData.CertChain.ChainStatus.Any(s => (s.Status & X509ChainStatusFlags.NotTimeValid) != 0))
SendAlertFatal(AlertDescription.CertificateExpired);
else if (_handshakeData.CertChain.ChainStatus.Any(s => (s.Status & X509ChainStatusFlags.Revoked) != 0))
SendAlertFatal(AlertDescription.CertificateRevoked);
else
{
var errorMsg = "Server certificate was not accepted.";