Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
NegotiateStream.cs
Go to the documentation of this file.
3using System.IO;
12
13namespace System.Net.Security;
14
15[UnsupportedOSPlatform("tvos")]
17{
18 private static readonly ExceptionDispatchInfo s_disposedSentinel = ExceptionDispatchInfo.Capture(new ObjectDisposedException("NegotiateStream", (string?)null));
19
20 private static readonly byte[] s_emptyMessage = new byte[0];
21
22 private readonly byte[] _readHeader;
23
25
26 private byte[] _readBuffer;
27
28 private int _readBufferOffset;
29
30 private int _readBufferCount;
31
32 private byte[] _writeBuffer;
33
34 private volatile int _writeInProgress;
35
36 private volatile int _readInProgress;
37
38 private volatile int _authInProgress;
39
41
43
45
47
49
51
53
54 private uint _readSequenceNumber;
55
57
58 private bool _remoteOk;
59
60 public override bool IsAuthenticated => IsAuthenticatedCore;
61
62 [MemberNotNullWhen(true, "_context")]
64 {
65 [MemberNotNullWhen(true, "_context")]
66 get
67 {
68 if (_context != null && HandshakeComplete && _exception == null)
69 {
70 return _remoteOk;
71 }
72 return false;
73 }
74 }
75
76 public override bool IsMutuallyAuthenticated
77 {
78 get
79 {
81 {
83 }
84 return false;
85 }
86 }
87
88 public override bool IsEncrypted
89 {
90 get
91 {
93 {
95 }
96 return false;
97 }
98 }
99
100 public override bool IsSigned
101 {
102 get
103 {
105 {
107 {
109 }
110 return true;
111 }
112 return false;
113 }
114 }
115
116 public override bool IsServer
117 {
118 get
119 {
120 if (_context != null)
121 {
122 return _context.IsServer;
123 }
124 return false;
125 }
126 }
127
128 public virtual TokenImpersonationLevel ImpersonationLevel
129 {
130 get
131 {
132 ThrowIfFailed(authSuccessCheck: true);
134 }
135 }
136
138 {
139 get
140 {
141 if (!_context.IsDelegationFlag || !(_context.ProtocolName != "NTLM"))
142 {
144 {
145 return TokenImpersonationLevel.Impersonation;
146 }
147 return TokenImpersonationLevel.Identification;
148 }
149 return TokenImpersonationLevel.Delegation;
150 }
151 }
152
153 private bool HandshakeComplete
154 {
155 get
156 {
158 {
160 }
161 return false;
162 }
163 }
164
166 {
167 get
168 {
170 {
172 }
173 return true;
174 }
175 }
176
178 {
179 get
180 {
181 IIdentity identity = _remoteIdentity;
182 if (identity == null)
183 {
184 ThrowIfFailed(authSuccessCheck: true);
186 }
187 return identity;
188 }
189 }
190
191 public override bool CanSeek => false;
192
193 public override bool CanRead
194 {
195 get
196 {
197 if (IsAuthenticated)
198 {
199 return base.InnerStream.CanRead;
200 }
201 return false;
202 }
203 }
204
205 public override bool CanTimeout => base.InnerStream.CanTimeout;
206
207 public override bool CanWrite
208 {
209 get
210 {
211 if (IsAuthenticated)
212 {
213 return base.InnerStream.CanWrite;
214 }
215 return false;
216 }
217 }
218
219 public override int ReadTimeout
220 {
221 get
222 {
223 return base.InnerStream.ReadTimeout;
224 }
225 set
226 {
227 base.InnerStream.ReadTimeout = value;
228 }
229 }
230
231 public override int WriteTimeout
232 {
233 get
234 {
235 return base.InnerStream.WriteTimeout;
236 }
237 set
238 {
239 base.InnerStream.WriteTimeout = value;
240 }
241 }
242
243 public override long Length => base.InnerStream.Length;
244
245 public override long Position
246 {
247 get
248 {
249 return base.InnerStream.Position;
250 }
251 set
252 {
254 }
255 }
256
257 public NegotiateStream(Stream innerStream)
258 : this(innerStream, leaveInnerStreamOpen: false)
259 {
260 }
261
262 public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen)
263 : base(innerStream, leaveInnerStreamOpen)
264 {
265 _readHeader = new byte[4];
266 _readBuffer = Array.Empty<byte>();
267 }
268
269 protected override void Dispose(bool disposing)
270 {
271 try
272 {
275 }
276 finally
277 {
278 base.Dispose(disposing);
279 }
280 }
281
282 public override async ValueTask DisposeAsync()
283 {
284 try
285 {
288 }
289 finally
290 {
291 await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
292 }
293 }
294
295 public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback? asyncCallback, object? asyncState)
296 {
297 return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
298 }
299
300 public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback? asyncCallback, object? asyncState)
301 {
302 return BeginAuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
303 }
304
305 public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, AsyncCallback? asyncCallback, object? asyncState)
306 {
307 return BeginAuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
308 }
309
310 public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
311 {
312 return BeginAuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel, asyncCallback, asyncState);
313 }
314
315 public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
316 {
317 return System.Threading.Tasks.TaskToApm.Begin(AuthenticateAsClientAsync(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel), asyncCallback, asyncState);
318 }
319
324
329
334
335 public virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
336 {
337 AuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel);
338 }
339
340 public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
341 {
342 ValidateCreateContext("Negotiate", credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
343 AuthenticateAsync(new SyncReadWriteAdapter(base.InnerStream), "AuthenticateAsServer").GetAwaiter().GetResult();
344 }
345
346 public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback? asyncCallback, object? asyncState)
347 {
348 return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
349 }
350
351 public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy? policy, AsyncCallback? asyncCallback, object? asyncState)
352 {
353 return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
354 }
355
356 public virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
357 {
358 return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState);
359 }
360
361 public virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
362 {
363 return System.Threading.Tasks.TaskToApm.Begin(AuthenticateAsServerAsync(credential, policy, requiredProtectionLevel, requiredImpersonationLevel), asyncCallback, asyncState);
364 }
365
370
371 public virtual void AuthenticateAsClient()
372 {
374 }
375
376 public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName)
377 {
378 AuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
379 }
380
381 public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName)
382 {
383 AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
384 }
385
386 public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
387 {
388 AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
389 }
390
391 public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
392 {
393 ValidateCreateContext("Negotiate", isServer: false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
394 AuthenticateAsync(new SyncReadWriteAdapter(base.InnerStream), "AuthenticateAsClient").GetAwaiter().GetResult();
395 }
396
398 {
400 }
401
402 public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName)
403 {
404 return AuthenticateAsClientAsync(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
405 }
406
407 public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
408 {
409 return AuthenticateAsClientAsync(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
410 }
411
412 public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding? binding, string targetName)
413 {
414 return AuthenticateAsClientAsync(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
415 }
416
417 public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
418 {
419 ValidateCreateContext("Negotiate", isServer: false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
420 return AuthenticateAsync(new AsyncReadWriteAdapter(base.InnerStream, default(CancellationToken)), "AuthenticateAsClientAsync");
421 }
422
427
432
433 public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
434 {
435 return AuthenticateAsServerAsync(credential, null, requiredProtectionLevel, requiredImpersonationLevel);
436 }
437
438 public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
439 {
440 ValidateCreateContext("Negotiate", credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
441 return AuthenticateAsync(new AsyncReadWriteAdapter(base.InnerStream, default(CancellationToken)), "AuthenticateAsServerAsync");
442 }
443
444 public override void SetLength(long value)
445 {
446 base.InnerStream.SetLength(value);
447 }
448
449 public override long Seek(long offset, SeekOrigin origin)
450 {
452 }
453
454 public override void Flush()
455 {
456 base.InnerStream.Flush();
457 }
458
460 {
461 return base.InnerStream.FlushAsync(cancellationToken);
462 }
463
464 public override int Read(byte[] buffer, int offset, int count)
465 {
467 ThrowIfFailed(authSuccessCheck: true);
469 {
470 return base.InnerStream.Read(buffer, offset, count);
471 }
472 return ReadAsync(new SyncReadWriteAdapter(base.InnerStream), new Memory<byte>(buffer, offset, count), "Read").GetAwaiter().GetResult();
473 }
474
476 {
478 ThrowIfFailed(authSuccessCheck: true);
480 {
481 return base.InnerStream.ReadAsync(buffer, offset, count, cancellationToken);
482 }
483 return ReadAsync(new AsyncReadWriteAdapter(base.InnerStream, cancellationToken), new Memory<byte>(buffer, offset, count), "ReadAsync").AsTask();
484 }
485
487 {
488 ThrowIfFailed(authSuccessCheck: true);
490 {
491 return base.InnerStream.ReadAsync(buffer, cancellationToken);
492 }
493 return ReadAsync(new AsyncReadWriteAdapter(base.InnerStream, cancellationToken), buffer, "ReadAsync");
494 }
495
496 private async ValueTask<int> ReadAsync<TAdapter>(TAdapter adapter, Memory<byte> buffer, [CallerMemberName] string callerName = null) where TAdapter : IReadWriteAdapter
497 {
498 if (Interlocked.Exchange(ref _readInProgress, 1) == 1)
499 {
501 }
502 try
503 {
504 if (_readBufferCount != 0)
505 {
506 int num = Math.Min(_readBufferCount, buffer.Length);
507 if (num != 0)
508 {
509 _readBuffer.AsMemory(_readBufferOffset, num).CopyTo(buffer);
510 _readBufferOffset += num;
511 _readBufferCount -= num;
512 }
513 return num;
514 }
515 int num2;
516 do
517 {
518 if (await ReadAllAsync(adapter, _readHeader, allowZeroRead: true).ConfigureAwait(continueOnCapturedContext: false) == 0)
519 {
520 return 0;
521 }
523 if (num2 <= 4 || num2 > 65536)
524 {
526 }
527 _readBufferCount = num2;
529 if (_readBuffer.Length < num2)
530 {
531 _readBuffer = new byte[num2];
532 }
533 num2 = await ReadAllAsync(adapter, new Memory<byte>(_readBuffer, 0, num2), allowZeroRead: false).ConfigureAwait(continueOnCapturedContext: false);
535 }
536 while (num2 == 0 && buffer.Length != 0);
537 if (num2 > buffer.Length)
538 {
539 num2 = buffer.Length;
540 }
541 _readBuffer.AsMemory(_readBufferOffset, num2).CopyTo(buffer);
542 _readBufferOffset += num2;
543 _readBufferCount -= num2;
544 return num2;
545 }
546 catch (Exception ex) when (!(ex is IOException) && !(ex is OperationCanceledException))
547 {
548 throw new IOException(System.SR.net_io_read, ex);
549 }
550 finally
551 {
552 _readInProgress = 0;
553 }
554 static async ValueTask<int> ReadAllAsync(TAdapter adapter, Memory<byte> buffer, bool allowZeroRead)
555 {
556 int read = 0;
557 do
558 {
559 int num3 = await adapter.ReadAsync(buffer).ConfigureAwait(continueOnCapturedContext: false);
560 if (num3 == 0)
561 {
562 if (read == 0 && allowZeroRead)
563 {
564 break;
565 }
566 throw new IOException(System.SR.net_io_eof);
567 }
568 buffer = buffer.Slice(num3);
569 read += num3;
570 }
571 while (!buffer.IsEmpty);
572 return read;
573 }
574 }
575
576 public override void Write(byte[] buffer, int offset, int count)
577 {
579 ThrowIfFailed(authSuccessCheck: true);
581 {
582 base.InnerStream.Write(buffer, offset, count);
583 }
584 else
585 {
586 WriteAsync(new SyncReadWriteAdapter(base.InnerStream), new ReadOnlyMemory<byte>(buffer, offset, count)).GetAwaiter().GetResult();
587 }
588 }
589
591 {
593 ThrowIfFailed(authSuccessCheck: true);
595 {
596 return base.InnerStream.WriteAsync(buffer, offset, count, cancellationToken);
597 }
599 }
600
602 {
603 ThrowIfFailed(authSuccessCheck: true);
605 {
606 return base.InnerStream.WriteAsync(buffer, cancellationToken);
607 }
608 return new ValueTask(WriteAsync(new AsyncReadWriteAdapter(base.InnerStream, cancellationToken), buffer));
609 }
610
611 private async Task WriteAsync<TAdapter>(TAdapter adapter, ReadOnlyMemory<byte> buffer) where TAdapter : IReadWriteAdapter
612 {
613 if (Interlocked.Exchange(ref _writeInProgress, 1) == 1)
614 {
616 }
617 try
618 {
619 while (!buffer.IsEmpty)
620 {
621 int chunkBytes = Math.Min(buffer.Length, 64512);
622 int count;
623 try
624 {
625 count = EncryptData(buffer.Slice(0, chunkBytes).Span, ref _writeBuffer);
626 }
627 catch (Exception innerException)
628 {
629 throw new IOException(System.SR.net_io_encrypt, innerException);
630 }
631 await adapter.WriteAsync(_writeBuffer, 0, count).ConfigureAwait(continueOnCapturedContext: false);
632 buffer = buffer.Slice(chunkBytes);
633 }
634 }
635 catch (Exception ex) when (!(ex is IOException) && !(ex is OperationCanceledException))
636 {
637 throw new IOException(System.SR.net_io_write, ex);
638 }
639 finally
640 {
642 }
643 }
644
645 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState)
646 {
647 return System.Threading.Tasks.TaskToApm.Begin(ReadAsync(buffer, offset, count), asyncCallback, asyncState);
648 }
649
650 public override int EndRead(IAsyncResult asyncResult)
651 {
653 }
654
655 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState)
656 {
657 return System.Threading.Tasks.TaskToApm.Begin(WriteAsync(buffer, offset, count), asyncCallback, asyncState);
658 }
659
664
665 private void ThrowIfExceptional()
666 {
668 if (exception != null)
669 {
670 ThrowExceptional(exception);
671 }
672 static void ThrowExceptional(ExceptionDispatchInfo e)
673 {
674 if (e == s_disposedSentinel)
675 {
676 throw new ObjectDisposedException("NegotiateStream");
677 }
678 e.Throw();
679 }
680 }
681
682 private void ValidateCreateContext(string package, NetworkCredential credential, string servicePrincipalName, ExtendedProtectionPolicy policy, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel)
683 {
684 if (policy != null)
685 {
686 if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null)
687 {
689 }
691 }
692 else
693 {
695 }
696 ValidateCreateContext(package, isServer: true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel);
697 }
698
699 private void ValidateCreateContext(string package, bool isServer, NetworkCredential credential, string servicePrincipalName, ChannelBinding channelBinding, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel)
700 {
702 {
704 }
705 if (_context != null && _context.IsValidContext)
706 {
708 }
709 if (credential == null)
710 {
711 throw new ArgumentNullException("credential");
712 }
713 if (servicePrincipalName == null)
714 {
715 throw new ArgumentNullException("servicePrincipalName");
716 }
718 if (_context != null && IsServer != isServer)
719 {
721 }
722 _exception = null;
723 _remoteOk = false;
724 _framer = new StreamFramer();
725 _framer.WriteHeader.MessageId = 22;
726 _expectedProtectionLevel = protectionLevel;
727 _expectedImpersonationLevel = (isServer ? impersonationLevel : TokenImpersonationLevel.None);
730 ContextFlagsPal contextFlagsPal = ContextFlagsPal.Connection;
731 if (protectionLevel == ProtectionLevel.None && !isServer)
732 {
733 package = "NTLM";
734 }
735 else
736 {
737 switch (protectionLevel)
738 {
739 case ProtectionLevel.EncryptAndSign:
740 contextFlagsPal |= ContextFlagsPal.Confidentiality;
741 break;
742 case ProtectionLevel.Sign:
743 contextFlagsPal |= ContextFlagsPal.ReplayDetect | ContextFlagsPal.SequenceDetect | ContextFlagsPal.AcceptStream;
744 break;
745 }
746 }
747 if (isServer)
748 {
750 {
751 contextFlagsPal |= ContextFlagsPal.AllowMissingBindings;
752 }
754 {
755 contextFlagsPal |= ContextFlagsPal.ProxyBindings;
756 }
757 }
758 else
759 {
760 if (protectionLevel != 0)
761 {
762 contextFlagsPal |= ContextFlagsPal.MutualAuth;
763 }
764 if (impersonationLevel == TokenImpersonationLevel.Identification)
765 {
766 contextFlagsPal |= ContextFlagsPal.AcceptIntegrity;
767 }
768 if (impersonationLevel == TokenImpersonationLevel.Delegation)
769 {
770 contextFlagsPal |= ContextFlagsPal.Delegate;
771 }
772 }
774 try
775 {
776 _context = new NTAuthentication(isServer, package, credential, servicePrincipalName, contextFlagsPal, channelBinding);
777 }
778 catch (Win32Exception innerException)
779 {
780 throw new AuthenticationException(System.SR.net_auth_SSPI, innerException);
781 }
782 }
783
784 private void SetFailed(Exception e)
785 {
787 {
789 }
791 }
792
793 private void ThrowIfFailed(bool authSuccessCheck)
794 {
796 if (authSuccessCheck && !IsAuthenticatedCore)
797 {
799 }
800 }
801
802 private async Task AuthenticateAsync<TAdapter>(TAdapter adapter, [CallerMemberName] string callerName = null) where TAdapter : IReadWriteAdapter
803 {
804 ThrowIfFailed(authSuccessCheck: false);
805 if (Interlocked.Exchange(ref _authInProgress, 1) == 1)
806 {
807 throw new InvalidOperationException(System.SR.Format(System.SR.net_io_invalidnestedcall, callerName, "authenticate"));
808 }
809 try
810 {
811 await (_context.IsServer ? ReceiveBlobAsync(adapter) : SendBlobAsync(adapter, null)).ConfigureAwait(continueOnCapturedContext: false);
812 }
813 catch (Exception failed)
814 {
815 SetFailed(failed);
816 throw;
817 }
818 finally
819 {
820 _authInProgress = 0;
821 }
822 }
823
824 private bool CheckSpn()
825 {
827 {
828 return true;
829 }
830 string clientSpecifiedSpn = _context.ClientSpecifiedSpn;
831 if (string.IsNullOrEmpty(clientSpecifiedSpn))
832 {
833 return _extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported;
834 }
835 return _extendedProtectionPolicy.CustomServiceNames.Contains(clientSpecifiedSpn);
836 }
837
838 private async Task SendBlobAsync<TAdapter>(TAdapter adapter, byte[] message) where TAdapter : IReadWriteAdapter
839 {
840 Exception e = null;
841 if (message != s_emptyMessage)
842 {
843 message = GetOutgoingBlob(message, ref e);
844 }
845 if (e != null)
846 {
847 await SendAuthResetSignalAndThrowAsync(adapter, message, e).ConfigureAwait(continueOnCapturedContext: false);
848 }
850 {
851 if (_context.IsServer && !CheckSpn())
852 {
854 int num = 1790;
855 message = new byte[8];
856 for (int num2 = message.Length - 1; num2 >= 0; num2--)
857 {
858 message[num2] = (byte)((uint)num & 0xFFu);
859 num >>>= 8;
860 }
861 await SendAuthResetSignalAndThrowAsync(adapter, message, e).ConfigureAwait(continueOnCapturedContext: false);
862 }
864 {
866 int num3 = 1790;
867 message = new byte[8];
868 for (int num4 = message.Length - 1; num4 >= 0; num4--)
869 {
870 message[num4] = (byte)((uint)num3 & 0xFFu);
871 num3 >>>= 8;
872 }
873 await SendAuthResetSignalAndThrowAsync(adapter, message, e).ConfigureAwait(continueOnCapturedContext: false);
874 }
875 ProtectionLevel protectionLevel = (_context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : (_context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None));
876 if (protectionLevel < _expectedProtectionLevel)
877 {
879 int num5 = 1790;
880 message = new byte[8];
881 for (int num6 = message.Length - 1; num6 >= 0; num6--)
882 {
883 message[num6] = (byte)((uint)num5 & 0xFFu);
884 num5 >>>= 8;
885 }
886 await SendAuthResetSignalAndThrowAsync(adapter, message, e).ConfigureAwait(continueOnCapturedContext: false);
887 }
888 _framer.WriteHeader.MessageId = 20;
889 if (_context.IsServer)
890 {
891 _remoteOk = true;
892 if (message == null)
893 {
894 message = s_emptyMessage;
895 }
896 }
897 }
898 else if (message == null || message == s_emptyMessage)
899 {
900 throw new InternalException();
901 }
902 if (message != null)
903 {
904 await _framer.WriteMessageAsync(adapter, message).ConfigureAwait(continueOnCapturedContext: false);
905 }
907 {
908 await ReceiveBlobAsync(adapter).ConfigureAwait(continueOnCapturedContext: false);
909 }
910 }
911
912 private async Task ReceiveBlobAsync<TAdapter>(TAdapter adapter) where TAdapter : IReadWriteAdapter
913 {
914 byte[] array = await _framer.ReadMessageAsync(adapter).ConfigureAwait(continueOnCapturedContext: false);
915 if (array == null)
916 {
918 }
919 if (_framer.ReadHeader.MessageId == 21)
920 {
921 if (array.Length >= 8)
922 {
923 long num = 0L;
924 for (int i = 0; i < 8; i++)
925 {
926 num = (num << 8) + array[i];
927 }
929 }
931 }
932 if (_framer.ReadHeader.MessageId == 20)
933 {
934 _remoteOk = true;
935 }
936 else if (_framer.ReadHeader.MessageId != 22)
937 {
939 }
941 {
942 if (!_remoteOk)
943 {
945 }
946 }
947 else
948 {
949 await SendBlobAsync(adapter, array).ConfigureAwait(continueOnCapturedContext: false);
950 }
951 }
952
953 private async Task SendAuthResetSignalAndThrowAsync<TAdapter>(TAdapter adapter, byte[] message, Exception exception) where TAdapter : IReadWriteAdapter
954 {
955 _framer.WriteHeader.MessageId = 21;
957 {
959 }
961 {
963 }
964 await _framer.WriteMessageAsync(adapter, message).ConfigureAwait(continueOnCapturedContext: false);
967 }
968
969 private static bool IsError(SecurityStatusPal status)
970 {
971 return status.ErrorCode >= SecurityStatusPalErrorCode.OutOfMemory;
972 }
973
974 private byte[] GetOutgoingBlob(byte[] incomingBlob, ref Exception e)
975 {
976 SecurityStatusPal statusCode;
977 byte[] array = _context.GetOutgoingBlob(incomingBlob, throwOnError: false, out statusCode);
978 if (IsError(statusCode))
979 {
981 uint num = (uint)e.HResult;
982 array = new byte[8];
983 for (int num2 = array.Length - 1; num2 >= 0; num2--)
984 {
985 array[num2] = (byte)(num & 0xFFu);
986 num >>= 8;
987 }
988 }
989 if (array != null && array.Length == 0)
990 {
992 }
993 return array;
994 }
995
996 private int EncryptData(ReadOnlySpan<byte> buffer, [NotNull] ref byte[] outBuffer)
997 {
998 ThrowIfFailed(authSuccessCheck: true);
1000 return _context.Encrypt(buffer, ref outBuffer, _writeSequenceNumber);
1001 }
1002
1003 private int DecryptData(byte[] buffer, int offset, int count, out int newOffset)
1004 {
1005 ThrowIfFailed(authSuccessCheck: true);
1007 return _context.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber);
1008 }
1009
1010 private static void ThrowCredentialException(long error)
1011 {
1012 Win32Exception ex = new Win32Exception((int)error);
1013 throw ex.NativeErrorCode switch
1014 {
1018 };
1019 }
1020
1022 {
1023 if (exception is Win32Exception ex)
1024 {
1025 return ex.NativeErrorCode == 21;
1026 }
1027 return false;
1028 }
1029}
static int ToInt32(byte[] value, int startIndex)
static void ValidateBufferArguments(byte[] buffer, int offset, int count)
Definition Stream.cs:1044
static byte Min(byte val1, byte val2)
Definition Math.cs:912
static ICredentials DefaultCredentials
string GetOutgoingBlob(string incomingBlob)
int Encrypt(ReadOnlySpan< byte > buffer, [NotNull] ref byte[] output, uint sequenceNumber)
int Decrypt(byte[] payload, int offset, int count, out int newOffset, uint expectedSeqNumber)
static void ValidateImpersonationLevel(TokenImpersonationLevel impersonationLevel)
static IIdentity GetIdentity(NTAuthentication context)
static Win32Exception CreateExceptionFromError(System.Net.SecurityStatusPal statusCode)
virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName)
TokenImpersonationLevel PrivateImpersonationLevel
virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback? asyncCallback, object? asyncState)
virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName)
virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy? policy, AsyncCallback? asyncCallback, object? asyncState)
ExtendedProtectionPolicy _extendedProtectionPolicy
virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState)
async Task ReceiveBlobAsync< TAdapter >(TAdapter adapter)
override int EndRead(IAsyncResult asyncResult)
void ValidateCreateContext(string package, bool isServer, NetworkCredential credential, string servicePrincipalName, ChannelBinding channelBinding, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel)
int DecryptData(byte[] buffer, int offset, int count, out int newOffset)
async Task SendBlobAsync< TAdapter >(TAdapter adapter, byte[] message)
static bool IsLogonDeniedException(Exception exception)
virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
virtual void AuthenticateAsServer(ExtendedProtectionPolicy? policy)
override void Dispose(bool disposing)
virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
async Task WriteAsync< TAdapter >(TAdapter adapter, ReadOnlyMemory< byte > buffer)
override void EndWrite(IAsyncResult asyncResult)
override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
async Task SendAuthResetSignalAndThrowAsync< TAdapter >(TAdapter adapter, byte[] message, Exception exception)
static bool IsError(SecurityStatusPal status)
override Task< int > ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
void ThrowIfFailed(bool authSuccessCheck)
virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
override async ValueTask DisposeAsync()
void ValidateCreateContext(string package, NetworkCredential credential, string servicePrincipalName, ExtendedProtectionPolicy policy, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel)
virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback? asyncCallback, object? asyncState)
virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding? binding, string targetName)
virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
virtual void AuthenticateAsClient(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
override void Write(byte[] buffer, int offset, int count)
override int Read(byte[] buffer, int offset, int count)
virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy? policy)
virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
TokenImpersonationLevel _expectedImpersonationLevel
virtual void AuthenticateAsClient(NetworkCredential credential, string targetName)
virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, AsyncCallback? asyncCallback, object? asyncState)
virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback? asyncCallback, object? asyncState)
async Task AuthenticateAsync< TAdapter >(TAdapter adapter, [CallerMemberName] string callerName=null)
virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback? asyncCallback, object? asyncState)
async ValueTask< int > ReadAsync< TAdapter >(TAdapter adapter, Memory< byte > buffer, [CallerMemberName] string callerName=null)
static void ThrowCredentialException(long error)
static readonly ExceptionDispatchInfo s_disposedSentinel
int EncryptData(ReadOnlySpan< byte > buffer, [NotNull] ref byte[] outBuffer)
virtual void EndAuthenticateAsClient(IAsyncResult asyncResult)
override long Seek(long offset, SeekOrigin origin)
override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState)
override void SetLength(long value)
override ValueTask< int > ReadAsync(Memory< byte > buffer, CancellationToken cancellationToken=default(CancellationToken))
static readonly byte[] s_emptyMessage
byte[] GetOutgoingBlob(byte[] incomingBlob, ref Exception e)
NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen)
override ValueTask WriteAsync(ReadOnlyMemory< byte > buffer, CancellationToken cancellationToken=default(CancellationToken))
override Task FlushAsync(CancellationToken cancellationToken)
static ExceptionDispatchInfo Capture(Exception source)
static string net_auth_eof
Definition SR.cs:74
static string net_frame_read_size
Definition SR.cs:86
static string net_io_invalidnestedcall
Definition SR.cs:24
static string net_auth_client_server
Definition SR.cs:70
static string Format(string resourceFormat, object p1)
Definition SR.cs:118
static string net_io_encrypt
Definition SR.cs:32
static string net_auth_noauth
Definition SR.cs:68
static string net_auth_reauth
Definition SR.cs:66
static string net_auth_bad_client_creds_or_target_mismatch
Definition SR.cs:58
static string net_io_eof
Definition SR.cs:40
static string net_io_header_id
Definition SR.cs:28
static string net_auth_alert
Definition SR.cs:78
static string net_auth_SSPI
Definition SR.cs:72
static string net_auth_context_expectation
Definition SR.cs:60
static string net_auth_bad_client_creds
Definition SR.cs:56
static string net_auth_must_specify_extended_protection_scheme
Definition SR.cs:82
static string net_io_read
Definition SR.cs:36
static string net_auth_context_expectation_remote
Definition SR.cs:62
static string net_io_write
Definition SR.cs:38
static string net_noseek
Definition SR.cs:114
Definition SR.cs:7
static int Exchange(ref int location1, int value)
static IAsyncResult Begin(Task task, AsyncCallback callback, object state)
Definition TaskToApm.cs:43
static void End(IAsyncResult asyncResult)
Definition TaskToApm.cs:48
new TaskAwaiter< TResult > GetAwaiter()
Definition Task.cs:221
ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
Definition ValueTask.cs:312