-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
SslStream.IO.cs
1001 lines (857 loc) · 44.2 KB
/
SslStream.IO.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
public partial class SslStream
{
private readonly SslAuthenticationOptions _sslAuthenticationOptions = new SslAuthenticationOptions();
private int _nestedAuth;
private bool _isRenego;
private TlsFrameHelper.TlsFrameInfo _lastFrame;
private object _handshakeLock => _sslAuthenticationOptions;
private volatile TaskCompletionSource<bool>? _handshakeWaiter;
private const int HandshakeTypeOffsetSsl2 = 2; // Offset of HelloType in Sslv2 and Unified frames
private const int HandshakeTypeOffsetTls = 5; // Offset of HelloType in Sslv3 and TLS frames
private const int UnknownTlsFrameLength = int.MaxValue; // frame too short to determine length
private bool _receivedEOF;
// Used by Telemetry to ensure we log connection close exactly once
// 0 = no handshake
// 1 = handshake completed, connection opened
// 2 = SslStream disposed, connection closed
private int _connectionOpenedStatus;
private void SetException(Exception e)
{
Debug.Assert(e != null, $"Expected non-null Exception to be passed to {nameof(SetException)}");
_exception ??= ExceptionDispatchInfo.Capture(e);
CloseContext();
}
//
// This is to not depend on GC&SafeHandle class if the context is not needed anymore.
//
private void CloseInternal()
{
_exception = s_disposedSentinel;
CloseContext();
// Ensure a Read or Auth operation is not in progress,
// block potential future read and auth operations since SslStream is disposing.
// This leaves the _nestedRead = 2 and _nestedAuth = 2, but that's ok, since
// subsequent operations check the _exception sentinel first
if (Interlocked.Exchange(ref _nestedRead, StreamDisposed) == StreamNotInUse &&
Interlocked.Exchange(ref _nestedAuth, StreamDisposed) == StreamNotInUse)
{
_buffer.ReturnBuffer();
}
if (!_buffer.IsValid)
{
// Suppress finalizer since the read buffer was returned.
GC.SuppressFinalize(this);
}
if (NetSecurityTelemetry.Log.IsEnabled())
{
// Set the status to disposed. If it was opened before, log ConnectionClosed
if (Interlocked.Exchange(ref _connectionOpenedStatus, 2) == 1)
{
NetSecurityTelemetry.Log.ConnectionClosed(GetSslProtocolInternal());
}
}
}
private SecurityStatusPal EncryptData(ReadOnlyMemory<byte> buffer, ref byte[] outBuffer, out int outSize)
{
ThrowIfExceptionalOrNotAuthenticated();
lock (_handshakeLock)
{
if (_handshakeWaiter != null)
{
outSize = 0;
// avoid waiting under lock.
return new SecurityStatusPal(SecurityStatusPalErrorCode.TryAgain);
}
return Encrypt(buffer, ref outBuffer, out outSize);
}
}
//
// This method assumes that a SSPI context is already in a good shape.
// For example it is either a fresh context or already authenticated context that needs renegotiation.
//
private Task ProcessAuthenticationAsync(bool isAsync = false, CancellationToken cancellationToken = default)
{
ThrowIfExceptional();
if (NetSecurityTelemetry.Log.IsEnabled())
{
return ProcessAuthenticationWithTelemetryAsync(isAsync, cancellationToken);
}
else
{
return isAsync ?
ForceAuthenticationAsync<AsyncReadWriteAdapter>(IsServer, null, cancellationToken) :
ForceAuthenticationAsync<SyncReadWriteAdapter>(IsServer, null, cancellationToken);
}
}
private async Task ProcessAuthenticationWithTelemetryAsync(bool isAsync, CancellationToken cancellationToken)
{
NetSecurityTelemetry.Log.HandshakeStart(IsServer, _sslAuthenticationOptions.TargetHost);
long startingTimestamp = Stopwatch.GetTimestamp();
try
{
Task task = isAsync ?
ForceAuthenticationAsync<AsyncReadWriteAdapter>(IsServer, null, cancellationToken) :
ForceAuthenticationAsync<SyncReadWriteAdapter>(IsServer, null, cancellationToken);
await task.ConfigureAwait(false);
// SslStream could already have been disposed at this point, in which case _connectionOpenedStatus == 2
// Make sure that we increment the open connection counter only if it is guaranteed to be decremented in dispose/finalize
bool connectionOpen = Interlocked.CompareExchange(ref _connectionOpenedStatus, 1, 0) == 0;
NetSecurityTelemetry.Log.HandshakeCompleted(GetSslProtocolInternal(), startingTimestamp, connectionOpen);
}
catch (Exception ex)
{
NetSecurityTelemetry.Log.HandshakeFailed(IsServer, startingTimestamp, ex.Message);
throw;
}
}
//
// This is used to reply on re-handshake when received SEC_I_RENEGOTIATE on Read().
//
private async Task ReplyOnReAuthenticationAsync<TIOAdapter>(byte[]? buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
try
{
await ForceAuthenticationAsync<TIOAdapter>(receiveFirst: false, buffer, cancellationToken).ConfigureAwait(false);
}
finally
{
_handshakeWaiter!.SetResult(true);
_handshakeWaiter = null;
}
}
// This will initiate renegotiation or PHA for Tls1.3
private async Task RenegotiateAsync<TIOAdapter>(CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
if (Interlocked.CompareExchange(ref _nestedAuth, StreamInUse, StreamNotInUse) != StreamNotInUse)
{
ObjectDisposedException.ThrowIf(_nestedAuth == StreamDisposed, this);
throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, "authenticate"));
}
if (Interlocked.CompareExchange(ref _nestedRead, StreamInUse, StreamNotInUse) != StreamNotInUse)
{
ObjectDisposedException.ThrowIf(_nestedRead == StreamDisposed, this);
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read"));
}
// Write is different since we do not do anything special in Dispose
if (Interlocked.Exchange(ref _nestedWrite, StreamInUse) != StreamNotInUse)
{
_nestedRead = StreamNotInUse;
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "write"));
}
try
{
if (_buffer.ActiveLength > 0)
{
throw new InvalidOperationException(SR.net_ssl_renegotiate_buffer);
}
_sslAuthenticationOptions.RemoteCertRequired = true;
_isRenego = true;
SecurityStatusPal status = Renegotiate(out byte[]? nextmsg);
if (nextmsg is { Length: > 0 })
{
await TIOAdapter.WriteAsync(InnerStream, nextmsg, cancellationToken).ConfigureAwait(false);
await TIOAdapter.FlushAsync(InnerStream, cancellationToken).ConfigureAwait(false);
}
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (status.ErrorCode == SecurityStatusPalErrorCode.NoRenegotiation)
{
// Peer does not want to renegotiate. That should keep session usable.
return;
}
throw SslStreamPal.GetException(status);
}
ProtocolToken message;
do
{
int frameSize = await ReceiveHandshakeFrameAsync<TIOAdapter>(cancellationToken).ConfigureAwait(false);
ProcessTlsFrame(frameSize, out message);
if (message.Size > 0)
{
await TIOAdapter.WriteAsync(InnerStream, new ReadOnlyMemory<byte>(message.Payload!, 0, message.Size), cancellationToken).ConfigureAwait(false);
await TIOAdapter.FlushAsync(InnerStream, cancellationToken).ConfigureAwait(false);
}
}
while (message.Status.ErrorCode == SecurityStatusPalErrorCode.ContinueNeeded);
CompleteHandshake(_sslAuthenticationOptions);
}
finally
{
if (_buffer.ActiveLength == 0)
{
_buffer.ReturnBuffer();
}
_nestedRead = StreamNotInUse;
_nestedWrite = StreamNotInUse;
_isRenego = false;
// We will not release _nestedAuth at this point to prevent another renegotiation attempt.
}
}
// reAuthenticationData is only used on Windows in case of renegotiation.
private async Task ForceAuthenticationAsync<TIOAdapter>(bool receiveFirst, byte[]? reAuthenticationData, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
ProtocolToken message = default;
bool handshakeCompleted = false;
if (reAuthenticationData == null)
{
// prevent nesting only when authentication functions are called explicitly. e.g. handle renegotiation transparently.
if (Interlocked.Exchange(ref _nestedAuth, StreamInUse) == StreamInUse)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, "authenticate"));
}
}
try
{
if (!receiveFirst)
{
NextMessage(reAuthenticationData, out message);
if (message.Size > 0)
{
await TIOAdapter.WriteAsync(InnerStream, new ReadOnlyMemory<byte>(message.Payload!, 0, message.Size), cancellationToken).ConfigureAwait(false);
await TIOAdapter.FlushAsync(InnerStream, cancellationToken).ConfigureAwait(false);
if (NetEventSource.Log.IsEnabled())
NetEventSource.Log.SentFrame(this, message.Payload);
}
if (message.Failed)
{
// tracing done in NextMessage()
throw new AuthenticationException(SR.net_auth_SSPI, message.GetException());
}
else if (message.Status.ErrorCode == SecurityStatusPalErrorCode.OK)
{
// We can finish renegotiation without doing any read.
handshakeCompleted = true;
}
}
if (!handshakeCompleted)
{
_buffer.EnsureAvailableSpace(InitialHandshakeBufferSize);
}
while (!handshakeCompleted)
{
int frameSize = await ReceiveHandshakeFrameAsync<TIOAdapter>(cancellationToken).ConfigureAwait(false);
ProcessTlsFrame(frameSize, out message);
ReadOnlyMemory<byte> payload = default;
if (message.Size > 0)
{
payload = new ReadOnlyMemory<byte>(message.Payload, 0, message.Size);
}
else if (message.Failed && (_lastFrame.Header.Type == TlsContentType.Handshake || _lastFrame.Header.Type == TlsContentType.ChangeCipherSpec))
{
// If we failed without OS sending out alert, inject one here to be consistent across platforms.
payload = TlsFrameHelper.CreateAlertFrame(_lastFrame.Header.Version, TlsAlertDescription.ProtocolVersion);
}
if (!payload.IsEmpty)
{
// If there is message send it out even if call failed. It may contain TLS Alert.
await TIOAdapter.WriteAsync(InnerStream, payload, cancellationToken).ConfigureAwait(false);
await TIOAdapter.FlushAsync(InnerStream, cancellationToken).ConfigureAwait(false);
if (NetEventSource.Log.IsEnabled())
NetEventSource.Log.SentFrame(this, payload.Span);
}
if (message.Failed)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, message.Status);
if (_lastFrame.Header.Type == TlsContentType.Alert && _lastFrame.AlertDescription != TlsAlertDescription.CloseNotify &&
message.Status.ErrorCode == SecurityStatusPalErrorCode.IllegalMessage)
{
// Improve generic message and show details if we failed because of TLS Alert.
throw new AuthenticationException(SR.Format(SR.net_auth_tls_alert, _lastFrame.AlertDescription.ToString()), message.GetException());
}
throw new AuthenticationException(SR.net_auth_SSPI, message.GetException());
}
else if (message.Status.ErrorCode == SecurityStatusPalErrorCode.OK)
{
// We can finish renegotiation without doing any read.
handshakeCompleted = true;
}
}
CompleteHandshake(_sslAuthenticationOptions);
}
finally
{
if (reAuthenticationData == null)
{
_nestedAuth = StreamNotInUse;
_isRenego = false;
}
}
if (NetEventSource.Log.IsEnabled())
NetEventSource.Log.SspiSelectedCipherSuite(nameof(ForceAuthenticationAsync),
SslProtocol,
CipherAlgorithm,
CipherStrength,
HashAlgorithm,
HashStrength,
KeyExchangeAlgorithm,
KeyExchangeStrength);
}
// This method will make sure we have at least one full TLS frame buffered.
private async ValueTask<int> ReceiveHandshakeFrameAsync<TIOAdapter>(CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
int frameSize = await EnsureFullTlsFrameAsync<TIOAdapter>(cancellationToken, InitialHandshakeBufferSize).ConfigureAwait(false);
if (frameSize == 0)
{
// We expect to receive at least one frame
throw new IOException(SR.net_io_eof);
}
// At this point, we have at least one TLS frame.
switch (_lastFrame.Header.Type)
{
case TlsContentType.Alert:
if (TlsFrameHelper.TryGetFrameInfo(_buffer.EncryptedReadOnlySpan, ref _lastFrame))
{
if (NetEventSource.Log.IsEnabled() && _lastFrame.AlertDescription != TlsAlertDescription.CloseNotify) NetEventSource.Error(this, $"Received TLS alert {_lastFrame.AlertDescription}");
}
break;
case TlsContentType.Handshake:
#pragma warning disable CS0618
if (!_isRenego && _buffer.EncryptedReadOnlySpan[_lastFrame.Header.Version == SslProtocols.Ssl2 ? HandshakeTypeOffsetSsl2 : HandshakeTypeOffsetTls] == (byte)TlsHandshakeType.ClientHello &&
_sslAuthenticationOptions!.IsServer) // guard against malicious endpoints. We should not see ClientHello on client.
#pragma warning restore CS0618
{
TlsFrameHelper.ProcessingOptions options = NetEventSource.Log.IsEnabled() ?
TlsFrameHelper.ProcessingOptions.All :
TlsFrameHelper.ProcessingOptions.ServerName;
if (OperatingSystem.IsMacOS() && _sslAuthenticationOptions.IsServer)
{
// macOS cannot process ALPN on server at the momennt.
// We fallback to our own process similar to SNI bellow.
options |= TlsFrameHelper.ProcessingOptions.RawApplicationProtocol;
}
// Process SNI from Client Hello message
if (!TlsFrameHelper.TryGetFrameInfo(_buffer.EncryptedReadOnlySpan, ref _lastFrame, options))
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Failed to parse TLS hello.");
}
if (_lastFrame.HandshakeType == TlsHandshakeType.ClientHello)
{
// SNI if it exist. Even if we could not parse the hello, we can fall-back to default certificate.
if (_lastFrame.TargetName != null)
{
_sslAuthenticationOptions.TargetHost = _lastFrame.TargetName;
}
if (_sslAuthenticationOptions.ServerOptionDelegate != null)
{
SslServerAuthenticationOptions userOptions =
await _sslAuthenticationOptions.ServerOptionDelegate(this, new SslClientHelloInfo(_sslAuthenticationOptions.TargetHost, _lastFrame.SupportedVersions),
_sslAuthenticationOptions.UserState, cancellationToken).ConfigureAwait(false);
_sslAuthenticationOptions.UpdateOptions(userOptions);
}
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Log.ReceivedFrame(this, _lastFrame);
}
}
break;
case TlsContentType.AppData:
// TLS1.3 it is not possible to distinguish between late Handshake and Application Data
if (_isRenego && SslProtocol != SslProtocols.Tls13)
{
throw new InvalidOperationException(SR.net_ssl_renegotiate_data);
}
break;
}
return frameSize;
}
// Calls crypto on received data. No IO inside.
private void ProcessTlsFrame(int frameSize, out ProtocolToken message)
{
int chunkSize = frameSize;
ReadOnlySpan<byte> availableData = _buffer.EncryptedReadOnlySpan;
// DiscardEncrypted() does not touch data, it just increases start index so next
// EncryptedSpan will exclude the "discarded" data.
_buffer.DiscardEncrypted(frameSize);
// Often more TLS messages fit into same packet. Get as many complete frames as we can.
while (_buffer.EncryptedLength > TlsFrameHelper.HeaderSize)
{
TlsFrameHeader nextHeader = default;
if (!TlsFrameHelper.TryGetFrameHeader(_buffer.EncryptedReadOnlySpan, ref nextHeader))
{
break;
}
frameSize = nextHeader.Length;
// Can process more handshake frames in single step or during TLS1.3 post-handshake auth, but we should
// avoid processing too much so as to preserve API boundary between handshake and I/O.
if ((nextHeader.Type != TlsContentType.Handshake && nextHeader.Type != TlsContentType.ChangeCipherSpec) && !_isRenego || frameSize > _buffer.EncryptedLength)
{
// We don't have full frame left or we already have app data which needs to be processed by decrypt.
break;
}
chunkSize += frameSize;
_buffer.DiscardEncrypted(frameSize);
}
NextMessage(availableData.Slice(0, chunkSize), out message);
}
//
// This is to reset auth state on remote side.
// If this write succeeds we will allow auth retrying.
//
private void SendAuthResetSignal(ReadOnlySpan<byte> alert, ExceptionDispatchInfo exception)
{
SetException(exception.SourceException);
if (alert.Length == 0)
{
//
// We don't have an alert to send so cannot retry and fail prematurely.
//
exception.Throw();
}
InnerStream.Write(alert);
exception.Throw();
}
// - Loads the channel parameters
// - Optionally verifies the Remote Certificate
// - Sets HandshakeCompleted flag
// - Sets the guarding event if other thread is waiting for
// handshake completion
//
// - Returns false if failed to verify the Remote Cert
//
private bool CompleteHandshake(ref ProtocolToken alertToken, out SslPolicyErrors sslPolicyErrors, out X509ChainStatusFlags chainStatus)
{
ProcessHandshakeSuccess();
if (_nestedAuth != StreamInUse)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Ignoring unsolicited renegotiated certificate.");
// ignore certificates received outside of handshake or requested renegotiation.
sslPolicyErrors = SslPolicyErrors.None;
chainStatus = X509ChainStatusFlags.NoError;
return true;
}
#if TARGET_ANDROID
// On Android, the remote certificate verification can be invoked from Java TrustManager's callback
// during the handshake process. If that has occurred, we shouldn't run the validation again and
// return the existing validation result.
//
// The Java TrustManager callback is called only when the peer has a certificate. It's possible that
// the peer didn't provide any certificate (for example when the peer is the client) and the validation
// result hasn't been set. In that case we still need to run the verification at this point.
if (TryGetRemoteCertificateValidationResult(out sslPolicyErrors, out chainStatus, ref alertToken, out bool isValid))
{
_handshakeCompleted = isValid;
return isValid;
}
#endif
if (!VerifyRemoteCertificate(_sslAuthenticationOptions.CertValidationDelegate, _sslAuthenticationOptions.CertificateContext?.Trust, ref alertToken, out sslPolicyErrors, out chainStatus))
{
_handshakeCompleted = false;
return false;
}
_handshakeCompleted = true;
return true;
}
private void CompleteHandshake(SslAuthenticationOptions sslAuthenticationOptions)
{
ProtocolToken alertToken = default;
if (!CompleteHandshake(ref alertToken, out SslPolicyErrors sslPolicyErrors, out X509ChainStatusFlags chainStatus))
{
if (sslAuthenticationOptions!.CertValidationDelegate != null)
{
// there may be some chain errors but the decision was made by custom callback. Details should be tracing if enabled.
SendAuthResetSignal(new ReadOnlySpan<byte>(alertToken.Payload), ExceptionDispatchInfo.Capture(new AuthenticationException(SR.net_ssl_io_cert_custom_validation, null)));
}
else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors && chainStatus != X509ChainStatusFlags.NoError)
{
// We failed only because of chain and we have some insight.
SendAuthResetSignal(new ReadOnlySpan<byte>(alertToken.Payload), ExceptionDispatchInfo.Capture(new AuthenticationException(SR.Format(SR.net_ssl_io_cert_chain_validation, chainStatus), null)));
}
else
{
// Simple add sslPolicyErrors as crude info.
SendAuthResetSignal(new ReadOnlySpan<byte>(alertToken.Payload), ExceptionDispatchInfo.Capture(new AuthenticationException(SR.Format(SR.net_ssl_io_cert_validation, sslPolicyErrors), null)));
}
}
}
private async ValueTask WriteAsyncChunked<TIOAdapter>(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
do
{
int chunkBytes = Math.Min(buffer.Length, MaxDataSize);
await WriteSingleChunk<TIOAdapter>(buffer.Slice(0, chunkBytes), cancellationToken).ConfigureAwait(false);
buffer = buffer.Slice(chunkBytes);
} while (buffer.Length != 0);
}
private ValueTask WriteSingleChunk<TIOAdapter>(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
byte[] rentedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length + FrameOverhead);
byte[] outBuffer = rentedBuffer;
SecurityStatusPal status;
int encryptedBytes;
while (true)
{
status = EncryptData(buffer, ref outBuffer, out encryptedBytes);
// TryAgain should be rare, when renegotiation happens exactly when we want to write.
if (status.ErrorCode != SecurityStatusPalErrorCode.TryAgain)
{
break;
}
TaskCompletionSource<bool>? waiter = _handshakeWaiter;
if (waiter != null)
{
Task waiterTask = TIOAdapter.WaitAsync(waiter);
// We finished synchronously waiting for renegotiation. We can try again immediately.
if (waiterTask.IsCompletedSuccessfully)
{
continue;
}
// We need to wait asynchronously as well as for the write when EncryptData is finished.
return WaitAndWriteAsync(buffer, waiterTask, rentedBuffer, cancellationToken);
}
}
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
ArrayPool<byte>.Shared.Return(rentedBuffer);
return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new IOException(SR.net_io_encrypt, SslStreamPal.GetException(status))));
}
ValueTask t = TIOAdapter.WriteAsync(InnerStream, new ReadOnlyMemory<byte>(outBuffer, 0, encryptedBytes), cancellationToken);
if (t.IsCompletedSuccessfully)
{
ArrayPool<byte>.Shared.Return(rentedBuffer);
return t;
}
else
{
return CompleteWriteAsync(t, rentedBuffer);
}
async ValueTask WaitAndWriteAsync(ReadOnlyMemory<byte> buffer, Task waitTask, byte[] rentedBuffer, CancellationToken cancellationToken)
{
byte[]? bufferToReturn = rentedBuffer;
byte[] outBuffer = rentedBuffer;
try
{
// Wait for renegotiation to finish.
await waitTask.ConfigureAwait(false);
SecurityStatusPal status = EncryptData(buffer, ref outBuffer, out int encryptedBytes);
if (status.ErrorCode == SecurityStatusPalErrorCode.TryAgain)
{
// No need to hold on the buffer any more.
byte[] tmp = bufferToReturn;
bufferToReturn = null;
ArrayPool<byte>.Shared.Return(tmp);
// Call WriteSingleChunk() recursively to avoid code duplication.
// This should be extremely rare in cases when second renegotiation happens concurrently with Write.
await WriteSingleChunk<TIOAdapter>(buffer, cancellationToken).ConfigureAwait(false);
}
else if (status.ErrorCode == SecurityStatusPalErrorCode.OK)
{
await TIOAdapter.WriteAsync(InnerStream, new ReadOnlyMemory<byte>(outBuffer, 0, encryptedBytes), cancellationToken).ConfigureAwait(false);
}
else
{
throw new IOException(SR.net_io_encrypt, SslStreamPal.GetException(status));
}
}
finally
{
if (bufferToReturn != null)
{
ArrayPool<byte>.Shared.Return(bufferToReturn);
}
}
}
static async ValueTask CompleteWriteAsync(ValueTask writeTask, byte[] bufferToReturn)
{
try
{
await writeTask.ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(bufferToReturn);
}
}
}
~SslStream()
{
Dispose(disposing: false);
}
private void ReturnReadBufferIfEmpty()
{
if (_buffer.ActiveLength == 0)
{
_buffer.ReturnBuffer();
}
}
private bool HaveFullTlsFrame(out int frameSize)
{
frameSize = GetFrameSize(_buffer.EncryptedReadOnlySpan);
return _buffer.EncryptedLength >= frameSize;
}
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
private async ValueTask<int> EnsureFullTlsFrameAsync<TIOAdapter>(CancellationToken cancellationToken, int estimatedSize)
where TIOAdapter : IReadWriteAdapter
{
if (HaveFullTlsFrame(out int frameSize))
{
return frameSize;
}
await TIOAdapter.ReadAsync(InnerStream, Memory<byte>.Empty, cancellationToken).ConfigureAwait(false);
// If we don't have enough data to determine the frame size, use the provided estimate
// (e.g. a full TLS frame for reads, and a somewhat shorter frame for handshake / renegotiation).
// If we do know the frame size, ensure we have space for the whole frame.
_buffer.EnsureAvailableSpace(frameSize == UnknownTlsFrameLength ?
estimatedSize :
frameSize - _buffer.EncryptedLength);
while (_buffer.EncryptedLength < frameSize)
{
// there should be space left to read into
Debug.Assert(_buffer.AvailableLength > 0, "_buffer.AvailableBytes > 0");
// We either don't have full frame or we don't have enough data to even determine the size.
int bytesRead = await TIOAdapter.ReadAsync(InnerStream, _buffer.AvailableMemory, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0)
{
if (_buffer.EncryptedLength != 0)
{
// we got EOF in middle of TLS frame. Treat that as error.
throw new IOException(SR.net_io_eof);
}
return 0;
}
_buffer.Commit(bytesRead);
if (frameSize == int.MaxValue && _buffer.EncryptedLength > TlsFrameHelper.HeaderSize)
{
// recalculate frame size if needed e.g. we could not get it before.
frameSize = GetFrameSize(_buffer.EncryptedReadOnlySpan);
_buffer.EnsureAvailableSpace(frameSize - _buffer.EncryptedLength);
}
}
return frameSize;
}
private SecurityStatusPal DecryptData(int frameSize)
{
SecurityStatusPal status;
lock (_handshakeLock)
{
ThrowIfExceptionalOrNotAuthenticated();
// Decrypt will decrypt in-place and modify these to point to the actual decrypted data, which may be smaller.
status = Decrypt(_buffer.EncryptedSpanSliced(frameSize), out int decryptedOffset, out int decryptedCount);
_buffer.OnDecrypted(decryptedOffset, decryptedCount, frameSize);
if (status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate)
{
// The status indicates that peer wants to renegotiate. (Windows only)
// In practice, there can be some other reasons too - like TLS1.3 session creation
// of alert handling. We need to pass the data to lsass and it is not safe to do parallel
// write any more as that can change TLS state and the EncryptData() can fail in strange ways.
// To handle this we call DecryptData() under lock and we create TCS waiter.
// EncryptData() checks that under same lock and if it exist it will not call low-level crypto.
// Instead it will wait synchronously or asynchronously and it will try again after the wait.
// The result will be set when ReplyOnReAuthenticationAsync() is finished e.g. lsass business is over.
// If that happen before EncryptData() runs, _handshakeWaiter will be set to null
// and EncryptData() will work normally e.g. no waiting, just exclusion with DecryptData()
if (_sslAuthenticationOptions.AllowRenegotiation || SslProtocol == SslProtocols.Tls13 || _nestedAuth != 0)
{
// create TCS only if we plan to proceed. If not, we will throw later outside of the lock.
// Tls1.3 does not have renegotiation. However on Windows this error code is used
// for session management e.g. anything lsass needs to see.
// We also allow it when explicitly requested using RenegotiateAsync().
_handshakeWaiter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
}
return status;
}
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
private async ValueTask<int> ReadAsyncInternal<TIOAdapter>(Memory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
// Throw first if we already have exception.
// Check for disposal is not atomic so we will check again below.
ThrowIfExceptionalOrNotAuthenticated();
if (Interlocked.CompareExchange(ref _nestedRead, StreamInUse, StreamNotInUse) != StreamNotInUse)
{
ObjectDisposedException.ThrowIf(_nestedRead == StreamDisposed, this);
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read"));
}
try
{
int processedLength = 0;
int nextTlsFrameLength = UnknownTlsFrameLength;
if (_buffer.DecryptedLength != 0)
{
processedLength = CopyDecryptedData(buffer);
if (processedLength == buffer.Length || !HaveFullTlsFrame(out nextTlsFrameLength))
{
// We either filled whole buffer or used all buffered frames.
return processedLength;
}
buffer = buffer.Slice(processedLength);
}
if (_receivedEOF && nextTlsFrameLength == UnknownTlsFrameLength)
{
// there should be no frames waiting for processing
Debug.Assert(_buffer.EncryptedLength == 0);
// We received EOF during previous read but had buffered data to return.
return 0;
}
Debug.Assert(_buffer.DecryptedLength == 0);
while (true)
{
int payloadBytes = await EnsureFullTlsFrameAsync<TIOAdapter>(cancellationToken, ReadBufferSize).ConfigureAwait(false);
if (payloadBytes == 0)
{
_receivedEOF = true;
break;
}
SecurityStatusPal status = DecryptData(payloadBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
byte[]? extraBuffer = null;
if (_buffer.DecryptedLength != 0)
{
extraBuffer = new byte[_buffer.DecryptedLength];
_buffer.DecryptedSpan.CopyTo(extraBuffer);
_buffer.Discard(_buffer.DecryptedLength);
}
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(null, $"***Processing an error Status = {status}");
if (status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate)
{
// We determined above that we will not process it.
if (_handshakeWaiter == null)
{
throw new IOException(SR.net_ssl_io_renego);
}
await ReplyOnReAuthenticationAsync<TIOAdapter>(extraBuffer, cancellationToken).ConfigureAwait(false);
}
else if (status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired)
{
_receivedEOF = true;
break;
}
else
{
throw new IOException(SR.net_io_decrypt, SslStreamPal.GetException(status));
}
}
if (_buffer.DecryptedLength > 0)
{
// This will either copy data from rented buffer or adjust final buffer as needed.
// In both cases _decryptedBytesOffset and _decryptedBytesCount will be updated as needed.
int copyLength = CopyDecryptedData(buffer);
processedLength += copyLength;
if (copyLength == buffer.Length)
{
// We have more decrypted data after we filled provided buffer.
break;
}
buffer = buffer.Slice(copyLength);
}
if (processedLength == 0)
{
// We did not get any real data so far.
continue;
}
if (!HaveFullTlsFrame(out payloadBytes))
{
// We don't have another frame to process but we have some data to return to caller.
break;
}
TlsFrameHelper.TryGetFrameHeader(_buffer.EncryptedReadOnlySpan, ref _lastFrame.Header);
if (_lastFrame.Header.Type != TlsContentType.AppData)
{
// Alerts, handshake and anything else will be processed separately.
// This may not be necessary but it improves compatibility with older versions.
break;
}
}
return processedLength;
}
catch (Exception e)
{
if (e is IOException || (e is OperationCanceledException && cancellationToken.IsCancellationRequested))
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
ReturnReadBufferIfEmpty();
_nestedRead = StreamNotInUse;
}
}
private async ValueTask WriteAsyncInternal<TIOAdapter>(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
ThrowIfExceptionalOrNotAuthenticatedOrShutdown();
if (buffer.Length == 0 && !SslStreamPal.CanEncryptEmptyMessage)
{
// If it's an empty message and the PAL doesn't support that, we're done.
return;
}
if (Interlocked.Exchange(ref _nestedWrite, StreamInUse) == StreamInUse)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "write"));
}
try
{
ValueTask t = buffer.Length < MaxDataSize ?
WriteSingleChunk<TIOAdapter>(buffer, cancellationToken) :
WriteAsyncChunked<TIOAdapter>(buffer, cancellationToken);
await t.ConfigureAwait(false);
}
catch (Exception e)
{
if (e is IOException || (e is OperationCanceledException && cancellationToken.IsCancellationRequested))
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
_nestedWrite = StreamNotInUse;
}
}
private int CopyDecryptedData(Memory<byte> buffer)
{
Debug.Assert(_buffer.DecryptedLength > 0);
int copyBytes = Math.Min(_buffer.DecryptedLength, buffer.Length);
if (copyBytes != 0)
{
_buffer.DecryptedReadOnlySpanSliced(copyBytes).CopyTo(buffer.Span);
_buffer.Discard(copyBytes);
}
return copyBytes;
}
// Returns TLS Frame size including header size.
private int GetFrameSize(ReadOnlySpan<byte> buffer)
{
if (buffer.Length < TlsFrameHelper.HeaderSize)
{
return UnknownTlsFrameLength;
}
if (!TlsFrameHelper.TryGetFrameHeader(buffer, ref _lastFrame.Header))
{
throw new IOException(SR.net_ssl_io_frame);
}
if (_lastFrame.Header.Length < 0)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "invalid TLS frame size");
throw new AuthenticationException(SR.net_frame_read_size);
}
return _lastFrame.Header.Length;
}
}