/
NegotiateStream.cs
970 lines (795 loc) · 42.5 KB
/
NegotiateStream.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
/// <summary>
/// Provides a stream that uses the Negotiate security protocol to authenticate the client, and optionally the server, in client-server communication.
/// </summary>
[UnsupportedOSPlatform("tvos")]
public partial class NegotiateStream : AuthenticatedStream
{
/// <summary>Set as the _exception when the instance is disposed.</summary>
private static readonly ExceptionDispatchInfo s_disposedSentinel = ExceptionDispatchInfo.Capture(new ObjectDisposedException(nameof(NegotiateStream), (string?)null));
private const int ERROR_TRUST_FAILURE = 1790; // Used to serialize protectionLevel or impersonationLevel mismatch error to the remote side.
private const int MaxReadFrameSize = 64 * 1024;
private const int MaxWriteDataSize = 63 * 1024; // 1k for the framing and trailer that is always less as per SSPI.
private const string DefaultPackage = NegotiationInfoClass.Negotiate;
#pragma warning disable CA1825 // used in reference comparison, requires unique object identity
private static readonly byte[] s_emptyMessage = new byte[0];
#pragma warning restore CA1825
private readonly byte[] _readHeader;
private IIdentity? _remoteIdentity;
private byte[] _readBuffer;
private int _readBufferOffset;
private int _readBufferCount;
private byte[]? _writeBuffer;
private volatile int _writeInProgress;
private volatile int _readInProgress;
private volatile int _authInProgress;
private ExceptionDispatchInfo? _exception;
private StreamFramer? _framer;
private NTAuthentication? _context;
private bool _canRetryAuthentication;
private ProtectionLevel _expectedProtectionLevel;
private TokenImpersonationLevel _expectedImpersonationLevel;
private ExtendedProtectionPolicy? _extendedProtectionPolicy;
/// <summary>
/// SSPI does not send a server ack on successful auth.
/// This is a state variable used to gracefully handle auth confirmation.
/// </summary>
private bool _remoteOk;
public NegotiateStream(Stream innerStream) : this(innerStream, false)
{
}
public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen)
{
_readHeader = new byte[4];
_readBuffer = Array.Empty<byte>();
}
protected override void Dispose(bool disposing)
{
try
{
_exception = s_disposedSentinel;
_context?.CloseContext();
}
finally
{
base.Dispose(disposing);
}
}
public override async ValueTask DisposeAsync()
{
try
{
_exception = s_disposedSentinel;
_context?.CloseContext();
}
finally
{
await base.DisposeAsync().ConfigureAwait(false);
}
}
public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, binding: null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsClient(credential, binding: null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsClient(
NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsClient(credential, binding: null, targetName, requiredProtectionLevel, allowedImpersonationLevel,
asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsClient(
NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback? asyncCallback, object? asyncState) =>
TaskToApm.Begin(AuthenticateAsClientAsync(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel), asyncCallback, asyncState);
public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) => TaskToApm.End(asyncResult);
public virtual void AuthenticateAsServer() =>
AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy: null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual void AuthenticateAsServer(ExtendedProtectionPolicy? policy) =>
AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) =>
AuthenticateAsServer(credential, policy: null, requiredProtectionLevel, requiredImpersonationLevel);
public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
ValidateCreateContext(DefaultPackage, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
AuthenticateAsync<SyncReadWriteAdapter>(default(CancellationToken)).GetAwaiter().GetResult();
}
public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy: null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy? policy, AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsServer(
NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel,
AsyncCallback? asyncCallback, object? asyncState) =>
BeginAuthenticateAsServer(credential, policy: null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState);
public virtual IAsyncResult BeginAuthenticateAsServer(
NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel,
AsyncCallback? asyncCallback, object? asyncState) =>
TaskToApm.Begin(AuthenticateAsServerAsync(credential, policy, requiredProtectionLevel, requiredImpersonationLevel), asyncCallback, asyncState);
public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) => TaskToApm.End(asyncResult);
public virtual void AuthenticateAsClient() =>
AuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, binding: null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName) =>
AuthenticateAsClient(credential, binding: null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName) =>
AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual void AuthenticateAsClient(
NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) =>
AuthenticateAsClient(credential, binding: null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
public virtual void AuthenticateAsClient(
NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
{
ValidateCreateContext(DefaultPackage, isServer: false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
AuthenticateAsync<SyncReadWriteAdapter>(default(CancellationToken)).GetAwaiter().GetResult();
}
public virtual Task AuthenticateAsClientAsync() =>
AuthenticateAsClientAsync((NetworkCredential)CredentialCache.DefaultCredentials, binding: null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName) =>
AuthenticateAsClientAsync(credential, binding: null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel) =>
AuthenticateAsClientAsync(credential, binding: null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding? binding, string targetName) =>
AuthenticateAsClientAsync(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
ValidateCreateContext(DefaultPackage, isServer: false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
return AuthenticateAsync<AsyncReadWriteAdapter>(default(CancellationToken));
}
public virtual Task AuthenticateAsServerAsync() =>
AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials, policy: null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy? policy) =>
AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) =>
AuthenticateAsServerAsync(credential, policy: null, requiredProtectionLevel, requiredImpersonationLevel);
public virtual Task AuthenticateAsServerAsync(
NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
ValidateCreateContext(DefaultPackage, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
return AuthenticateAsync<AsyncReadWriteAdapter>(default(CancellationToken));
}
public override bool IsAuthenticated => IsAuthenticatedCore;
[MemberNotNullWhen(true, nameof(_context))]
private bool IsAuthenticatedCore => _context != null && HandshakeComplete && _exception == null && _remoteOk;
public override bool IsMutuallyAuthenticated =>
IsAuthenticatedCore &&
!_context.IsNTLM && // suppressing for NTLM since SSPI does not return correct value in the context flags.
_context.IsMutualAuthFlag;
public override bool IsEncrypted => IsAuthenticatedCore && _context.IsConfidentialityFlag;
public override bool IsSigned => IsAuthenticatedCore && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag);
public override bool IsServer => _context != null && _context.IsServer;
public virtual TokenImpersonationLevel ImpersonationLevel
{
get
{
ThrowIfFailed(authSuccessCheck: true);
return PrivateImpersonationLevel;
}
}
private TokenImpersonationLevel PrivateImpersonationLevel =>
_context!.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM ? TokenImpersonationLevel.Delegation : // We should suppress the delegate flag in NTLM case.
_context.IsIdentifyFlag ? TokenImpersonationLevel.Identification :
TokenImpersonationLevel.Impersonation;
private bool HandshakeComplete => _context!.IsCompleted && _context.IsValidContext;
private bool CanGetSecureStream => _context!.IsConfidentialityFlag || _context.IsIntegrityFlag;
public virtual IIdentity RemoteIdentity
{
get
{
IIdentity? identity = _remoteIdentity;
if (identity is null)
{
ThrowIfFailed(authSuccessCheck: true);
_remoteIdentity = identity = NegotiateStreamPal.GetIdentity(_context!);
}
return identity;
}
}
public override bool CanSeek => false;
public override bool CanRead => IsAuthenticated && InnerStream.CanRead;
public override bool CanTimeout => InnerStream.CanTimeout;
public override bool CanWrite => IsAuthenticated && InnerStream.CanWrite;
public override int ReadTimeout
{
get => InnerStream.ReadTimeout;
set => InnerStream.ReadTimeout = value;
}
public override int WriteTimeout
{
get => InnerStream.WriteTimeout;
set => InnerStream.WriteTimeout = value;
}
public override long Length => InnerStream.Length;
public override long Position
{
get => InnerStream.Position;
set => throw new NotSupportedException(SR.net_noseek);
}
public override void SetLength(long value) =>
InnerStream.SetLength(value);
public override long Seek(long offset, SeekOrigin origin) =>
throw new NotSupportedException(SR.net_noseek);
public override void Flush() =>
InnerStream.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) =>
InnerStream.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count)
{
ValidateBufferArguments(buffer, offset, count);
ThrowIfFailed(authSuccessCheck: true);
if (!CanGetSecureStream)
{
return InnerStream.Read(buffer, offset, count);
}
ValueTask<int> vt = ReadAsync<SyncReadWriteAdapter>(new Memory<byte>(buffer, offset, count), default(CancellationToken));
Debug.Assert(vt.IsCompleted, "Should have completed synchroously with sync adapter");
return vt.GetAwaiter().GetResult();
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateBufferArguments(buffer, offset, count);
ThrowIfFailed(authSuccessCheck: true);
if (!CanGetSecureStream)
{
return InnerStream.ReadAsync(buffer, offset, count, cancellationToken);
}
return ReadAsync<AsyncReadWriteAdapter>(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
ThrowIfFailed(authSuccessCheck: true);
if (!CanGetSecureStream)
{
return InnerStream.ReadAsync(buffer, cancellationToken);
}
return ReadAsync<AsyncReadWriteAdapter>(buffer, cancellationToken);
}
private async ValueTask<int> ReadAsync<TIOAdapter>(Memory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
Debug.Assert(_context is not null);
if (Interlocked.Exchange(ref _readInProgress, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read"));
}
try
{
if (_readBufferCount != 0)
{
int copyBytes = Math.Min(_readBufferCount, buffer.Length);
if (copyBytes != 0)
{
_readBuffer.AsMemory(_readBufferOffset, copyBytes).CopyTo(buffer);
_readBufferOffset += copyBytes;
_readBufferCount -= copyBytes;
}
return copyBytes;
}
while (true)
{
int readBytes = await ReadAllAsync(InnerStream, _readHeader, allowZeroRead: true, cancellationToken).ConfigureAwait(false);
if (readBytes == 0)
{
return 0;
}
// Replace readBytes with the body size recovered from the header content.
readBytes = BitConverter.ToInt32(_readHeader, 0);
// The body carries 4 bytes for trailer size slot plus trailer, hence <= 4 frame size is always an error.
// Additionally we'd like to restrict the read frame size to 64k.
if (readBytes <= 4 || readBytes > MaxReadFrameSize)
{
throw new IOException(SR.net_frame_read_size);
}
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
_readBufferCount = readBytes;
_readBufferOffset = 0;
if (_readBuffer.Length < readBytes)
{
_readBuffer = new byte[readBytes];
}
readBytes = await ReadAllAsync(InnerStream, new Memory<byte>(_readBuffer, 0, readBytes), allowZeroRead: false, cancellationToken).ConfigureAwait(false);
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_
// Decrypted data start from zero offset, the size can be shrunk after decryption.
_readBufferCount = readBytes = _context.Decrypt(_readBuffer.AsSpan(0, readBytes), out _readBufferOffset);
if (readBytes == 0 && buffer.Length != 0)
{
// Read again.
continue;
}
if (readBytes > buffer.Length)
{
readBytes = buffer.Length;
}
_readBuffer.AsMemory(_readBufferOffset, readBytes).CopyTo(buffer);
_readBufferOffset += readBytes;
_readBufferCount -= readBytes;
return readBytes;
}
}
catch (Exception e) when (!(e is IOException || e is OperationCanceledException))
{
throw new IOException(SR.net_io_read, e);
}
finally
{
_readInProgress = 0;
}
static async ValueTask<int> ReadAllAsync(Stream stream, Memory<byte> buffer, bool allowZeroRead, CancellationToken cancellationToken)
{
int read = await TIOAdapter.ReadAtLeastAsync(
stream, buffer, buffer.Length, throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
if (read < buffer.Length)
{
if (read != 0 || !allowZeroRead)
{
throw new IOException(SR.net_io_eof);
}
}
return read;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
ValidateBufferArguments(buffer, offset, count);
ThrowIfFailed(authSuccessCheck: true);
if (!CanGetSecureStream)
{
InnerStream.Write(buffer, offset, count);
return;
}
WriteAsync<SyncReadWriteAdapter>(new ReadOnlyMemory<byte>(buffer, offset, count), default(CancellationToken)).GetAwaiter().GetResult();
}
/// <returns>A <see cref="Task"/> that represents the asynchronous read operation.</returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateBufferArguments(buffer, offset, count);
ThrowIfFailed(authSuccessCheck: true);
if (!CanGetSecureStream)
{
return InnerStream.WriteAsync(buffer, offset, count, cancellationToken);
}
return WriteAsync<AsyncReadWriteAdapter>(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
}
/// <returns>A <see cref="ValueTask"/> that represents the asynchronous read operation.</returns>
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
ThrowIfFailed(authSuccessCheck: true);
if (!CanGetSecureStream)
{
return InnerStream.WriteAsync(buffer, cancellationToken);
}
return new ValueTask(WriteAsync<AsyncReadWriteAdapter>(buffer, cancellationToken));
}
private async Task WriteAsync<TIOAdapter>(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
Debug.Assert(_context is not null);
if (Interlocked.Exchange(ref _writeInProgress, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "write"));
}
try
{
while (!buffer.IsEmpty)
{
int chunkBytes = Math.Min(buffer.Length, MaxWriteDataSize);
int encryptedBytes;
try
{
encryptedBytes = _context.Encrypt(buffer.Slice(0, chunkBytes).Span, ref _writeBuffer);
}
catch (Exception e)
{
throw new IOException(SR.net_io_encrypt, e);
}
await TIOAdapter.WriteAsync(InnerStream, new ReadOnlyMemory<byte>(_writeBuffer, 0, encryptedBytes), cancellationToken).ConfigureAwait(false);
buffer = buffer.Slice(chunkBytes);
}
}
catch (Exception e) when (!(e is IOException || e is OperationCanceledException))
{
throw new IOException(SR.net_io_write, e);
}
finally
{
_writeInProgress = 0;
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count), asyncCallback, asyncState);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count), asyncCallback, asyncState);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
private void ThrowIfExceptional()
{
ExceptionDispatchInfo? e = _exception;
if (e != null)
{
ThrowExceptional(e);
}
// Local function to make the check method more inline friendly.
void ThrowExceptional(ExceptionDispatchInfo e)
{
// If the stored exception just indicates disposal, throw a new ODE rather than the stored one,
// so as to not continually build onto the shared exception's stack.
ObjectDisposedException.ThrowIf(ReferenceEquals(e, s_disposedSentinel), this);
// Throw the stored exception.
e.Throw();
}
}
private void ValidateCreateContext(
string package,
NetworkCredential credential,
string servicePrincipalName,
ExtendedProtectionPolicy? policy,
ProtectionLevel protectionLevel,
TokenImpersonationLevel impersonationLevel)
{
if (policy != null)
{
// One of these must be set if EP is turned on
if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null)
{
throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy));
}
_extendedProtectionPolicy = policy;
}
else
{
_extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
}
ValidateCreateContext(package, isServer: true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel);
}
private void ValidateCreateContext(
string package,
bool isServer,
NetworkCredential credential,
string? servicePrincipalName,
ChannelBinding? channelBinding,
ProtectionLevel protectionLevel,
TokenImpersonationLevel impersonationLevel)
{
if (!_canRetryAuthentication)
{
ThrowIfExceptional();
}
if (_context != null && _context.IsValidContext)
{
throw new InvalidOperationException(SR.net_auth_reauth);
}
ArgumentNullException.ThrowIfNull(credential);
ArgumentNullException.ThrowIfNull(servicePrincipalName);
NegotiateStreamPal.ValidateImpersonationLevel(impersonationLevel);
if (_context != null && IsServer != isServer)
{
throw new InvalidOperationException(SR.net_auth_client_server);
}
_exception = null;
_remoteOk = false;
_framer = new StreamFramer();
_framer.WriteHeader.MessageId = FrameHeader.HandshakeId;
_expectedProtectionLevel = protectionLevel;
_expectedImpersonationLevel = isServer ? impersonationLevel : TokenImpersonationLevel.None;
ContextFlagsPal flags = ContextFlagsPal.Connection;
// A workaround for the client when talking to Win9x on the server side.
if (protectionLevel == ProtectionLevel.None && !isServer)
{
package = NegotiationInfoClass.NTLM;
}
else if (protectionLevel == ProtectionLevel.EncryptAndSign)
{
flags |= ContextFlagsPal.Confidentiality;
}
else if (protectionLevel == ProtectionLevel.Sign)
{
// Assuming user expects NT4 SP4 and above.
flags |= ContextFlagsPal.ReplayDetect | ContextFlagsPal.SequenceDetect | ContextFlagsPal.InitIntegrity;
}
if (isServer)
{
if (_extendedProtectionPolicy!.PolicyEnforcement == PolicyEnforcement.WhenSupported)
{
flags |= ContextFlagsPal.AllowMissingBindings;
}
if (_extendedProtectionPolicy.PolicyEnforcement != PolicyEnforcement.Never &&
_extendedProtectionPolicy.ProtectionScenario == ProtectionScenario.TrustedProxy)
{
flags |= ContextFlagsPal.ProxyBindings;
}
}
else
{
// Server side should not request any of these flags.
if (protectionLevel != ProtectionLevel.None)
{
flags |= ContextFlagsPal.MutualAuth;
}
if (impersonationLevel == TokenImpersonationLevel.Identification)
{
flags |= ContextFlagsPal.InitIdentify;
}
if (impersonationLevel == TokenImpersonationLevel.Delegation)
{
flags |= ContextFlagsPal.Delegate;
}
}
_canRetryAuthentication = false;
try
{
_context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding!);
}
catch (Win32Exception e)
{
throw new AuthenticationException(SR.net_auth_SSPI, e);
}
}
private void SetFailed(Exception e)
{
if (_exception == null || !(_exception.SourceException is ObjectDisposedException))
{
_exception = ExceptionDispatchInfo.Capture(e);
}
_context?.CloseContext();
}
private void ThrowIfFailed(bool authSuccessCheck)
{
ThrowIfExceptional();
if (authSuccessCheck && !IsAuthenticatedCore)
{
throw new InvalidOperationException(SR.net_auth_noauth);
}
}
private async Task AuthenticateAsync<TIOAdapter>(CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
Debug.Assert(_context != null);
ThrowIfFailed(authSuccessCheck: false);
if (Interlocked.Exchange(ref _authInProgress, 1) == 1)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, "authenticate"));
}
try
{
await (_context.IsServer ?
ReceiveBlobAsync<TIOAdapter>(cancellationToken) : // server should listen for a client blob
SendBlobAsync<TIOAdapter>(message: null, cancellationToken)).ConfigureAwait(false); // client should send the first blob
}
catch (Exception e)
{
SetFailed(e);
throw;
}
finally
{
_authInProgress = 0;
}
}
private bool CheckSpn()
{
Debug.Assert(_context != null);
if (_context.IsKerberos ||
_extendedProtectionPolicy!.PolicyEnforcement == PolicyEnforcement.Never ||
_extendedProtectionPolicy.CustomServiceNames == null)
{
return true;
}
string? clientSpn = _context.ClientSpecifiedSpn;
if (string.IsNullOrEmpty(clientSpn))
{
return _extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported;
}
return _extendedProtectionPolicy.CustomServiceNames.Contains(clientSpn);
}
// Client authentication starts here, but server also loops through this method.
private async Task SendBlobAsync<TIOAdapter>(byte[]? message, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
Debug.Assert(_context != null);
Exception? exception = null;
if (message != s_emptyMessage)
{
message = GetOutgoingBlob(message, ref exception);
}
if (exception != null)
{
// Signal remote side on a failed attempt.
await SendAuthResetSignalAndThrowAsync<TIOAdapter>(message!, exception, cancellationToken).ConfigureAwait(false);
Debug.Fail("Unreachable");
}
if (HandshakeComplete)
{
if (_context.IsServer && !CheckSpn())
{
exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch);
int statusCode = ERROR_TRUST_FAILURE;
message = new byte[sizeof(long)];
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(statusCode & 0xFF);
statusCode = (int)((uint)statusCode >> 8);
}
await SendAuthResetSignalAndThrowAsync<TIOAdapter>(message, exception, cancellationToken).ConfigureAwait(false);
Debug.Fail("Unreachable");
}
if (PrivateImpersonationLevel < _expectedImpersonationLevel)
{
exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, _expectedImpersonationLevel.ToString(), PrivateImpersonationLevel.ToString()));
int statusCode = ERROR_TRUST_FAILURE;
message = new byte[sizeof(long)];
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(statusCode & 0xFF);
statusCode = (int)((uint)statusCode >> 8);
}
await SendAuthResetSignalAndThrowAsync<TIOAdapter>(message, exception, cancellationToken).ConfigureAwait(false);
Debug.Fail("Unreachable");
}
ProtectionLevel result = _context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : _context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None;
if (result < _expectedProtectionLevel)
{
exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, result.ToString(), _expectedProtectionLevel.ToString()));
int statusCode = ERROR_TRUST_FAILURE;
message = new byte[sizeof(long)];
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(statusCode & 0xFF);
statusCode = (int)((uint)statusCode >> 8);
}
await SendAuthResetSignalAndThrowAsync<TIOAdapter>(message, exception, cancellationToken).ConfigureAwait(false);
Debug.Fail("Unreachable");
}
// Signal remote party that we are done
_framer!.WriteHeader.MessageId = FrameHeader.HandshakeDoneId;
if (_context.IsServer)
{
// Server may complete now because client SSPI would not complain at this point.
_remoteOk = true;
// However the client will wait for server to send this ACK
// Force signaling server OK to the client
message ??= s_emptyMessage;
}
}
else if (message == null || message == s_emptyMessage)
{
throw new InternalException();
}
if (message != null)
{
//even if we are completed, there could be a blob for sending.
await _framer!.WriteMessageAsync<TIOAdapter>(InnerStream, message, cancellationToken).ConfigureAwait(false);
}
if (HandshakeComplete && _remoteOk)
{
// We are done with success.
return;
}
await ReceiveBlobAsync<TIOAdapter>(cancellationToken).ConfigureAwait(false);
}
// Server authentication starts here, but client also loops through this method.
private async Task ReceiveBlobAsync<TIOAdapter>(CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
Debug.Assert(_framer != null);
byte[]? message = await _framer.ReadMessageAsync<TIOAdapter>(InnerStream, cancellationToken).ConfigureAwait(false);
if (message == null)
{
// This is an EOF otherwise we would get at least *empty* message but not a null one.
throw new AuthenticationException(SR.net_auth_eof);
}
// Process Header information.
if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeErrId)
{
if (message.Length >= sizeof(long))
{
// Try to recover remote win32 Exception.
long error = 0;
for (int i = 0; i < 8; ++i)
{
error = (error << 8) + message[i];
}
ThrowCredentialException(error);
}
throw new AuthenticationException(SR.net_auth_alert);
}
if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeDoneId)
{
_remoteOk = true;
}
else if (_framer.ReadHeader.MessageId != FrameHeader.HandshakeId)
{
throw new AuthenticationException(SR.Format(SR.net_io_header_id, nameof(FrameHeader.MessageId), _framer.ReadHeader.MessageId, FrameHeader.HandshakeId));
}
// If we are done don't go into send.
if (HandshakeComplete)
{
if (!_remoteOk)
{
throw new AuthenticationException(SR.Format(SR.net_io_header_id, nameof(FrameHeader.MessageId), _framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId));
}
return;
}
// Not yet done, get a new blob and send it if any.
await SendBlobAsync<TIOAdapter>(message, cancellationToken).ConfigureAwait(false);
}
// This is to reset auth state on the remote side.
// If this write succeeds we will allow auth retrying.
private async Task SendAuthResetSignalAndThrowAsync<TIOAdapter>(byte[] message, Exception exception, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
_framer!.WriteHeader.MessageId = FrameHeader.HandshakeErrId;
if (IsLogonDeniedException(exception))
{
exception = new InvalidCredentialException(IsServer ? SR.net_auth_bad_client_creds : SR.net_auth_bad_client_creds_or_target_mismatch, exception);
}
if (!(exception is AuthenticationException))
{
exception = new AuthenticationException(SR.net_auth_SSPI, exception);
}
await _framer.WriteMessageAsync<TIOAdapter>(InnerStream, message, cancellationToken).ConfigureAwait(false);
_canRetryAuthentication = true;
ExceptionDispatchInfo.Throw(exception);
}
private static bool IsError(SecurityStatusPal status) =>
(int)status.ErrorCode >= (int)SecurityStatusPalErrorCode.OutOfMemory;
private unsafe byte[]? GetOutgoingBlob(byte[]? incomingBlob, ref Exception? e)
{
Debug.Assert(_context != null);
byte[]? message = _context.GetOutgoingBlob(incomingBlob, false, out SecurityStatusPal statusCode);
if (IsError(statusCode))
{
e = NegotiateStreamPal.CreateExceptionFromError(statusCode);
uint error = (uint)e.HResult;
message = new byte[sizeof(long)];
for (int i = message.Length - 1; i >= 0; --i)
{
message[i] = (byte)(error & 0xFF);
error >>= 8;
}
}
if (message != null && message.Length == 0)
{
message = s_emptyMessage;
}
return message;
}
private static void ThrowCredentialException(long error)
{
var e = new Win32Exception((int)error);
throw e.NativeErrorCode switch
{
(int)SecurityStatusPalErrorCode.LogonDenied => new InvalidCredentialException(SR.net_auth_bad_client_creds, e),
ERROR_TRUST_FAILURE => new AuthenticationException(SR.net_auth_context_expectation_remote, e),
_ => new AuthenticationException(SR.net_auth_alert, e)
};
}
private static bool IsLogonDeniedException(Exception exception) =>
exception is Win32Exception win32exception &&
win32exception.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied;
}
}