diff --git a/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs b/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs index fcd925a50b016a..7484ad270655c5 100644 --- a/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs +++ b/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - +#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -301,8 +301,8 @@ internal static void SslSetTargetName(SafeSslHandle sslHandle, string targetName internal static unsafe void SslCtxSetAlpnProtos(SafeSslHandle ctx, List protocols) { - SafeCreateHandle cfProtocolsRefs = null; - SafeCreateHandle[] cfProtocolsArrayRef = null; + SafeCreateHandle? cfProtocolsRefs = null; + SafeCreateHandle[]? cfProtocolsArrayRef = null; try { if (protocols.Count == 1 && protocols[0] == SslApplicationProtocol.Http2) @@ -353,7 +353,7 @@ internal static unsafe void SslCtxSetAlpnProtos(SafeSslHandle ctx, List= 1 && cipherList[cipherList.Length - 1] == 0)); - byte[] cipherSuites = + byte[]? cipherSuites = CipherSuitesPolicyPal.GetOpenSslCipherSuites(sslAuthenticationOptions.CipherSuitesPolicy, protocols, policy); Debug.Assert(cipherSuites == null || (cipherSuites.Length >= 1 && cipherSuites[cipherSuites.Length - 1] == 0)); @@ -151,7 +152,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 if (hasCertificateAndKey) { - SetSslCertificate(innerContext, certHandle, certKeyHandle); + SetSslCertificate(innerContext, certHandle!, certKeyHandle!); } if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) @@ -189,7 +190,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 if (!sslAuthenticationOptions.IsServer) { // The IdnMapping converts unicode input into the IDNA punycode sequence. - string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost); + string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost!); // Similar to windows behavior, set SNI on openssl by default for client context, ignore errors. if (!Ssl.SslSetTlsExtHostName(context, punyCode)) @@ -203,10 +204,10 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 bool hasCertReference = false; try { - certHandle.DangerousAddRef(ref hasCertReference); + certHandle!.DangerousAddRef(ref hasCertReference); using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle())) { - X509Chain chain = null; + X509Chain? chain = null; try { chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false); @@ -222,7 +223,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) { - chain.ChainElements[i].Certificate.Dispose(); + chain.ChainElements[i].Certificate!.Dispose(); } chain.Dispose(); @@ -233,7 +234,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 finally { if (hasCertReference) - certHandle.DangerousRelease(); + certHandle!.DangerousRelease(); } } @@ -253,15 +254,15 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 return context; } - internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan input, out byte[] sendBuf, out int sendCount) + internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan input, out byte[]? sendBuf, out int sendCount) { sendBuf = null; sendCount = 0; - Exception handshakeException = null; + Exception? handshakeException = null; if (input.Length > 0) { - if (Ssl.BioWrite(context.InputBio, ref MemoryMarshal.GetReference(input), input.Length) != input.Length) + if (Ssl.BioWrite(context.InputBio!, ref MemoryMarshal.GetReference(input), input.Length) != input.Length) { // Make sure we clear out the error that is stored in the queue throw Crypto.CreateOpenSslCryptographicException(); @@ -271,7 +272,7 @@ internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan in int retVal = Ssl.SslDoHandshake(context); if (retVal != 1) { - Exception innerError; + Exception? innerError; Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError); if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) @@ -283,14 +284,14 @@ internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan in } } - sendCount = Crypto.BioCtrlPending(context.OutputBio); + sendCount = Crypto.BioCtrlPending(context.OutputBio!); if (sendCount > 0) { sendBuf = new byte[sendCount]; try { - sendCount = BioRead(context.OutputBio, sendBuf, sendCount); + sendCount = BioRead(context.OutputBio!, sendBuf, sendCount); } catch (Exception) when (handshakeException != null) { @@ -330,7 +331,7 @@ internal static int Encrypt(SafeSslHandle context, ReadOnlySpan input, ref errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal; - Exception innerError = null; + Exception? innerError = null; lock (context) { @@ -359,14 +360,14 @@ internal static int Encrypt(SafeSslHandle context, ReadOnlySpan input, ref } else { - int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio); + int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio!); if (output == null || output.Length < capacityNeeded) { output = new byte[capacityNeeded]; } - retVal = BioRead(context.OutputBio, output, capacityNeeded); + retVal = BioRead(context.OutputBio!, output, capacityNeeded); if (retVal <= 0) { @@ -386,8 +387,8 @@ internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, #endif errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; - int retVal = BioWrite(context.InputBio, outBuffer, offset, count); - Exception innerError = null; + int retVal = BioWrite(context.InputBio!, outBuffer, offset, count); + Exception? innerError = null; lock (context) { @@ -561,7 +562,7 @@ private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int co return bytes; } - private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError) + private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception? innerError) { ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it @@ -633,17 +634,17 @@ internal static SslException CreateSslException(string message) internal sealed class SslException : Exception { - public SslException(string inputMessage) + public SslException(string? inputMessage) : base(inputMessage) { } - public SslException(string inputMessage, Exception ex) + public SslException(string? inputMessage, Exception? ex) : base(inputMessage, ex) { } - public SslException(string inputMessage, int error) + public SslException(string? inputMessage, int error) : this(inputMessage) { HResult = error; diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs index 2246b5f4bf9a74..b7edaf3919684b 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Net.Security; @@ -57,7 +58,7 @@ internal static partial class Ssl [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")] internal static extern void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len); - internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl) + internal static byte[]? SslGetAlpnSelected(SafeSslHandle ssl) { IntPtr protocol; int len; @@ -133,9 +134,9 @@ internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl) [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetOpenSslCipherSuiteName")] private static extern IntPtr GetOpenSslCipherSuiteName(SafeSslHandle ssl, int cipherSuite, out int isTls12OrLower); - internal static string GetOpenSslCipherSuiteName(SafeSslHandle ssl, TlsCipherSuite cipherSuite, out bool isTls12OrLower) + internal static string? GetOpenSslCipherSuiteName(SafeSslHandle ssl, TlsCipherSuite cipherSuite, out bool isTls12OrLower) { - string ret = Marshal.PtrToStringAnsi(GetOpenSslCipherSuiteName(ssl, (int)cipherSuite, out int isTls12OrLowerInt)); + string? ret = Marshal.PtrToStringAnsi(GetOpenSslCipherSuiteName(ssl, (int)cipherSuite, out int isTls12OrLowerInt)); isTls12OrLower = isTls12OrLowerInt != 0; return ret; } @@ -178,7 +179,7 @@ internal static bool AddExtraChainCertificates(SafeSslHandle sslContext, X509Cha // Don't include the first item (the cert whose private key we have) for (int i = 1; i < stop; i++) { - SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate.Handle); + SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate!.Handle); Crypto.CheckValidOpenSslHandle(dupCertHandle); if (!SslAddExtraChainCert(sslContext, dupCertHandle)) { @@ -219,8 +220,8 @@ namespace Microsoft.Win32.SafeHandles { internal sealed class SafeSslHandle : SafeHandle { - private SafeBioHandle _readBio; - private SafeBioHandle _writeBio; + private SafeBioHandle? _readBio; + private SafeBioHandle? _writeBio; private bool _isServer; private bool _handshakeCompleted = false; @@ -231,7 +232,7 @@ public bool IsServer get { return _isServer; } } - public SafeBioHandle InputBio + public SafeBioHandle? InputBio { get { @@ -239,7 +240,7 @@ public SafeBioHandle InputBio } } - public SafeBioHandle OutputBio + public SafeBioHandle? OutputBio { get { diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/ISSPIInterface.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/ISSPIInterface.cs index 20cd29588f9a10..ee81875cee8354 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/ISSPIInterface.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/ISSPIInterface.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Net.Security; using System.Runtime.InteropServices; @@ -10,22 +11,22 @@ namespace System.Net // SspiCli SSPI interface. internal interface ISSPIInterface { - SecurityPackageInfoClass[] SecurityPackages { get; set; } + SecurityPackageInfoClass[]? SecurityPackages { get; set; } int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray); int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.CredentialUse usage, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential); int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.CredentialUse usage, ref Interop.SspiCli.SCHANNEL_CRED authdata, out SafeFreeCredentials outCredential); int AcquireDefaultCredential(string moduleName, Interop.SspiCli.CredentialUse usage, out SafeFreeCredentials outCredential); - int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteSslContext context, InputSecurityBuffers inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags); - int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteSslContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags); + int AcceptSecurityContext(SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, InputSecurityBuffers inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags); + int InitializeSecurityContext(ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags); int EncryptMessage(SafeDeleteContext context, ref Interop.SspiCli.SecBufferDesc inputOutput, uint sequenceNumber); int DecryptMessage(SafeDeleteContext context, ref Interop.SspiCli.SecBufferDesc inputOutput, uint sequenceNumber); int MakeSignature(SafeDeleteContext context, ref Interop.SspiCli.SecBufferDesc inputOutput, uint sequenceNumber); int VerifySignature(SafeDeleteContext context, ref Interop.SspiCli.SecBufferDesc inputOutput, uint sequenceNumber); int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding refHandle); - int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute attribute, Span buffer, Type handleType, out SafeHandle refHandle); + int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute attribute, Span buffer, Type? handleType, out SafeHandle? refHandle); int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken); - int CompleteAuthToken(ref SafeDeleteSslContext refContext, in SecurityBuffer inputBuffer); - int ApplyControlToken(ref SafeDeleteContext refContext, in SecurityBuffer inputBuffer); + int CompleteAuthToken(ref SafeDeleteSslContext? refContext, in SecurityBuffer inputBuffer); + int ApplyControlToken(ref SafeDeleteContext? refContext, in SecurityBuffer inputBuffer); } } diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs index 95ff08ff76a787..61ca04f896cddd 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Net.Security; using System.Runtime.CompilerServices; @@ -307,7 +308,7 @@ internal static extern int EnumerateSecurityPackagesW( [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( - [In] string principal, + [In] string? principal, [In] string moduleName, [In] int usage, [In] void* logonID, @@ -320,7 +321,7 @@ [Out] out long timeStamp [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( - [In] string principal, + [In] string? principal, [In] string moduleName, [In] int usage, [In] void* logonID, @@ -333,7 +334,7 @@ [Out] out long timeStamp [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( - [In] string principal, + [In] string? principal, [In] string moduleName, [In] int usage, [In] void* logonID, diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/NegotiationInfoClass.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/NegotiationInfoClass.cs index ffe7759b2a1ff9..6cce8e0c31e94b 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/NegotiationInfoClass.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/NegotiationInfoClass.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System.Net @@ -10,7 +11,7 @@ namespace System.Net // Kerberos are used in the context of a Negotiate handshake internal static partial class NegotiationInfoClass { - internal static string GetAuthenticationPackageName(SafeHandle safeHandle, int negotiationState) + internal static string? GetAuthenticationPackageName(SafeHandle safeHandle, int negotiationState) { if (safeHandle.IsInvalid) { @@ -28,7 +29,7 @@ internal static string GetAuthenticationPackageName(SafeHandle safeHandle, int n if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE || negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC) { - string name; + string? name; unsafe { name = Marshal.PtrToStringUni(((SecurityPackageInfo*)packageInfo)->Name); diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIAuthType.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIAuthType.cs index 10e9e6d0321dde..f5a06cc9b65f72 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIAuthType.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIAuthType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Net.Security; using System.Runtime.InteropServices; @@ -10,9 +11,9 @@ namespace System.Net // Authentication SSPI (Kerberos, NTLM, Negotiate and WDigest): internal sealed class SSPIAuthType : ISSPIInterface { - private static volatile SecurityPackageInfoClass[] s_securityPackages; + private static volatile SecurityPackageInfoClass[]? s_securityPackages; - public SecurityPackageInfoClass[] SecurityPackages + public SecurityPackageInfoClass[]? SecurityPackages { get { @@ -45,12 +46,12 @@ public int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.Credentia return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } - public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteSslContext context, InputSecurityBuffers inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) + public int AcceptSecurityContext(SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, InputSecurityBuffers inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, inputBuffers, ref outputBuffer, ref outFlags); } - public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteSslContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) + public int InitializeSecurityContext(ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, inputBuffers, ref outputBuffer, ref outFlags); } @@ -133,7 +134,7 @@ public int QueryContextChannelBinding(SafeDeleteContext context, Interop.SspiCli throw new NotSupportedException(); } - public unsafe int QueryContextAttributes(SafeDeleteContext context, Interop.SspiCli.ContextAttribute attribute, Span buffer, Type handleType, out SafeHandle refHandle) + public unsafe int QueryContextAttributes(SafeDeleteContext context, Interop.SspiCli.ContextAttribute attribute, Span buffer, Type? handleType, out SafeHandle? refHandle) { refHandle = null; if (handleType != null) @@ -163,7 +164,7 @@ public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityCo return GetSecurityContextToken(phContext, out phToken); } - public int CompleteAuthToken(ref SafeDeleteSslContext refContext, in SecurityBuffer inputBuffer) + public int CompleteAuthToken(ref SafeDeleteSslContext? refContext, in SecurityBuffer inputBuffer) { return SafeDeleteContext.CompleteAuthToken(ref refContext, in inputBuffer); } @@ -182,7 +183,7 @@ private static int GetSecurityContextToken(SafeDeleteContext phContext, out Secu } } - public int ApplyControlToken(ref SafeDeleteContext refContext, in SecurityBuffer inputBuffers) + public int ApplyControlToken(ref SafeDeleteContext? refContext, in SecurityBuffer inputBuffers) { throw new NotSupportedException(); } diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SSPISecureChannelType.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SSPISecureChannelType.cs index e3832d8c3cdba5..ff73238161bab4 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SSPISecureChannelType.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SSPISecureChannelType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Net.Security; using System.Runtime.InteropServices; @@ -10,9 +11,9 @@ namespace System.Net // Schannel SSPI interface. internal sealed class SSPISecureChannelType : ISSPIInterface { - private static volatile SecurityPackageInfoClass[] s_securityPackages; + private static volatile SecurityPackageInfoClass[]? s_securityPackages; - public SecurityPackageInfoClass[] SecurityPackages + public SecurityPackageInfoClass[]? SecurityPackages { get { @@ -45,12 +46,12 @@ public int AcquireCredentialsHandle(string moduleName, Interop.SspiCli.Credentia return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } - public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteSslContext context, InputSecurityBuffers inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) + public int AcceptSecurityContext(SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, InputSecurityBuffers inputBuffers, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, inputBuffers, ref outputBuffer, ref outFlags); } - public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteSslContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) + public int InitializeSecurityContext(ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, inputBuffers, ref outputBuffer, ref outFlags); } @@ -103,7 +104,7 @@ public unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Intero return SafeFreeContextBufferChannelBinding.QueryContextChannelBinding(phContext, attribute, &bindings, refHandle); } - public unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute attribute, Span buffer, Type handleType, out SafeHandle refHandle) + public unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute attribute, Span buffer, Type? handleType, out SafeHandle? refHandle) { refHandle = null; if (handleType != null) @@ -132,12 +133,12 @@ public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityCo throw new NotSupportedException(); } - public int CompleteAuthToken(ref SafeDeleteSslContext refContext, in SecurityBuffer inputBuffer) + public int CompleteAuthToken(ref SafeDeleteSslContext? refContext, in SecurityBuffer inputBuffer) { throw new NotSupportedException(); } - public int ApplyControlToken(ref SafeDeleteContext refContext, in SecurityBuffer inputBuffer) + public int ApplyControlToken(ref SafeDeleteContext? refContext, in SecurityBuffer inputBuffer) { return SafeDeleteContext.ApplyControlToken(ref refContext, in inputBuffer); } diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIWrapper.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIWrapper.cs index 79e004c6476fa2..b6f80179a7593c 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIWrapper.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SSPIWrapper.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; using System.Diagnostics; using System.Globalization; @@ -23,7 +24,7 @@ internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(ISSPIInterf if (secModule.SecurityPackages == null) { int moduleCount = 0; - SafeFreeContextBuffer arrayBaseHandle = null; + SafeFreeContextBuffer? arrayBaseHandle = null; try { int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle); @@ -56,7 +57,7 @@ internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(ISSPIInterf return secModule.SecurityPackages; } - internal static SecurityPackageInfoClass GetVerifyPackageInfo(ISSPIInterface secModule, string packageName, bool throwIfMissing) + internal static SecurityPackageInfoClass? GetVerifyPackageInfo(ISSPIInterface secModule, string packageName, bool throwIfMissing) { SecurityPackageInfoClass[] supportedSecurityPackages = EnumerateSecurityPackages(secModule); if (supportedSecurityPackages != null) @@ -88,7 +89,7 @@ public static SafeFreeCredentials AcquireDefaultCredential(ISSPIInterface secMod NetEventSource.Log.AcquireDefaultCredential(package, intent); } - SafeFreeCredentials outCredential = null; + SafeFreeCredentials? outCredential = null; int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential); if (errorCode != 0) @@ -103,7 +104,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle(ISSPIInterface secMod { if (NetEventSource.IsEnabled) NetEventSource.Log.AcquireCredentialsHandle(package, intent, authdata); - SafeFreeCredentials credentialsHandle = null; + SafeFreeCredentials? credentialsHandle = null; int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle); if (errorCode != 0) @@ -123,7 +124,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle(ISSPIInterface secMod NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc); } - SafeFreeCredentials outCredential = null; + SafeFreeCredentials? outCredential = null; int errorCode = secModule.AcquireCredentialsHandle( package, intent, @@ -140,7 +141,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle(ISSPIInterface secMod return outCredential; } - internal static int InitializeSecurityContext(ISSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteSslContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) + internal static int InitializeSecurityContext(ISSPIInterface secModule, ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { if (NetEventSource.IsEnabled) NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags); @@ -151,7 +152,7 @@ internal static int InitializeSecurityContext(ISSPIInterface secModule, ref Safe return errorCode; } - internal static int AcceptSecurityContext(ISSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteSslContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) + internal static int AcceptSecurityContext(ISSPIInterface secModule, SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, InputSecurityBuffers inputBuffers, ref SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags) { if (NetEventSource.IsEnabled) NetEventSource.Log.AcceptSecurityContext(credential, context, inFlags); @@ -162,7 +163,7 @@ internal static int AcceptSecurityContext(ISSPIInterface secModule, SafeFreeCred return errorCode; } - internal static int CompleteAuthToken(ISSPIInterface secModule, ref SafeDeleteSslContext context, in SecurityBuffer inputBuffer) + internal static int CompleteAuthToken(ISSPIInterface secModule, ref SafeDeleteSslContext? context, in SecurityBuffer inputBuffer) { int errorCode = secModule.CompleteAuthToken(ref context, in inputBuffer); @@ -171,7 +172,7 @@ internal static int CompleteAuthToken(ISSPIInterface secModule, ref SafeDeleteSs return errorCode; } - internal static int ApplyControlToken(ISSPIInterface secModule, ref SafeDeleteContext context, in SecurityBuffer inputBuffer) + internal static int ApplyControlToken(ISSPIInterface secModule, ref SafeDeleteContext? context, in SecurityBuffer inputBuffer) { int errorCode = secModule.ApplyControlToken(ref context, in inputBuffer); @@ -353,7 +354,7 @@ private static unsafe int EncryptDecryptHelper(OP op, ISSPIInterface secModule, } } - public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute) + public static SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute); @@ -383,7 +384,7 @@ public static bool QueryBlittableContextAttributes(ISSPIInterface secModule, securityContext, contextAttribute, MemoryMarshal.AsBytes(span), null, - out SafeHandle sspiHandle); + out SafeHandle? sspiHandle); #if NETSTANDARD2_0 attribute = span[0]; #endif @@ -401,7 +402,7 @@ public static bool QueryBlittableContextAttributes(ISSPIInterface secModule, } } - public static bool QueryBlittableContextAttributes(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, Type safeHandleType, out SafeHandle sspiHandle, ref T attribute) where T : unmanaged + public static bool QueryBlittableContextAttributes(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, Type safeHandleType, out SafeHandle? sspiHandle, ref T attribute) where T : unmanaged { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute); @@ -430,7 +431,7 @@ public static bool QueryBlittableContextAttributes(ISSPIInterface secModule, return true; } - public static string QueryStringContextAttributes(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute) + public static string? QueryStringContextAttributes(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute) { Debug.Assert( contextAttribute == Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES || @@ -444,7 +445,10 @@ public static string QueryStringContextAttributes(ISSPIInterface secModule, Safe contextAttribute, MemoryMarshal.AsBytes(buffer), typeof(SafeFreeContextBuffer), - out SafeHandle sspiHandle); + out SafeHandle? sspiHandle); + + Debug.Assert(sspiHandle != null); + using (sspiHandle) { if (errorCode != 0) @@ -453,13 +457,13 @@ public static string QueryStringContextAttributes(ISSPIInterface secModule, Safe return null; } - string result = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle()); + string? result = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle()); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, result); return result; } } - public static SafeFreeCertContext QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(ISSPIInterface secModule, SafeDeleteContext securityContext) + public static SafeFreeCertContext? QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(ISSPIInterface secModule, SafeDeleteContext securityContext) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); @@ -469,7 +473,7 @@ public static SafeFreeCertContext QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT Interop.SspiCli.ContextAttribute.SECPKG_ATTR_REMOTE_CERT_CONTEXT, MemoryMarshal.AsBytes(buffer), typeof(SafeFreeCertContext), - out SafeHandle sspiHandle); + out SafeHandle? sspiHandle); if (errorCode != 0) { @@ -478,12 +482,12 @@ public static SafeFreeCertContext QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT return null; } - var result = (SafeFreeCertContext)sspiHandle; + var result = (SafeFreeCertContext)sspiHandle!; if (NetEventSource.IsEnabled) NetEventSource.Exit(null, result); return result; } - public static bool QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(ISSPIInterface secModule, SafeDeleteContext securityContext, ref Interop.SspiCli.SecPkgContext_IssuerListInfoEx ctx, out SafeHandle sspiHandle) + public static bool QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(ISSPIInterface secModule, SafeDeleteContext securityContext, ref Interop.SspiCli.SecPkgContext_IssuerListInfoEx ctx, out SafeHandle? sspiHandle) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs index d5931550c573d7..ab509c45306808 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs index 0b6e968388971f..e60c216b9b9f59 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Runtime.InteropServices; @@ -14,8 +15,8 @@ internal class SecurityPackageInfoClass internal short Version = 0; internal short RPCID = 0; internal int MaxToken = 0; - internal string Name = null; - internal string Comment = null; + internal string? Name = null; + internal string? Comment = null; /* This is to support SSL with no client cert. diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs index 02d939392b030e..382d1f6a2979ed 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; @@ -51,7 +52,7 @@ internal void Set(IntPtr value) internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; - SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null; + SafeFreeContextBuffer_SECURITY? pkgArray_SECURITY = null; res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; @@ -75,7 +76,7 @@ internal static SafeFreeContextBuffer CreateEmptyHandle() // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // - public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) + public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle? refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; @@ -335,7 +336,7 @@ internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid // internal SafeFreeCredentials Target; - internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) + internal static SafeCredentialReference? CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) @@ -359,7 +360,7 @@ protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; target?.DangerousRelease(); - Target = null; + Target = null!; return true; } } @@ -387,13 +388,13 @@ internal abstract partial class SafeDeleteContext : SafeHandle private const string dummyStr = " "; private static readonly IdnMapping s_idnMapping = new IdnMapping(); - protected SafeFreeCredentials _EffectiveCredential; + protected SafeFreeCredentials? _EffectiveCredential; //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( - ref SafeFreeCredentials inCredentials, - ref SafeDeleteSslContext refContext, - string targetName, + ref SafeFreeCredentials? inCredentials, + ref SafeDeleteSslContext? refContext, + string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inSecBuffers, @@ -429,7 +430,7 @@ internal static unsafe int InitializeSecurityContext( } // Optional output buffer that may need to be freed. - SafeFreeContextBuffer outFreeContextBuffer = null; + SafeFreeContextBuffer? outFreeContextBuffer = null; try { Span inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[3]; @@ -509,7 +510,7 @@ internal static unsafe int InitializeSecurityContext( inFlags, endianness, &inSecurityBufferDescriptor, - refContext, + refContext!, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); @@ -549,7 +550,7 @@ private static unsafe int MustRunInitializeSecurityContext( SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags attributes, - SafeFreeContextBuffer handleTemplate) + SafeFreeContextBuffer? handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; @@ -630,8 +631,8 @@ private static unsafe int MustRunInitializeSecurityContext( //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( - ref SafeFreeCredentials inCredentials, - ref SafeDeleteSslContext refContext, + ref SafeFreeCredentials? inCredentials, + ref SafeDeleteSslContext? refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inSecBuffers, @@ -667,7 +668,7 @@ internal static unsafe int AcceptSecurityContext( } // Optional output buffer that may need to be freed. - SafeFreeContextBuffer outFreeContextBuffer = null; + SafeFreeContextBuffer? outFreeContextBuffer = null; Span outUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[2]; outUnmanagedBuffer[1].pvBuffer = IntPtr.Zero; try @@ -745,7 +746,7 @@ internal static unsafe int AcceptSecurityContext( &inSecurityBufferDescriptor, inFlags, endianness, - refContext, + refContext!, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); @@ -796,7 +797,7 @@ private static unsafe int MustRunAcceptSecurityContext_SECURITY( SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, - SafeFreeContextBuffer handleTemplate) + SafeFreeContextBuffer? handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; @@ -874,7 +875,7 @@ private static unsafe int MustRunAcceptSecurityContext_SECURITY( } internal static unsafe int CompleteAuthToken( - ref SafeDeleteSslContext refContext, + ref SafeDeleteSslContext? refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.IsEnabled) @@ -920,14 +921,14 @@ internal static unsafe int CompleteAuthToken( bool gotRef = false; try { - refContext.DangerousAddRef(ref gotRef); + refContext!.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { - refContext.DangerousRelease(); + refContext!.DangerousRelease(); } } } @@ -937,7 +938,7 @@ internal static unsafe int CompleteAuthToken( } internal static unsafe int ApplyControlToken( - ref SafeDeleteContext refContext, + ref SafeDeleteContext? refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.IsEnabled) @@ -985,14 +986,14 @@ internal static unsafe int ApplyControlToken( bool gotRef = false; try { - refContext.DangerousAddRef(ref gotRef); + refContext!.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { - refContext.DangerousRelease(); + refContext!.DangerousRelease(); } } } @@ -1075,7 +1076,7 @@ public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, return status; } - public override string ToString() + public override string? ToString() { if (IsInvalid) { diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs index ab22e43d6448a7..8e8dd178b90209 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -76,7 +77,7 @@ internal class SafeGssCredHandle : SafeHandle public static SafeGssCredHandle CreateAcceptor() { - SafeGssCredHandle retHandle = null; + SafeGssCredHandle? retHandle = null; Interop.NetSecurityNative.Status status; Interop.NetSecurityNative.Status minorStatus; @@ -108,7 +109,7 @@ public static SafeGssCredHandle Create(string username, string password, bool is return new SafeGssCredHandle(); } - SafeGssCredHandle retHandle = null; + SafeGssCredHandle? retHandle = null; using (SafeGssNameHandle userHandle = SafeGssNameHandle.CreateUser(username)) { Interop.NetSecurityNative.Status status; diff --git a/src/libraries/Common/src/System/Collections/Generic/BidirectionalDictionary.cs b/src/libraries/Common/src/System/Collections/Generic/BidirectionalDictionary.cs index 32c4463433ee61..6b5923d8f46dc5 100644 --- a/src/libraries/Common/src/System/Collections/Generic/BidirectionalDictionary.cs +++ b/src/libraries/Common/src/System/Collections/Generic/BidirectionalDictionary.cs @@ -2,11 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Collections.Generic { internal sealed class BidirectionalDictionary : IEnumerable> + where T1 : notnull + where T2 : notnull { private readonly Dictionary _forward; private readonly Dictionary _backward; diff --git a/src/libraries/Common/src/System/Net/ArrayBuffer.cs b/src/libraries/Common/src/System/Net/ArrayBuffer.cs index 3ed340eb04e219..ca1a1c4066e505 100644 --- a/src/libraries/Common/src/System/Net/ArrayBuffer.cs +++ b/src/libraries/Common/src/System/Net/ArrayBuffer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; @@ -45,7 +46,7 @@ public void Dispose() if (_usePool) { byte[] array = _bytes; - _bytes = null; + _bytes = null!; if (array != null) { diff --git a/src/libraries/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs b/src/libraries/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs index 8ba682fa1017cf..38c3a40d64884c 100644 --- a/src/libraries/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs +++ b/src/libraries/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; namespace System.Net @@ -13,7 +14,7 @@ namespace System.Net // internal abstract class DebugCriticalHandleMinusOneIsInvalid : CriticalHandleMinusOneIsInvalid { - private string _trace; + private string _trace = null!; protected DebugCriticalHandleMinusOneIsInvalid() : base() { diff --git a/src/libraries/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs b/src/libraries/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs index ff4ea687d2cd87..33bca4dee3f706 100644 --- a/src/libraries/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs +++ b/src/libraries/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; namespace System.Net @@ -13,7 +14,7 @@ namespace System.Net // internal abstract class DebugCriticalHandleZeroOrMinusOneIsInvalid : CriticalHandleZeroOrMinusOneIsInvalid { - private string _trace; + private string _trace = null!; protected DebugCriticalHandleZeroOrMinusOneIsInvalid() : base() { diff --git a/src/libraries/Common/src/System/Net/Http/TlsCertificateExtensions.cs b/src/libraries/Common/src/System/Net/Http/TlsCertificateExtensions.cs index 4183fb1c28564e..16d9a077802c7c 100644 --- a/src/libraries/Common/src/System/Net/Http/TlsCertificateExtensions.cs +++ b/src/libraries/Common/src/System/Net/Http/TlsCertificateExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -36,7 +37,7 @@ private static bool IsClientCertificate(X509Certificate2 cert) // required extension. if (!foundEku) { - X509EnhancedKeyUsageExtension enhancedUsageExt = extension as X509EnhancedKeyUsageExtension; + X509EnhancedKeyUsageExtension? enhancedUsageExt = extension as X509EnhancedKeyUsageExtension; if (enhancedUsageExt != null) { foundEku = true; @@ -56,7 +57,7 @@ private static bool IsClientCertificate(X509Certificate2 cert) // No point going over it if we have already established that our cert has digital signature if (!foundKeyUsages) { - X509KeyUsageExtension usageExt = extension as X509KeyUsageExtension; + X509KeyUsageExtension? usageExt = extension as X509KeyUsageExtension; if (usageExt != null) { foundKeyUsages = true; @@ -73,7 +74,7 @@ private static bool IsClientCertificate(X509Certificate2 cert) return isClientAuth && isDigitalSignature; } - internal static X509Chain BuildNewChain(X509Certificate2 certificate, bool includeClientApplicationPolicy) + internal static X509Chain? BuildNewChain(X509Certificate2 certificate, bool includeClientApplicationPolicy) { var chain = new X509Chain(); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; @@ -100,8 +101,8 @@ internal static X509Chain BuildNewChain(X509Certificate2 certificate, bool inclu /// internal static bool TryFindClientCertificate(this X509Certificate2Collection certificates, ISet allowedIssuers, - out X509Certificate2 clientCertificate, - out X509Chain clientCertChain) + out X509Certificate2? clientCertificate, + out X509Chain? clientCertChain) { clientCertificate = null; clientCertChain = null; @@ -124,7 +125,7 @@ internal static bool TryFindClientCertificate(this X509Certificate2Collection ce return true; } - X509Chain chain = BuildNewChain(cert, includeClientApplicationPolicy: true); + X509Chain? chain = BuildNewChain(cert, includeClientApplicationPolicy: true); if (chain == null) { continue; @@ -142,7 +143,7 @@ internal static bool TryFindClientCertificate(this X509Certificate2Collection ce if (chain.ChainElements.Count > 0 && isComplete) { - X509Certificate2 trustAnchor = chain.ChainElements[chain.ChainElements.Count - 1].Certificate; + X509Certificate2 trustAnchor = chain.ChainElements[chain.ChainElements.Count - 1].Certificate!; if (allowedIssuers.Contains(trustAnchor.SubjectName.Name)) { clientCertificate = cert; diff --git a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs index 5d8d5797f02683..29abfe2c0f8b75 100644 --- a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs +++ b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs @@ -113,7 +113,7 @@ public static void Enter(object? thisOrContextObject, FormattableString? formatt /// The object to log. /// The calling member. [NonEvent] - public static void Enter(object? thisOrContextObject, object arg0, [CallerMemberName] string? memberName = null) + public static void Enter(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null) { DebugValidateArg(thisOrContextObject); DebugValidateArg(arg0); @@ -126,7 +126,7 @@ public static void Enter(object? thisOrContextObject, object arg0, [CallerMember /// The second object to log. /// The calling member. [NonEvent] - public static void Enter(object? thisOrContextObject, object? arg0, object arg1, [CallerMemberName] string? memberName = null) + public static void Enter(object? thisOrContextObject, object? arg0, object? arg1, [CallerMemberName] string? memberName = null) { DebugValidateArg(thisOrContextObject); DebugValidateArg(arg0); @@ -141,7 +141,7 @@ public static void Enter(object? thisOrContextObject, object? arg0, object arg1, /// The third object to log. /// The calling member. [NonEvent] - public static void Enter(object? thisOrContextObject, object arg0, object arg1, object arg2, [CallerMemberName] string? memberName = null) + public static void Enter(object? thisOrContextObject, object? arg0, object? arg1, object? arg2, [CallerMemberName] string? memberName = null) { DebugValidateArg(thisOrContextObject); DebugValidateArg(arg0); @@ -186,7 +186,7 @@ public static void Exit(object? thisOrContextObject, object? arg0, [CallerMember /// A second return value from the member. /// The calling member. [NonEvent] - public static void Exit(object? thisOrContextObject, object arg0, object arg1, [CallerMemberName] string? memberName = null) + public static void Exit(object? thisOrContextObject, object? arg0, object? arg1, [CallerMemberName] string? memberName = null) { DebugValidateArg(thisOrContextObject); DebugValidateArg(arg0); diff --git a/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs b/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs index f47cb85b7d8f9b..03a98ef5aef82a 100644 --- a/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs +++ b/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; @@ -13,21 +14,21 @@ internal partial class NTAuthentication { private bool _isServer; - private SafeFreeCredentials _credentialsHandle; - private SafeDeleteContext _securityContext; - private string _spn; + private SafeFreeCredentials? _credentialsHandle; + private SafeDeleteContext? _securityContext; + private string _spn = null!; private int _tokenSize; private ContextFlagsPal _requestedContextFlags; private ContextFlagsPal _contextFlags; private bool _isCompleted; - private string _package; - private string _lastProtocolName; - private string _protocolName; - private string _clientSpecifiedSpn; + private string _package = null!; + private string? _lastProtocolName; + private string? _protocolName; + private string? _clientSpecifiedSpn; - private ChannelBinding _channelBinding; + private ChannelBinding _channelBinding = null!; // If set, no more calls should be made. internal bool IsCompleted => _isCompleted; @@ -37,7 +38,7 @@ internal partial class NTAuthentication // True indicates this instance is for Server and will use AcceptSecurityContext SSPI API. internal bool IsServer => _isServer; - internal string ClientSpecifiedSpn + internal string? ClientSpecifiedSpn { get { @@ -57,11 +58,11 @@ internal string ProtocolName // Note: May return string.Empty if the auth is not done yet or failed. if (_protocolName == null) { - string negotiationAuthenticationPackage = null; + string? negotiationAuthenticationPackage = null; if (IsValidContext) { - negotiationAuthenticationPackage = NegotiateStreamPal.QueryContextAuthenticationPackage(_securityContext); + negotiationAuthenticationPackage = NegotiateStreamPal.QueryContextAuthenticationPackage(_securityContext!); if (IsCompleted) { _protocolName = negotiationAuthenticationPackage; @@ -126,7 +127,7 @@ private void Initialize(bool isServer, string package, NetworkCredential credent } } - internal SafeDeleteContext GetContext(out SecurityStatusPal status) + internal SafeDeleteContext? GetContext(out SecurityStatusPal status) { status = new SecurityStatusPal(SecurityStatusPalErrorCode.OK); if (!(IsCompleted && IsValidContext)) @@ -158,22 +159,22 @@ internal void CloseContext() internal int VerifySignature(byte[] buffer, int offset, int count) { - return NegotiateStreamPal.VerifySignature(_securityContext, buffer, offset, count); + return NegotiateStreamPal.VerifySignature(_securityContext!, buffer, offset, count); } internal int MakeSignature(byte[] buffer, int offset, int count, ref byte[] output) { - return NegotiateStreamPal.MakeSignature(_securityContext, buffer, offset, count, ref output); + return NegotiateStreamPal.MakeSignature(_securityContext!, buffer, offset, count, ref output); } - internal string GetOutgoingBlob(string incomingBlob) + internal string? GetOutgoingBlob(string incomingBlob) { - byte[] decodedIncomingBlob = null; + byte[]? decodedIncomingBlob = null; if (incomingBlob != null && incomingBlob.Length > 0) { decodedIncomingBlob = Convert.FromBase64String(incomingBlob); } - byte[] decodedOutgoingBlob = null; + byte[]? decodedOutgoingBlob = null; if ((IsValidContext || IsCompleted) && decodedIncomingBlob == null) { @@ -187,7 +188,7 @@ internal string GetOutgoingBlob(string incomingBlob) decodedOutgoingBlob = GetOutgoingBlob(decodedIncomingBlob, true, out statusCode); } - string outgoingBlob = null; + string? outgoingBlob = null; if (decodedOutgoingBlob != null && decodedOutgoingBlob.Length > 0) { outgoingBlob = Convert.ToBase64String(decodedOutgoingBlob); @@ -201,18 +202,18 @@ internal string GetOutgoingBlob(string incomingBlob) return outgoingBlob; } - internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool thrownOnError) + internal byte[]? GetOutgoingBlob(byte[] incomingBlob, bool thrownOnError) { SecurityStatusPal statusCode; return GetOutgoingBlob(incomingBlob, thrownOnError, out statusCode); } // Accepts an incoming binary security blob and returns an outgoing binary security blob. - internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out SecurityStatusPal statusCode) + internal byte[]? GetOutgoingBlob(byte[]? incomingBlob, bool throwOnError, out SecurityStatusPal statusCode) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, incomingBlob); - var result = new byte[_tokenSize]; + byte[]? result = new byte[_tokenSize]; bool firstTime = _securityContext == null; try @@ -221,7 +222,7 @@ internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out Secu { // client session statusCode = NegotiateStreamPal.InitializeSecurityContext( - ref _credentialsHandle, + ref _credentialsHandle!, ref _securityContext, _spn, _requestedContextFlags, @@ -312,14 +313,14 @@ internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out Secu return result; } - private string GetClientSpecifiedSpn() + private string? GetClientSpecifiedSpn() { if (!(IsValidContext && IsCompleted)) { NetEventSource.Fail(this, "Trying to get the client SPN before handshaking is done!"); } - string spn = NegotiateStreamPal.QueryContextClientSpecifiedSpn(_securityContext); + string? spn = NegotiateStreamPal.QueryContextClientSpecifiedSpn(_securityContext!); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"The client specified SPN is [{spn}]"); diff --git a/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs b/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs index 7313b72028032c..ba00467c14f3ef 100644 --- a/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs +++ b/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; @@ -13,7 +14,7 @@ internal static class CertificateValidation { private static readonly IdnMapping s_idnMapping = new IdnMapping(); - internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string hostName) + internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string? hostName) { SslPolicyErrors errors = chain.Build(remoteCertificate) ? SslPolicyErrors.None : @@ -32,7 +33,7 @@ internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X int hostNameMatch; using (SafeX509Handle certHandle = Interop.Crypto.X509UpRef(remoteCertificate.Handle)) { - IPAddress hostnameAsIp; + IPAddress? hostnameAsIp; if (IPAddress.TryParse(hostName, out hostnameAsIp)) { byte[] addressBytes = hostnameAsIp.GetAddressBytes(); diff --git a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs index bec9e8fd7f33d0..1fdcd6952254b8 100644 --- a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs +++ b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; using System.ComponentModel; using System.Diagnostics; @@ -39,7 +40,7 @@ internal static string QueryContextAuthenticationPackage(SafeDeleteContext secur } private static byte[] GssWrap( - SafeGssContextHandle context, + SafeGssContextHandle? context, bool encrypt, byte[] buffer, int offset, @@ -68,7 +69,7 @@ private static byte[] GssWrap( } private static int GssUnwrap( - SafeGssContextHandle context, + SafeGssContextHandle? context, byte[] buffer, int offset, int count) @@ -96,14 +97,14 @@ private static int GssUnwrap( } private static bool GssInitSecurityContext( - ref SafeGssContextHandle context, + ref SafeGssContextHandle? context, SafeGssCredHandle credential, bool isNtlm, ChannelBinding channelBinding, - SafeGssNameHandle targetName, + SafeGssNameHandle? targetName, Interop.NetSecurityNative.GssFlags inFlags, - byte[] buffer, - out byte[] outputBuffer, + byte[]? buffer, + out byte[]? outputBuffer, out uint outFlags, out bool isNtlmUsed) { @@ -186,9 +187,9 @@ private static bool GssInitSecurityContext( } private static bool GssAcceptSecurityContext( - ref SafeGssContextHandle context, + ref SafeGssContextHandle? context, SafeGssCredHandle credential, - byte[] buffer, + byte[]? buffer, out byte[] outputBuffer, out uint outFlags, out bool isNtlmUsed) @@ -239,7 +240,7 @@ private static bool GssAcceptSecurityContext( } private static string GssGetUser( - ref SafeGssContextHandle context) + ref SafeGssContextHandle? context) { Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer); @@ -277,12 +278,12 @@ Interop.NetSecurityNative.Status status private static SecurityStatusPal EstablishSecurityContext( SafeFreeNegoCredentials credential, - ref SafeDeleteContext context, + ref SafeDeleteContext? context, ChannelBinding channelBinding, string targetName, ContextFlagsPal inFlags, - byte[] incomingBlob, - ref byte[] resultBuffer, + byte[]? incomingBlob, + ref byte[]? resultBuffer, ref ContextFlagsPal outFlags) { bool isNtlmOnly = credential.IsNtlmOnly; @@ -305,7 +306,7 @@ private static SecurityStatusPal EstablishSecurityContext( ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(inFlags, isServer: false); uint outputFlags; bool isNtlmUsed; - SafeGssContextHandle contextHandle = negoContext.GssContext; + SafeGssContextHandle? contextHandle = negoContext.GssContext; bool done = GssInitSecurityContext( ref contextHandle, credential.GssCredential, @@ -339,7 +340,7 @@ private static SecurityStatusPal EstablishSecurityContext( Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext); if (null == negoContext.GssContext) { - negoContext.SetGssContext(contextHandle); + negoContext.SetGssContext(contextHandle!); } SecurityStatusPalErrorCode errorCode = done ? @@ -356,12 +357,12 @@ private static SecurityStatusPal EstablishSecurityContext( internal static SecurityStatusPal InitializeSecurityContext( ref SafeFreeCredentials credentialsHandle, - ref SafeDeleteContext securityContext, + ref SafeDeleteContext? securityContext, string spn, ContextFlagsPal requestedContextFlags, - byte[] incomingBlob, + byte[]? incomingBlob, ChannelBinding channelBinding, - ref byte[] resultBlob, + ref byte[]? resultBlob, ref ContextFlagsPal contextFlags) { SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle; @@ -395,23 +396,23 @@ internal static SecurityStatusPal InitializeSecurityContext( } internal static SecurityStatusPal AcceptSecurityContext( - SafeFreeCredentials credentialsHandle, - ref SafeDeleteContext securityContext, + SafeFreeCredentials? credentialsHandle, + ref SafeDeleteContext? securityContext, ContextFlagsPal requestedContextFlags, - byte[] incomingBlob, + byte[]? incomingBlob, ChannelBinding channelBinding, ref byte[] resultBlob, ref ContextFlagsPal contextFlags) { if (securityContext == null) { - securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle); + securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!); } SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext; try { - SafeGssContextHandle contextHandle = negoContext.GssContext; + SafeGssContextHandle? contextHandle = negoContext.GssContext; bool done = GssAcceptSecurityContext( ref contextHandle, negoContext.AcceptorCredential, @@ -427,7 +428,7 @@ internal static SecurityStatusPal AcceptSecurityContext( Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext); if (null == negoContext.GssContext) { - negoContext.SetGssContext(contextHandle); + negoContext.SetGssContext(contextHandle!); } contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop( @@ -495,7 +496,7 @@ private static string GetUser( SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext; try { - SafeGssContextHandle contextHandle = negoContext.GssContext; + SafeGssContextHandle? contextHandle = negoContext.GssContext; return GssGetUser(ref contextHandle); } catch (Exception ex) @@ -545,8 +546,8 @@ internal static SafeFreeCredentials AcquireCredentialsHandle(string package, boo } internal static SecurityStatusPal CompleteAuthToken( - ref SafeDeleteContext securityContext, - byte[] incomingBlob) + ref SafeDeleteContext? securityContext, + byte[]? incomingBlob) { return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } @@ -558,7 +559,7 @@ internal static int Encrypt( int count, bool isConfidential, bool isNtlm, - ref byte[] output, + ref byte[]? output, uint sequenceNumber) { SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext; @@ -582,7 +583,7 @@ internal static int Encrypt( internal static int Decrypt( SafeDeleteContext securityContext, - byte[] buffer, + byte[]? buffer, int offset, int count, bool isConfidential, @@ -603,7 +604,7 @@ internal static int Decrypt( } newOffset = offset; - return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count); + return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count); } internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count) @@ -620,7 +621,7 @@ internal static int VerifySignature(SafeDeleteContext securityContext, byte[] bu throw new ArgumentOutOfRangeException(nameof(count)); } - return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count); + return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count); } internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output) diff --git a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs index 96690d1a3bc601..a1f306edd44e2d 100644 --- a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; using System.Diagnostics; using System.Globalization; @@ -20,7 +21,7 @@ internal static partial class NegotiateStreamPal { internal static int QueryMaxTokenSize(string package) { - return SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken; + return SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true)!.MaxToken; } internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer) @@ -33,7 +34,7 @@ internal static SafeFreeCredentials AcquireDefaultCredential(string package, boo internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential) { - SafeSspiAuthDataHandle authData = null; + SafeSspiAuthDataHandle? authData = null; try { Interop.SECURITY_STATUS result = Interop.SspiCli.SspiEncodeStringsAsAuthIdentity( @@ -55,29 +56,29 @@ internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string packa } } - internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) + internal static string? QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) { return SSPIWrapper.QueryStringContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET); } - internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext) + internal static string? QueryContextAuthenticationPackage(SafeDeleteContext securityContext) { SecPkgContext_NegotiationInfoW ctx = default; - bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NEGOTIATION_INFO, typeof(SafeFreeContextBuffer), out SafeHandle sspiHandle, ref ctx); + bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NEGOTIATION_INFO, typeof(SafeFreeContextBuffer), out SafeHandle? sspiHandle, ref ctx); using (sspiHandle) { - return success ? NegotiationInfoClass.GetAuthenticationPackageName(sspiHandle, (int)ctx.NegotiationState) : null; + return success ? NegotiationInfoClass.GetAuthenticationPackageName(sspiHandle!, (int)ctx.NegotiationState) : null; } } internal static SecurityStatusPal InitializeSecurityContext( - ref SafeFreeCredentials credentialsHandle, - ref SafeDeleteContext securityContext, + ref SafeFreeCredentials? credentialsHandle, + ref SafeDeleteContext? securityContext, string spn, ContextFlagsPal requestedContextFlags, - byte[] incomingBlob, + byte[]? incomingBlob, ChannelBinding channelBinding, - ref byte[] resultBlob, + ref byte[]? resultBlob, ref ContextFlagsPal contextFlags) { @@ -96,7 +97,7 @@ internal static SecurityStatusPal InitializeSecurityContext( Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero; // There is only one SafeDeleteContext type on Windows which is SafeDeleteSslContext so this cast is safe. - SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; + SafeDeleteSslContext? sslContext = (SafeDeleteSslContext?)securityContext; Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPIAuth, ref credentialsHandle, @@ -114,11 +115,11 @@ internal static SecurityStatusPal InitializeSecurityContext( } internal static SecurityStatusPal CompleteAuthToken( - ref SafeDeleteContext securityContext, - byte[] incomingBlob) + ref SafeDeleteContext? securityContext, + byte[]? incomingBlob) { // There is only one SafeDeleteContext type on Windows which is SafeDeleteSslContext so this cast is safe. - SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; + SafeDeleteSslContext? sslContext = (SafeDeleteSslContext?)securityContext; var inSecurityBuffer = new SecurityBuffer(incomingBlob, SecurityBufferType.SECBUFFER_TOKEN); Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.CompleteAuthToken( GlobalSSPI.SSPIAuth, @@ -129,12 +130,12 @@ internal static SecurityStatusPal CompleteAuthToken( } internal static SecurityStatusPal AcceptSecurityContext( - SafeFreeCredentials credentialsHandle, - ref SafeDeleteContext securityContext, + SafeFreeCredentials? credentialsHandle, + ref SafeDeleteContext? securityContext, ContextFlagsPal requestedContextFlags, - byte[] incomingBlob, + byte[]? incomingBlob, ChannelBinding channelBinding, - ref byte[] resultBlob, + ref byte[]? resultBlob, ref ContextFlagsPal contextFlags) { InputSecurityBuffers inputBuffers = default; @@ -152,7 +153,7 @@ internal static SecurityStatusPal AcceptSecurityContext( Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero; // There is only one SafeDeleteContext type on Windows which is SafeDeleteSslContext so this cast is safe. - SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; + SafeDeleteSslContext? sslContext = (SafeDeleteSslContext?)securityContext; Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPIAuth, credentialsHandle, diff --git a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs index a7dcea6f6162e7..5ceb41cb71c3eb 100644 --- a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics.Tracing; using System.Net.Security; @@ -37,7 +38,7 @@ public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.Credent } [NonEvent] - public void InitializeSecurityContext(SafeFreeCredentials credential, SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags) + public void InitializeSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) { if (IsEnabled()) { @@ -45,11 +46,11 @@ public void InitializeSecurityContext(SafeFreeCredentials credential, SafeDelete } } [Event(InitializeSecurityContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void InitializeSecurityContext(string credential, string context, string targetName, Interop.SspiCli.ContextFlags inFlags) => + private void InitializeSecurityContext(string? credential, string? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) => WriteEvent(InitializeSecurityContextId, credential, context, targetName, (int)inFlags); [NonEvent] - public void AcceptSecurityContext(SafeFreeCredentials credential, SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags) + public void AcceptSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, Interop.SspiCli.ContextFlags inFlags) { if (IsEnabled()) { diff --git a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs index 458b71dafd31c4..d91badee89faa9 100644 --- a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs +++ b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics.Tracing; using System.Globalization; using System.Net.Security; @@ -15,7 +16,7 @@ internal sealed partial class NetEventSource // Event ids are defined in NetEventSource.Common.cs. [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void EnumerateSecurityPackages(string securityPackage) + public void EnumerateSecurityPackages(string? securityPackage) { if (IsEnabled()) { diff --git a/src/libraries/Common/src/System/Net/Security/SSPIHandleCache.cs b/src/libraries/Common/src/System/Net/Security/SSPIHandleCache.cs index 996ae783e0b287..90e1dc85f95cd9 100644 --- a/src/libraries/Common/src/System/Net/Security/SSPIHandleCache.cs +++ b/src/libraries/Common/src/System/Net/Security/SSPIHandleCache.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading; namespace System.Net.Security @@ -20,7 +21,7 @@ internal static void CacheCredential(SafeFreeCredentials newHandle) { try { - SafeCredentialReference newRef = SafeCredentialReference.CreateReference(newHandle); + SafeCredentialReference? newRef = SafeCredentialReference.CreateReference(newHandle); if (newRef == null) { diff --git a/src/libraries/Common/src/System/Net/Security/SecurityBuffer.Windows.cs b/src/libraries/Common/src/System/Net/Security/SecurityBuffer.Windows.cs index 9ba6ed506cf538..48589338e62cb6 100644 --- a/src/libraries/Common/src/System/Net/Security/SecurityBuffer.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/SecurityBuffer.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; @@ -62,7 +63,7 @@ internal readonly ref struct InputSecurityBuffer { public readonly SecurityBufferType Type; public readonly ReadOnlySpan Token; - public readonly SafeHandle UnmanagedToken; + public readonly SafeHandle? UnmanagedToken; public InputSecurityBuffer(ReadOnlySpan data, SecurityBufferType tokentype) { @@ -85,10 +86,10 @@ internal struct SecurityBuffer public int offset; public int size; public SecurityBufferType type; - public byte[] token; - public SafeHandle unmanagedToken; + public byte[]? token; + public SafeHandle? unmanagedToken; - public SecurityBuffer(byte[] data, int offset, int size, SecurityBufferType tokentype) + public SecurityBuffer(byte[]? data, int offset, int size, SecurityBufferType tokentype) { if (offset < 0 || offset > (data == null ? 0 : data.Length)) { @@ -107,7 +108,7 @@ public SecurityBuffer(byte[] data, int offset, int size, SecurityBufferType toke this.unmanagedToken = null; } - public SecurityBuffer(byte[] data, SecurityBufferType tokentype) + public SecurityBuffer(byte[]? data, SecurityBufferType tokentype) { this.offset = 0; this.size = data == null ? 0 : data.Length; diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteContext.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteContext.cs index c3c75790b92d1e..3ced4e156f3be3 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteContext.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteContext.cs @@ -39,7 +39,7 @@ protected override bool ReleaseHandle() { Debug.Assert((null != _credential), "Null credential in SafeDeleteContext"); _credential.DangerousRelease(); - _credential = null; + _credential = null!; return true; } } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs index 1d558167ce2c74..0e4add100f76e2 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -12,9 +13,9 @@ namespace System.Net.Security { internal sealed class SafeDeleteNegoContext : SafeDeleteContext { - private SafeGssCredHandle _acceptorCredential; - private SafeGssNameHandle _targetName; - private SafeGssContextHandle _context; + private SafeGssCredHandle? _acceptorCredential; + private SafeGssNameHandle? _targetName; + private SafeGssContextHandle? _context; private bool _isNtlmUsed; public SafeGssCredHandle AcceptorCredential @@ -26,7 +27,7 @@ public SafeGssCredHandle AcceptorCredential } } - public SafeGssNameHandle TargetName + public SafeGssNameHandle? TargetName { get { return _targetName; } } @@ -37,7 +38,7 @@ public bool IsNtlmUsed get { return _isNtlmUsed; } } - public SafeGssContextHandle GssContext + public SafeGssContextHandle? GssContext { get { return _context; } } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteSslContext.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteSslContext.cs index 781b8c3362e972..52ef417ad3bab8 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteSslContext.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeDeleteSslContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; @@ -63,7 +64,7 @@ protected override void Dispose(bool disposing) if (null != _sslContext) { _sslContext.Dispose(); - _sslContext = null; + _sslContext = null!; } } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCertContext.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCertContext.cs index ad9904d988c709..df78077e4d64de 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCertContext.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCertContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; @@ -18,7 +19,7 @@ internal sealed class SafeFreeCertContext : DebugSafeHandle internal sealed class SafeFreeCertContext : SafeHandle { #endif - private readonly SafeX509Handle _certificate; + private readonly SafeX509Handle? _certificate; public SafeFreeCertContext(SafeX509Handle certificate) : base(IntPtr.Zero, true) { @@ -44,7 +45,7 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - _certificate.DangerousRelease(); + _certificate!.DangerousRelease(); _certificate.Dispose(); return true; } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs index 245f0f24cfcec6..236e0e61484d0e 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; @@ -39,7 +40,7 @@ internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid // internal SafeFreeCredentials Target; - internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) + internal static SafeCredentialReference? CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) @@ -67,7 +68,7 @@ protected override bool ReleaseHandle() target.DangerousRelease(); } - Target = null; + Target = null!; return true; } } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs index ab8cf2fea0d1da..b36c1394330a14 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -82,7 +83,7 @@ public override bool IsInvalid protected override bool ReleaseHandle() { _credential.DangerousRelease(); - _credential = null; + _credential = null!; return true; } } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs index 045426c9d1d962..90ee4654cebf0e 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; @@ -15,18 +16,18 @@ namespace System.Net.Security { internal sealed class SafeFreeSslCredentials : SafeFreeCredentials { - private SafeX509Handle _certHandle; - private SafeEvpPKeyHandle _certKeyHandle; + private SafeX509Handle? _certHandle; + private SafeEvpPKeyHandle? _certKeyHandle; private SslProtocols _protocols = SslProtocols.None; private EncryptionPolicy _policy; private bool _isInvalid = false; - internal SafeX509Handle CertHandle + internal SafeX509Handle? CertHandle { get { return _certHandle; } } - internal SafeEvpPKeyHandle CertKeyHandle + internal SafeEvpPKeyHandle? CertKeyHandle { get { return _certKeyHandle; } } @@ -41,20 +42,20 @@ internal EncryptionPolicy Policy get { return _policy; } } - public SafeFreeSslCredentials(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy) + public SafeFreeSslCredentials(X509Certificate? certificate, SslProtocols protocols, EncryptionPolicy policy) : base(IntPtr.Zero, true) { Debug.Assert( certificate == null || certificate is X509Certificate2, "Only X509Certificate2 certificates are supported at this time"); - X509Certificate2 cert = (X509Certificate2)certificate; + X509Certificate2? cert = (X509Certificate2?)certificate; if (cert != null) { Debug.Assert(cert.HasPrivateKey, "cert.HasPrivateKey"); - using (RSAOpenSsl rsa = (RSAOpenSsl)cert.GetRSAPrivateKey()) + using (RSAOpenSsl? rsa = (RSAOpenSsl?)cert.GetRSAPrivateKey()) { if (rsa != null) { @@ -65,7 +66,7 @@ public SafeFreeSslCredentials(X509Certificate certificate, SslProtocols protocol if (_certKeyHandle == null) { - using (ECDsaOpenSsl ecdsa = (ECDsaOpenSsl)cert.GetECDsaPrivateKey()) + using (ECDsaOpenSsl? ecdsa = (ECDsaOpenSsl?)cert.GetECDsaPrivateKey()) { if (ecdsa != null) { diff --git a/src/libraries/Common/src/System/Net/SecurityStatusPal.cs b/src/libraries/Common/src/System/Net/SecurityStatusPal.cs index 324a991e4fff65..595aec0970aba1 100644 --- a/src/libraries/Common/src/System/Net/SecurityStatusPal.cs +++ b/src/libraries/Common/src/System/Net/SecurityStatusPal.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Net { internal readonly struct SecurityStatusPal { public readonly SecurityStatusPalErrorCode ErrorCode; - public readonly Exception Exception; + public readonly Exception? Exception; - public SecurityStatusPal(SecurityStatusPalErrorCode errorCode, Exception exception = null) + public SecurityStatusPal(SecurityStatusPalErrorCode errorCode, Exception? exception = null) { ErrorCode = errorCode; Exception = exception; diff --git a/src/libraries/System.Net.Security/ref/System.Net.Security.cs b/src/libraries/System.Net.Security/ref/System.Net.Security.cs index 13fa69d74e54f1..c022960def9c77 100644 --- a/src/libraries/System.Net.Security/ref/System.Net.Security.cs +++ b/src/libraries/System.Net.Security/ref/System.Net.Security.cs @@ -33,7 +33,7 @@ public enum EncryptionPolicy AllowNoEncryption = 1, NoEncryption = 2, } - public delegate System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection localCertificates, System.Security.Cryptography.X509Certificates.X509Certificate remoteCertificate, string[] acceptableIssuers); + public delegate System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection localCertificates, System.Security.Cryptography.X509Certificates.X509Certificate? remoteCertificate, string[] acceptableIssuers); public partial class NegotiateStream : System.Net.Security.AuthenticatedStream { public NegotiateStream(System.IO.Stream innerStream) : base (default(System.IO.Stream), default(bool)) { } @@ -54,34 +54,34 @@ public partial class NegotiateStream : System.Net.Security.AuthenticatedStream public virtual System.Security.Principal.IIdentity RemoteIdentity { get { throw null; } } public override int WriteTimeout { get { throw null; } set { } } public virtual void AuthenticateAsClient() { } - public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName) { } - public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } + public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName) { } + public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync() { throw null; } - public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName) { throw null; } - public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } + public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName) { throw null; } + public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, string targetName) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } public virtual void AuthenticateAsServer() { } public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } - public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } - public virtual void AuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy) { } + public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } + public virtual void AuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy) { } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync() { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } - public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } - public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback asyncCallback, object asyncState) { throw null; } + public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } + public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { } @@ -101,8 +101,8 @@ public enum ProtectionLevel Sign = 1, EncryptAndSign = 2, } - public delegate bool RemoteCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors); - public delegate System.Security.Cryptography.X509Certificates.X509Certificate ServerCertificateSelectionCallback(object sender, string hostName); + public delegate bool RemoteCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate? certificate, System.Security.Cryptography.X509Certificates.X509Chain? chain, System.Net.Security.SslPolicyErrors sslPolicyErrors); + public delegate System.Security.Cryptography.X509Certificates.X509Certificate ServerCertificateSelectionCallback(object sender, string? hostName); public readonly partial struct SslApplicationProtocol : System.IEquatable { private readonly object _dummy; @@ -114,7 +114,7 @@ public enum ProtectionLevel public SslApplicationProtocol(string protocol) { throw null; } public System.ReadOnlyMemory Protocol { get { throw null; } } public bool Equals(System.Net.Security.SslApplicationProtocol other) { throw null; } - public override bool Equals(object obj) { throw null; } + public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Security.SslApplicationProtocol left, System.Net.Security.SslApplicationProtocol right) { throw null; } public static bool operator !=(System.Net.Security.SslApplicationProtocol left, System.Net.Security.SslApplicationProtocol right) { throw null; } @@ -124,37 +124,37 @@ public partial class SslClientAuthenticationOptions { public SslClientAuthenticationOptions() { } public bool AllowRenegotiation { get { throw null; } set { } } - public System.Collections.Generic.List ApplicationProtocols { get { throw null; } set { } } + public System.Collections.Generic.List? ApplicationProtocols { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } } - public System.Net.Security.CipherSuitesPolicy CipherSuitesPolicy { get { throw null; } set { } } - public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } set { } } + public System.Net.Security.CipherSuitesPolicy? CipherSuitesPolicy { get { throw null; } set { } } + public System.Security.Cryptography.X509Certificates.X509CertificateCollection? ClientCertificates { get { throw null; } set { } } public System.Security.Authentication.SslProtocols EnabledSslProtocols { get { throw null; } set { } } public System.Net.Security.EncryptionPolicy EncryptionPolicy { get { throw null; } set { } } - public System.Net.Security.LocalCertificateSelectionCallback LocalCertificateSelectionCallback { get { throw null; } set { } } - public System.Net.Security.RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get { throw null; } set { } } - public string TargetHost { get { throw null; } set { } } + public System.Net.Security.LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get { throw null; } set { } } + public System.Net.Security.RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get { throw null; } set { } } + public string? TargetHost { get { throw null; } set { } } } public partial class SslServerAuthenticationOptions { public SslServerAuthenticationOptions() { } public bool AllowRenegotiation { get { throw null; } set { } } - public System.Collections.Generic.List ApplicationProtocols { get { throw null; } set { } } + public System.Collections.Generic.List? ApplicationProtocols { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } } - public System.Net.Security.CipherSuitesPolicy CipherSuitesPolicy { get { throw null; } set { } } + public System.Net.Security.CipherSuitesPolicy? CipherSuitesPolicy { get { throw null; } set { } } public bool ClientCertificateRequired { get { throw null; } set { } } public System.Security.Authentication.SslProtocols EnabledSslProtocols { get { throw null; } set { } } public System.Net.Security.EncryptionPolicy EncryptionPolicy { get { throw null; } set { } } - public System.Net.Security.RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get { throw null; } set { } } - public System.Security.Cryptography.X509Certificates.X509Certificate ServerCertificate { get { throw null; } set { } } - public System.Net.Security.ServerCertificateSelectionCallback ServerCertificateSelectionCallback { get { throw null; } set { } } + public System.Net.Security.RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get { throw null; } set { } } + public System.Security.Cryptography.X509Certificates.X509Certificate? ServerCertificate { get { throw null; } set { } } + public System.Net.Security.ServerCertificateSelectionCallback? ServerCertificateSelectionCallback { get { throw null; } set { } } } public partial class SslStream : System.Net.Security.AuthenticatedStream { public SslStream(System.IO.Stream innerStream) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base (default(System.IO.Stream), default(bool)) { } - public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback) : base (default(System.IO.Stream), default(bool)) { } - public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback) : base (default(System.IO.Stream), default(bool)) { } - public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy) : base (default(System.IO.Stream), default(bool)) { } + public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback) : base (default(System.IO.Stream), default(bool)) { } + public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback) : base (default(System.IO.Stream), default(bool)) { } + public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy) : base (default(System.IO.Stream), default(bool)) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } @@ -172,23 +172,23 @@ public partial class SslStream : System.Net.Security.AuthenticatedStream public virtual System.Security.Authentication.ExchangeAlgorithmType KeyExchangeAlgorithm { get { throw null; } } public virtual int KeyExchangeStrength { get { throw null; } } public override long Length { get { throw null; } } - public virtual System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificate { get { throw null; } } + public virtual System.Security.Cryptography.X509Certificates.X509Certificate? LocalCertificate { get { throw null; } } public System.Net.Security.SslApplicationProtocol NegotiatedApplicationProtocol { get { throw null; } } [System.CLSCompliantAttribute(false)] public virtual System.Net.Security.TlsCipherSuite NegotiatedCipherSuite { get { throw null; } } public override long Position { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } - public virtual System.Security.Cryptography.X509Certificates.X509Certificate RemoteCertificate { get { throw null; } } + public virtual System.Security.Cryptography.X509Certificates.X509Certificate? RemoteCertificate { get { throw null; } } public virtual System.Security.Authentication.SslProtocols SslProtocol { get { throw null; } } public System.Net.TransportContext TransportContext { get { throw null; } } public override int WriteTimeout { get { throw null; } set { } } public virtual void AuthenticateAsClient(string targetHost) { } - public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { } - public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } + public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { } + public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } public System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.Security.SslClientAuthenticationOptions sslClientAuthenticationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost) { throw null; } - public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { throw null; } - public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } + public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { throw null; } + public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } @@ -196,14 +196,14 @@ public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certif public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback asyncCallback, object asyncState) { throw null; } - public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback asyncCallback, object asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } + public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { } @@ -572,15 +572,15 @@ public partial class AuthenticationException : System.SystemException { public AuthenticationException() { } protected AuthenticationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public AuthenticationException(string message) { } - public AuthenticationException(string message, System.Exception innerException) { } + public AuthenticationException(string? message) { } + public AuthenticationException(string? message, System.Exception? innerException) { } } public partial class InvalidCredentialException : System.Security.Authentication.AuthenticationException { public InvalidCredentialException() { } protected InvalidCredentialException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public InvalidCredentialException(string message) { } - public InvalidCredentialException(string message, System.Exception innerException) { } + public InvalidCredentialException(string? message) { } + public InvalidCredentialException(string? message, System.Exception? innerException) { } } } namespace System.Security.Authentication.ExtendedProtection @@ -590,14 +590,14 @@ public partial class ExtendedProtectionPolicy : System.Runtime.Serialization.ISe protected ExtendedProtectionPolicy(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ChannelBinding customChannelBinding) { } - public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Collections.ICollection customServiceNames) { } - public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Security.Authentication.ExtendedProtection.ServiceNameCollection customServiceNames) { } - public System.Security.Authentication.ExtendedProtection.ChannelBinding CustomChannelBinding { get { throw null; } } - public System.Security.Authentication.ExtendedProtection.ServiceNameCollection CustomServiceNames { get { throw null; } } + public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Collections.ICollection? customServiceNames) { } + public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Security.Authentication.ExtendedProtection.ServiceNameCollection? customServiceNames) { } + public System.Security.Authentication.ExtendedProtection.ChannelBinding? CustomChannelBinding { get { throw null; } } + public System.Security.Authentication.ExtendedProtection.ServiceNameCollection? CustomServiceNames { get { throw null; } } public static bool OSSupportsExtendedProtection { get { throw null; } } public System.Security.Authentication.ExtendedProtection.PolicyEnforcement PolicyEnforcement { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ProtectionScenario ProtectionScenario { get { throw null; } } - void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } + void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo? info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } public enum PolicyEnforcement @@ -614,7 +614,7 @@ public enum ProtectionScenario public partial class ServiceNameCollection : System.Collections.ReadOnlyCollectionBase { public ServiceNameCollection(System.Collections.ICollection items) { } - public bool Contains(string searchServiceName) { throw null; } + public bool Contains(string? searchServiceName) { throw null; } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(System.Collections.IEnumerable serviceNames) { throw null; } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(string serviceName) { throw null; } } diff --git a/src/libraries/System.Net.Security/ref/System.Net.Security.csproj b/src/libraries/System.Net.Security/ref/System.Net.Security.csproj index 1e605a2eb87244..6e4bace9eb569f 100644 --- a/src/libraries/System.Net.Security/ref/System.Net.Security.csproj +++ b/src/libraries/System.Net.Security/ref/System.Net.Security.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Net.Security/src/System.Net.Security.csproj b/src/libraries/System.Net.Security/src/System.Net.Security.csproj index abc2ce2068a290..d25fabd0de46ab 100644 --- a/src/libraries/System.Net.Security/src/System.Net.Security.csproj +++ b/src/libraries/System.Net.Security/src/System.Net.Security.csproj @@ -5,6 +5,7 @@ $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-OSX $(DefineConstants);PRODUCT + enable $(DefineConstants);SYSNETSECURITY_NO_OPENSSL diff --git a/src/libraries/System.Net.Security/src/System/Net/BufferAsyncResult.cs b/src/libraries/System.Net.Security/src/System/Net/BufferAsyncResult.cs index b5d4d530f5cfd3..e26466aa8fcfa7 100644 --- a/src/libraries/System.Net.Security/src/System/Net/BufferAsyncResult.cs +++ b/src/libraries/System.Net.Security/src/System/Net/BufferAsyncResult.cs @@ -21,7 +21,7 @@ internal sealed class BufferAsyncResult : LazyAsyncResult private bool _countOrResultIsResult; #endif - public BufferAsyncResult(object asyncObject, byte[] buffer, int offset, int count, object asyncState, AsyncCallback asyncCallback) + public BufferAsyncResult(object asyncObject, byte[] buffer, int offset, int count, object? asyncState, AsyncCallback? asyncCallback) : base(asyncObject, asyncState, asyncCallback) { Buffer = buffer; diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs index 4b32fc724dffef..5f61473794a82f 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs @@ -13,10 +13,10 @@ internal static partial class CertificateValidationPal internal static SslPolicyErrors VerifyCertificateProperties( SafeDeleteContext securityContext, X509Chain chain, - X509Certificate2 remoteCertificate, + X509Certificate2? remoteCertificate, bool checkCertName, bool isServer, - string hostName) + string? hostName) { SslPolicyErrors errors = SslPolicyErrors.None; @@ -35,7 +35,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( { SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext; - if (!Interop.AppleCrypto.SslCheckHostnameMatch(sslContext.SslContext, hostName, remoteCertificate.NotBefore, out int osStatus)) + if (!Interop.AppleCrypto.SslCheckHostnameMatch(sslContext.SslContext, hostName!, remoteCertificate.NotBefore, out int osStatus)) { errors |= SslPolicyErrors.RemoteCertificateNameMismatch; @@ -51,14 +51,14 @@ internal static SslPolicyErrors VerifyCertificateProperties( // // Extracts a remote certificate upon request. // - internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext) + internal static X509Certificate2? GetRemoteCertificate(SafeDeleteContext securityContext) { return GetRemoteCertificate(securityContext, null); } - internal static X509Certificate2 GetRemoteCertificate( - SafeDeleteContext securityContext, - out X509Certificate2Collection remoteCertificateStore) + internal static X509Certificate2? GetRemoteCertificate( + SafeDeleteContext? securityContext, + out X509Certificate2Collection? remoteCertificateStore) { if (securityContext == null) { @@ -70,9 +70,9 @@ internal static X509Certificate2 GetRemoteCertificate( return GetRemoteCertificate(securityContext, remoteCertificateStore); } - private static X509Certificate2 GetRemoteCertificate( + private static X509Certificate2? GetRemoteCertificate( SafeDeleteContext securityContext, - X509Certificate2Collection remoteCertificateStore) + X509Certificate2Collection? remoteCertificateStore) { if (securityContext == null) { @@ -88,7 +88,7 @@ private static X509Certificate2 GetRemoteCertificate( return null; } - X509Certificate2 result = null; + X509Certificate2? result = null; using (SafeX509ChainHandle chainHandle = Interop.AppleCrypto.SslCopyCertChain(sslContext)) { diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs index 6e7b2c1592dc73..f9f2aac958f080 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs @@ -12,12 +12,12 @@ namespace System.Net internal static partial class CertificateValidationPal { internal static SslPolicyErrors VerifyCertificateProperties( - SafeDeleteContext securityContext, + SafeDeleteContext? securityContext, X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, - string hostName) + string? hostName) { return CertificateValidation.BuildChainAndVerifyProperties(chain, remoteCertificate, checkCertName, hostName); } @@ -25,14 +25,14 @@ internal static SslPolicyErrors VerifyCertificateProperties( // // Extracts a remote certificate upon request. // - internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext) + internal static X509Certificate2? GetRemoteCertificate(SafeDeleteContext securityContext) { return GetRemoteCertificate(securityContext, null); } - internal static X509Certificate2 GetRemoteCertificate( - SafeDeleteContext securityContext, - out X509Certificate2Collection remoteCertificateStore) + internal static X509Certificate2? GetRemoteCertificate( + SafeDeleteContext? securityContext, + out X509Certificate2Collection? remoteCertificateStore) { if (securityContext == null) { @@ -44,7 +44,7 @@ internal static X509Certificate2 GetRemoteCertificate( return GetRemoteCertificate(securityContext, remoteCertificateStore); } - private static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, X509Certificate2Collection remoteCertificateStore) + private static X509Certificate2? GetRemoteCertificate(SafeDeleteContext? securityContext, X509Certificate2Collection? remoteCertificateStore) { bool gotReference = false; @@ -55,8 +55,8 @@ private static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityC if (NetEventSource.IsEnabled) NetEventSource.Enter(securityContext); - X509Certificate2 result = null; - SafeFreeCertContext remoteContext = null; + X509Certificate2? result = null; + SafeFreeCertContext? remoteContext = null; try { int errorCode = QueryContextRemoteCertificate(securityContext, out remoteContext); @@ -171,7 +171,7 @@ private static X509Store OpenStore(StoreLocation storeLocation) return store; } - private static int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext remoteCertContext) + private static int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext? remoteCertContext) { remoteCertContext = null; try diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs index b349e43934df54..bf62eba45a3b34 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs @@ -14,18 +14,18 @@ namespace System.Net internal static partial class CertificateValidationPal { internal static SslPolicyErrors VerifyCertificateProperties( - SafeDeleteContext securityContext, + SafeDeleteContext? securityContext, X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, - string hostName) + string? hostName) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; bool chainBuildResult = chain.Build(remoteCertificate); if (!chainBuildResult // Build failed on handle or on policy. - && chain.SafeHandle.DangerousGetHandle() == IntPtr.Zero) // Build failed to generate a valid handle. + && chain.SafeHandle!.DangerousGetHandle() == IntPtr.Zero) // Build failed to generate a valid handle. { throw new CryptographicException(Marshal.GetLastWin32Error()); } @@ -59,7 +59,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( (Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL & ~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG); - SafeX509ChainHandle chainContext = chain.SafeHandle; + SafeX509ChainHandle chainContext = chain.SafeHandle!; status = Verify(chainContext, ref cppStruct); if (status == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH) { @@ -81,14 +81,14 @@ internal static SslPolicyErrors VerifyCertificateProperties( // Extracts a remote certificate upon request. // - internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext) => + internal static X509Certificate2? GetRemoteCertificate(SafeDeleteContext? securityContext) => GetRemoteCertificate(securityContext, retrieveCollection: false, out _); - internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateCollection) => + internal static X509Certificate2? GetRemoteCertificate(SafeDeleteContext? securityContext, out X509Certificate2Collection? remoteCertificateCollection) => GetRemoteCertificate(securityContext, retrieveCollection: true, out remoteCertificateCollection); - private static X509Certificate2 GetRemoteCertificate( - SafeDeleteContext securityContext, bool retrieveCollection, out X509Certificate2Collection remoteCertificateCollection) + private static X509Certificate2? GetRemoteCertificate( + SafeDeleteContext? securityContext, bool retrieveCollection, out X509Certificate2Collection? remoteCertificateCollection) { remoteCertificateCollection = null; @@ -99,8 +99,8 @@ private static X509Certificate2 GetRemoteCertificate( if (NetEventSource.IsEnabled) NetEventSource.Enter(securityContext); - X509Certificate2 result = null; - SafeFreeCertContext remoteContext = null; + X509Certificate2? result = null; + SafeFreeCertContext? remoteContext = null; try { remoteContext = SSPIWrapper.QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(GlobalSSPI.SSPISecureChannel, securityContext); @@ -136,7 +136,7 @@ private static X509Certificate2 GetRemoteCertificate( internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext) { Interop.SspiCli.SecPkgContext_IssuerListInfoEx issuerList = default; - bool success = SSPIWrapper.QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(GlobalSSPI.SSPISecureChannel, securityContext, ref issuerList, out SafeHandle sspiHandle); + bool success = SSPIWrapper.QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(GlobalSSPI.SSPISecureChannel, securityContext, ref issuerList, out SafeHandle? sspiHandle); string[] issuers = Array.Empty(); try @@ -146,7 +146,7 @@ internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext secu unsafe { issuers = new string[issuerList.cIssuers]; - var elements = new Span((void*)sspiHandle.DangerousGetHandle(), issuers.Length); + var elements = new Span((void*)sspiHandle!.DangerousGetHandle(), issuers.Length); for (int i = 0; i < elements.Length; ++i) { if (elements[i].cbSize <= 0) diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs index bfa93d185cf495..08b78c7229c93d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.cs @@ -12,14 +12,14 @@ internal static partial class CertificateValidationPal { private static readonly object s_syncObject = new object(); - private static volatile X509Store s_myCertStoreEx; - private static volatile X509Store s_myMachineCertStoreEx; + private static volatile X509Store? s_myCertStoreEx; + private static volatile X509Store? s_myMachineCertStoreEx; static partial void CheckSupportsStore(StoreLocation storeLocation, ref bool hasSupport); - internal static X509Store EnsureStoreOpened(bool isMachineStore) + internal static X509Store? EnsureStoreOpened(bool isMachineStore) { - X509Store store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; + X509Store? store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; if (store == null) { diff --git a/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs b/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs index a6a2ffdfdc0716..3350245eb73c5c 100644 --- a/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs +++ b/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs @@ -20,7 +20,7 @@ namespace System.Net // internal class AsyncProtocolRequest { - private AsyncProtocolCallback _callback; + private AsyncProtocolCallback? _callback; private int _completionStatus; private const int StatusNotStarted = 0; @@ -31,7 +31,7 @@ internal class AsyncProtocolRequest public int Result; public readonly CancellationToken CancellationToken; - public byte[] Buffer; // Temporary buffer reused by a protocol. + public byte[]? Buffer; // Temporary buffer reused by a protocol. public int Offset; public int Count; @@ -41,7 +41,7 @@ public AsyncProtocolRequest(LazyAsyncResult userAsyncResult, CancellationToken c { NetEventSource.Fail(this, "userAsyncResult == null"); } - if (userAsyncResult.InternalPeekCompleted) + if (userAsyncResult!.InternalPeekCompleted) { NetEventSource.Fail(this, "userAsyncResult is already completed."); } @@ -49,7 +49,7 @@ public AsyncProtocolRequest(LazyAsyncResult userAsyncResult, CancellationToken c CancellationToken = cancellationToken; } - public void SetNextRequest(byte[] buffer, int offset, int count, AsyncProtocolCallback callback) + public void SetNextRequest(byte[]? buffer, int offset, int count, AsyncProtocolCallback? callback) { if (_completionStatus != StatusNotStarted) { @@ -79,7 +79,7 @@ internal void CompleteRequest(int result) if (status == StatusCheckedOnSyncCompletion) { _completionStatus = StatusNotStarted; - _callback(this); + _callback!(this); } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Logging/NetEventSource.cs b/src/libraries/System.Net.Security/src/System/Net/Logging/NetEventSource.cs index 39760bf3fde3ff..7622f100c33bf6 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Logging/NetEventSource.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Logging/NetEventSource.cs @@ -14,7 +14,7 @@ internal sealed partial class NetEventSource : EventSource /// The buffer to be logged. /// The calling member. [NonEvent] - public static void DumpBuffer(object thisOrContextObject, ReadOnlyMemory buffer, [CallerMemberName] string memberName = null) + public static void DumpBuffer(object thisOrContextObject, ReadOnlyMemory buffer, [CallerMemberName] string? memberName = null) { if (IsEnabled) { diff --git a/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs b/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs index 7ed6221bfe8b2f..4b1a3ebff9f790 100644 --- a/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs +++ b/src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs @@ -10,7 +10,7 @@ namespace System.Net { internal partial class NTAuthentication { - internal string AssociatedName + internal string? AssociatedName { get { @@ -19,7 +19,7 @@ internal string AssociatedName throw new Win32Exception((int)SecurityStatusPalErrorCode.InvalidHandle); } - string name = NegotiateStreamPal.QueryContextAssociatedName(_securityContext); + string? name = NegotiateStreamPal.QueryContextAssociatedName(_securityContext!); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"NTAuthentication: The context is associated with [{name}]"); return name; } @@ -114,10 +114,10 @@ private static void InitializeCallback(object state) context.ThisPtr.Initialize(context.IsServer, context.Package, context.Credential, context.Spn, context.RequestedContextFlags, context.ChannelBinding); } - internal int Encrypt(byte[] buffer, int offset, int count, ref byte[] output, uint sequenceNumber) + internal int Encrypt(byte[] buffer, int offset, int count, ref byte[]? output, uint sequenceNumber) { return NegotiateStreamPal.Encrypt( - _securityContext, + _securityContext!, buffer, offset, count, @@ -129,7 +129,7 @@ internal int Encrypt(byte[] buffer, int offset, int count, ref byte[] output, ui internal int Decrypt(byte[] payload, int offset, int count, out int newOffset, uint expectedSeqNumber) { - return NegotiateStreamPal.Decrypt(_securityContext, payload, offset, count, IsConfidentialityFlag, IsNTLM, out newOffset, expectedSeqNumber); + return NegotiateStreamPal.Decrypt(_securityContext!, payload, offset, count, IsConfidentialityFlag, IsNTLM, out newOffset, expectedSeqNumber); } } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs index a0044b77ed14d3..8208744b3b02f8 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs @@ -56,7 +56,7 @@ internal CipherSuitesPolicyPal(IEnumerable allowedCipherSuites) { foreach (TlsCipherSuite cs in allowedCipherSuites) { - string name = Interop.Ssl.GetOpenSslCipherSuiteName( + string? name = Interop.Ssl.GetOpenSslCipherSuiteName( ssl, cs, out bool isTls12OrLower); @@ -79,7 +79,7 @@ internal CipherSuitesPolicyPal(IEnumerable allowedCipherSuites) } } - internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy policy, EncryptionPolicy encryptionPolicy) + internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { // if TLS 1.3 was explicitly requested the underlying code will throw // if default option (SslProtocols.None) is used we will opt-out of TLS 1.3 @@ -106,7 +106,7 @@ internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy policy, EncryptionPo return policy.Pal._tls13CipherSuites.Length == 1; } - internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy policy, EncryptionPolicy encryptionPolicy) + internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { if (policy == null) { @@ -129,8 +129,8 @@ private static bool IsOnlyTls13(SslProtocols protocols) internal static bool WantsTls13(SslProtocols protocols) => protocols == SslProtocols.None || (protocols & SslProtocols.Tls13) != 0; - internal static byte[] GetOpenSslCipherList( - CipherSuitesPolicy policy, + internal static byte[]? GetOpenSslCipherList( + CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) { @@ -153,8 +153,8 @@ internal static byte[] GetOpenSslCipherList( return policy.Pal._cipherSuites; } - internal static byte[] GetOpenSslCipherSuites( - CipherSuitesPolicy policy, + internal static byte[]? GetOpenSslCipherSuites( + CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs index 9d0d6141bdef75..d5096cb3faefd1 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs @@ -13,6 +13,6 @@ internal CipherSuitesPolicyPal(IEnumerable allowedCipherSuites) throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } - internal IEnumerable GetCipherSuites() => null; + internal IEnumerable GetCipherSuites() => null!; } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs index a9f1a0eacc317b..7bc1fe817b8640 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs @@ -19,10 +19,10 @@ public partial class NegotiateStream : AuthenticatedStream private int _NestedWrite; private int _NestedRead; - private byte[] _ReadHeader; + private byte[] _ReadHeader = null!; // will be initialized by ctor helper // Never updated directly, special properties are used. - private byte[] _InternalBuffer; + private byte[]? _InternalBuffer; private int _InternalOffset; private int _InternalBufferCount; @@ -31,7 +31,7 @@ private void InitializeStreamPart() _ReadHeader = new byte[4]; } - private byte[] InternalBuffer + private byte[]? InternalBuffer { get { @@ -106,7 +106,7 @@ private void ValidateParameters(byte[] buffer, int offset, int count) // // Combined sync/async write method. For sync request asyncRequest==null. // - private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { ValidateParameters(buffer, offset, count); @@ -139,13 +139,13 @@ private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolReq } } - private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { // We loop to this method from the callback. // If the last chunk was just completed from async callback (count < 0), we complete user request. if (count >= 0) { - byte[] outBuffer = null; + byte[]? outBuffer = null; do { int chunkBytes = Math.Min(count, NegoState.MaxWriteDataSize); @@ -164,7 +164,7 @@ private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolReq { // prepare for the next request asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, null); - Task t = InnerStream.WriteAsync(outBuffer, 0, encryptedBytes); + Task t = InnerStream.WriteAsync(outBuffer!, 0, encryptedBytes); if (t.IsCompleted) { t.GetAwaiter().GetResult(); @@ -181,7 +181,7 @@ private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolReq } else { - InnerStream.Write(outBuffer, 0, encryptedBytes); + InnerStream.Write(outBuffer!, 0, encryptedBytes); } offset += chunkBytes; @@ -200,7 +200,7 @@ private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolReq // There is a little overhead because we need to pass buffer/offset/count used only in sync. // Still the benefit is that we have a common sync/async code path. // - private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { ValidateParameters(buffer, offset, count); @@ -217,7 +217,7 @@ private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolReque int copyBytes = InternalBufferCount > count ? count : InternalBufferCount; if (copyBytes != 0) { - Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes); + Buffer.BlockCopy(InternalBuffer!, InternalOffset, buffer, offset, copyBytes); DecrementInternalBufferCount(copyBytes); } asyncRequest?.CompleteUser(copyBytes); @@ -248,7 +248,7 @@ private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolReque // // To avoid recursion when 0 bytes have been decrypted, loop until decryption results in at least 1 byte. // - private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { int result; // When we read -1 bytes means we have decrypted 0 bytes, need looping. @@ -257,7 +257,7 @@ private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequ return result; } - private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { int readBytes = 0; if (asyncRequest != null) @@ -279,7 +279,7 @@ private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocol return StartFrameBody(readBytes, buffer, offset, count, asyncRequest); } - private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { if (readBytes == 0) { @@ -328,13 +328,13 @@ private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, } else //Sync { - readBytes = FixedSizeReader.ReadPacket(InnerStream, InternalBuffer, 0, readBytes); + readBytes = FixedSizeReader.ReadPacket(InnerStream, InternalBuffer!, 0, readBytes); } return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest); } - private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) + private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest? asyncRequest) { if (readBytes == 0) { @@ -345,7 +345,7 @@ private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count // Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_ int internalOffset; - readBytes = _negoState.DecryptData(InternalBuffer, 0, readBytes, out internalOffset); + readBytes = _negoState.DecryptData(InternalBuffer!, 0, readBytes, out internalOffset); // Decrypted data start from zero offset, the size can be shrunk after decryption. AdjustInternalBufferOffsetSize(readBytes, internalOffset); @@ -361,7 +361,7 @@ private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count readBytes = count; } - Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes); + Buffer.BlockCopy(InternalBuffer!, InternalOffset, buffer, offset, readBytes); // This will adjust both the remaining internal buffer count and the offset. DecrementInternalBufferCount(readBytes); @@ -383,7 +383,7 @@ private static void WriteCallback(IAsyncResult transportResult) NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest."); } - AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState; + AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState!; try { @@ -395,7 +395,7 @@ private static void WriteCallback(IAsyncResult transportResult) asyncRequest.Count = -1; } - negoStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); + negoStream.StartWriting(asyncRequest.Buffer!, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { @@ -418,7 +418,7 @@ private static void ReadCallback(AsyncProtocolRequest asyncRequest) BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; // This is an optimization to avoid an additional callback. - if ((object)asyncRequest.Buffer == (object)negoStream._ReadHeader) + if ((object?)asyncRequest.Buffer == (object?)negoStream._ReadHeader) { negoStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs index e18cf9f3b5b46b..abc42dfe2eb025 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs @@ -28,10 +28,10 @@ internal class NegoState private readonly Stream _innerStream; - private Exception _exception; + private Exception? _exception; - private StreamFramer _framer; - private NTAuthentication _context; + private StreamFramer? _framer; + private NTAuthentication? _context; private int _nestedAuth; @@ -45,7 +45,7 @@ internal class NegoState private uint _writeSequenceNumber; private uint _readSequenceNumber; - private ExtendedProtectionPolicy _extendedProtectionPolicy; + private ExtendedProtectionPolicy? _extendedProtectionPolicy; // SSPI does not send a server ack on successful auth. // This is a state variable used to gracefully handle auth confirmation. @@ -69,14 +69,14 @@ internal static string DefaultPackage internal IIdentity GetIdentity() { CheckThrow(true); - return NegotiateStreamPal.GetIdentity(_context); + return NegotiateStreamPal.GetIdentity(_context!); } internal void ValidateCreateContext( string package, NetworkCredential credential, string servicePrincipalName, - ExtendedProtectionPolicy policy, + ExtendedProtectionPolicy? policy, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { @@ -95,15 +95,15 @@ internal void ValidateCreateContext( _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } - ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel); + ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy!.CustomChannelBinding, protectionLevel, impersonationLevel); } internal void ValidateCreateContext( string package, bool isServer, NetworkCredential credential, - string servicePrincipalName, - ChannelBinding channelBinding, + string? servicePrincipalName, + ChannelBinding? channelBinding, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { @@ -162,7 +162,7 @@ internal void ValidateCreateContext( if (isServer) { - if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) + if (_extendedProtectionPolicy!.PolicyEnforcement == PolicyEnforcement.WhenSupported) { flags |= ContextFlagsPal.AllowMissingBindings; } @@ -196,7 +196,7 @@ internal void ValidateCreateContext( try { - _context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding); + _context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding!); } catch (Win32Exception e) { @@ -216,7 +216,7 @@ private Exception SetException(Exception e) _context.CloseContext(); } - return _exception; + return _exception!; } internal bool IsAuthenticated @@ -237,7 +237,7 @@ internal bool IsMutuallyAuthenticated } // Suppressing for NTLM since SSPI does not return correct value in the context flags. - if (_context.IsNTLM) + if (_context!.IsNTLM) { return false; } @@ -250,7 +250,7 @@ internal bool IsEncrypted { get { - return IsAuthenticated && _context.IsConfidentialityFlag; + return IsAuthenticated && _context!.IsConfidentialityFlag; } } @@ -258,7 +258,7 @@ internal bool IsSigned { get { - return IsAuthenticated && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag); + return IsAuthenticated && (_context!.IsIntegrityFlag || _context.IsConfidentialityFlag); } } @@ -274,7 +274,7 @@ internal bool CanGetSecureStream { get { - return (_context.IsConfidentialityFlag || _context.IsIntegrityFlag); + return (_context!.IsConfidentialityFlag || _context.IsIntegrityFlag); } } @@ -292,7 +292,7 @@ private TokenImpersonationLevel PrivateImpersonationLevel get { // We should suppress the delegate flag in NTLM case. - return (_context.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM) ? TokenImpersonationLevel.Delegation + return (_context!.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM) ? TokenImpersonationLevel.Delegation : _context.IsIdentifyFlag ? TokenImpersonationLevel.Identification : TokenImpersonationLevel.Impersonation; } @@ -302,7 +302,7 @@ private bool HandshakeComplete { get { - return _context.IsCompleted && _context.IsValidContext; + return _context!.IsCompleted && _context.IsValidContext; } } @@ -332,7 +332,7 @@ internal void Close() } } - internal void ProcessAuthentication(LazyAsyncResult lazyResult) + internal void ProcessAuthentication(LazyAsyncResult? lazyResult) { CheckThrow(false); if (Interlocked.Exchange(ref _nestedAuth, 1) == 1) @@ -342,7 +342,7 @@ internal void ProcessAuthentication(LazyAsyncResult lazyResult) try { - if (_context.IsServer) + if (_context!.IsServer) { // Listen for a client blob. StartReceiveBlob(lazyResult); @@ -375,7 +375,7 @@ internal void EndProcessAuthentication(IAsyncResult result) throw new ArgumentNullException("asyncResult"); } - LazyAsyncResult lazyResult = result as LazyAsyncResult; + LazyAsyncResult? lazyResult = result as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult"); @@ -389,7 +389,7 @@ internal void EndProcessAuthentication(IAsyncResult result) // No "artificial" timeouts implemented so far, InnerStream controls that. lazyResult.InternalWaitForCompletion(); - Exception e = lazyResult.Result as Exception; + Exception? e = lazyResult.Result as Exception; if (e != null) { @@ -401,18 +401,18 @@ internal void EndProcessAuthentication(IAsyncResult result) private bool CheckSpn() { - if (_context.IsKerberos) + if (_context!.IsKerberos) { return true; } - if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Never || + if (_extendedProtectionPolicy!.PolicyEnforcement == PolicyEnforcement.Never || _extendedProtectionPolicy.CustomServiceNames == null) { return true; } - string clientSpn = _context.ClientSpecifiedSpn; + string? clientSpn = _context.ClientSpecifiedSpn; if (string.IsNullOrEmpty(clientSpn)) { @@ -432,9 +432,9 @@ private bool CheckSpn() // // Client side starts here, but server also loops through this method. // - private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) + private void StartSendBlob(byte[]? message, LazyAsyncResult? lazyResult) { - Exception exception = null; + Exception? exception = null; if (message != s_emptyMessage) { message = GetOutgoingBlob(message, ref exception); @@ -443,13 +443,13 @@ private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) if (exception != null) { // Signal remote side on a failed attempt. - StartSendAuthResetSignal(lazyResult, message, exception); + StartSendAuthResetSignal(lazyResult, message!, exception); return; } if (HandshakeComplete) { - if (_context.IsServer && !CheckSpn()) + if (_context!.IsServer && !CheckSpn()) { exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch); int statusCode = ERROR_TRUST_FAILURE; @@ -500,7 +500,7 @@ private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) } // Signal remote party that we are done - _framer.WriteHeader.MessageId = FrameHeader.HandshakeDoneId; + _framer!.WriteHeader.MessageId = FrameHeader.HandshakeDoneId; if (_context.IsServer) { // Server may complete now because client SSPI would not complain at this point. @@ -524,11 +524,11 @@ private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) //even if we are completed, there could be a blob for sending. if (lazyResult == null) { - _framer.WriteMessage(message); + _framer!.WriteMessage(message); } else { - IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); + IAsyncResult ar = _framer!.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; @@ -542,7 +542,7 @@ private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) // // This will check and logically complete the auth handshake. // - private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult) + private void CheckCompletionBeforeNextReceive(LazyAsyncResult? lazyResult) { if (HandshakeComplete && _remoteOk) { @@ -561,9 +561,11 @@ private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult) // // Server side starts here, but client also loops through this method. // - private void StartReceiveBlob(LazyAsyncResult lazyResult) + private void StartReceiveBlob(LazyAsyncResult? lazyResult) { - byte[] message; + Debug.Assert(_framer != null); + + byte[]? message; if (lazyResult == null) { message = _framer.ReadMessage(); @@ -582,7 +584,7 @@ private void StartReceiveBlob(LazyAsyncResult lazyResult) ProcessReceivedBlob(message, lazyResult); } - private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult) + private void ProcessReceivedBlob(byte[]? message, LazyAsyncResult? lazyResult) { // This is an EOF otherwise we would get at least *empty* message but not a null one. if (message == null) @@ -591,7 +593,7 @@ private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult) } // Process Header information. - if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeErrId) + if (_framer!.ReadHeader.MessageId == FrameHeader.HandshakeErrId) { if (message.Length >= 8) // sizeof(long) { @@ -623,14 +625,14 @@ private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult) // // This will check and logically complete the auth handshake. // - private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult) + private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult? lazyResult) { //If we are done don't go into send. if (HandshakeComplete) { if (!_remoteOk) { - throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null); + throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer!.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null); } if (lazyResult != null) { @@ -648,9 +650,9 @@ private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyR // This is to reset auth state on the remote side. // If this write succeeds we will allow auth retrying. // - private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception) + private void StartSendAuthResetSignal(LazyAsyncResult? lazyResult, byte[] message, Exception exception) { - _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId; + _framer!.WriteHeader.MessageId = FrameHeader.HandshakeErrId; if (IsLogonDeniedException(exception)) { @@ -701,13 +703,13 @@ private static void WriteCallback(IAsyncResult transportResult) return; } - LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; + LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState!; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; - authState._framer.EndWriteMessage(transportResult); + authState._framer!.EndWriteMessage(transportResult); // Special case for an error notification. if (lazyResult.Result is Exception e) @@ -742,13 +744,13 @@ private static void ReadCallback(IAsyncResult transportResult) return; } - LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; + LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState!; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; - byte[] message = authState._framer.EndReadMessage(transportResult); + byte[]? message = authState._framer!.EndReadMessage(transportResult); authState.ProcessReceivedBlob(message, lazyResult); } catch (Exception e) @@ -768,9 +770,9 @@ internal static bool IsError(SecurityStatusPal status) return ((int)status.ErrorCode >= (int)SecurityStatusPalErrorCode.OutOfMemory); } - private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Exception e) + private unsafe byte[]? GetOutgoingBlob(byte[]? incomingBlob, ref Exception? e) { - byte[] message = _context.GetOutgoingBlob(incomingBlob, false, out SecurityStatusPal statusCode); + byte[]? message = _context!.GetOutgoingBlob(incomingBlob, false, out SecurityStatusPal statusCode); if (IsError(statusCode)) { @@ -793,13 +795,13 @@ private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Exception e) return message; } - internal int EncryptData(byte[] buffer, int offset, int count, ref byte[] outBuffer) + internal int EncryptData(byte[] buffer, int offset, int count, ref byte[]? outBuffer) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_writeSequenceNumber; - return _context.Encrypt(buffer, offset, count, ref outBuffer, _writeSequenceNumber); + return _context!.Encrypt(buffer, offset, count, ref outBuffer, _writeSequenceNumber); } internal int DecryptData(byte[] buffer, int offset, int count, out int newOffset) @@ -808,7 +810,7 @@ internal int DecryptData(byte[] buffer, int offset, int count, out int newOffset // SSPI seems to ignore this sequence number. ++_readSequenceNumber; - return _context.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber); + return _context!.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber); } internal static void ThrowCredentialException(long error) @@ -830,7 +832,7 @@ internal static void ThrowCredentialException(long error) internal static bool IsLogonDeniedException(Exception exception) { - Win32Exception win32exception = exception as Win32Exception; + Win32Exception? win32exception = exception as Win32Exception; return (win32exception != null) && (win32exception.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs index d96fdf867355c1..7fdf5ab50f3d8e 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs @@ -29,7 +29,7 @@ public partial class NegotiateStream : AuthenticatedStream { private readonly NegoState _negoState; private readonly string _package; - private IIdentity _remoteIdentity; + private IIdentity? _remoteIdentity; public NegotiateStream(Stream innerStream) : this(innerStream, false) { @@ -49,21 +49,21 @@ public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(inn #endif } - public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } - public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } - public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, @@ -75,8 +75,8 @@ public virtual IAsyncResult BeginAuthenticateAsClient( string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, - AsyncCallback asyncCallback, - object asyncState) + AsyncCallback? asyncCallback, + object? asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel, @@ -85,12 +85,12 @@ public virtual IAsyncResult BeginAuthenticateAsClient( public virtual IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, - ChannelBinding binding, + ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, - AsyncCallback asyncCallback, - object asyncState) + AsyncCallback? asyncCallback, + object? asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) @@ -124,7 +124,7 @@ public virtual void AuthenticateAsServer() AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } - public virtual void AuthenticateAsServer(ExtendedProtectionPolicy policy) + public virtual void AuthenticateAsServer(ExtendedProtectionPolicy? policy) { AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } @@ -134,7 +134,7 @@ public virtual void AuthenticateAsServer(NetworkCredential credential, Protectio AuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel); } - public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) + public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) @@ -147,12 +147,12 @@ public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedP #endif } - public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } - public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy? policy, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } @@ -161,19 +161,19 @@ public virtual IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, - AsyncCallback asyncCallback, - object asyncState) + AsyncCallback? asyncCallback, + object? asyncState) { return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, - ExtendedProtectionPolicy policy, + ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, - AsyncCallback asyncCallback, - object asyncState) + AsyncCallback? asyncCallback, + object? asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) @@ -212,7 +212,7 @@ public virtual void AuthenticateAsClient(NetworkCredential credential, string ta AuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } - public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName) + public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding? binding, string targetName) { AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } @@ -224,7 +224,7 @@ public virtual void AuthenticateAsClient( } public virtual void AuthenticateAsClient( - NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) + NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) @@ -255,13 +255,13 @@ public virtual Task AuthenticateAsClientAsync( return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } - public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding binding, string targetName) + public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding? binding, string targetName) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, binding, targetName, null); } public virtual Task AuthenticateAsClientAsync( - NetworkCredential credential, ChannelBinding binding, + NetworkCredential credential, ChannelBinding? binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { @@ -273,7 +273,7 @@ public virtual Task AuthenticateAsServerAsync() return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, null); } - public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy) + public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy? policy) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null); } @@ -284,7 +284,7 @@ public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, Prot } public virtual Task AuthenticateAsServerAsync( - NetworkCredential credential, ExtendedProtectionPolicy policy, + NetworkCredential credential, ExtendedProtectionPolicy? policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { @@ -578,7 +578,7 @@ public override void Write(byte[] buffer, int offset, int count) #endif } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) @@ -619,7 +619,7 @@ public override int EndRead(IAsyncResult asyncResult) throw new ArgumentNullException(nameof(asyncResult)); } - BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; + BufferAsyncResult? bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); @@ -650,7 +650,7 @@ public override int EndRead(IAsyncResult asyncResult) } // // - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) @@ -692,7 +692,7 @@ public override void EndWrite(IAsyncResult asyncResult) throw new ArgumentNullException(nameof(asyncResult)); } - BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; + BufferAsyncResult? bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs index 48a7efb2b73926..cbd1ca5666ae28 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs @@ -21,7 +21,7 @@ internal static IIdentity GetIdentity(NTAuthentication context) if (context.IsServer) { - var safeContext = context.GetContext(out var status); + SafeDeleteContext safeContext = context.GetContext(out var status)!; if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { throw new Win32Exception((int)status.ErrorCode); @@ -33,7 +33,7 @@ internal static IIdentity GetIdentity(NTAuthentication context) } - internal static string QueryContextAssociatedName(SafeDeleteContext securityContext) + internal static string QueryContextAssociatedName(SafeDeleteContext? securityContext) { throw new PlatformNotSupportedException(SR.net_nego_server_not_supported); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs index 5a7023a3607f74..9c80ef935309a0 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -20,17 +20,17 @@ internal static partial class NegotiateStreamPal { internal static IIdentity GetIdentity(NTAuthentication context) { - IIdentity result = null; - string name = context.IsServer ? context.AssociatedName : context.Spn; + IIdentity? result = null; + string name = context.IsServer ? context.AssociatedName! : context.Spn; string protocol = context.ProtocolName; if (context.IsServer) { - SecurityContextTokenHandle token = null; + SecurityContextTokenHandle? token = null; try { SecurityStatusPal status; - SafeDeleteContext securityContext = context.GetContext(out status); + SafeDeleteContext? securityContext = context.GetContext(out status); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { throw new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status)); @@ -40,7 +40,7 @@ internal static IIdentity GetIdentity(NTAuthentication context) // This token can be used for impersonation. We use it to create a WindowsIdentity and hand it out to the server app. Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.QuerySecurityContextToken( GlobalSSPI.SSPIAuth, - securityContext, + securityContext!, out token); if (winStatus != Interop.SECURITY_STATUS.OK) { @@ -68,7 +68,7 @@ internal static IIdentity GetIdentity(NTAuthentication context) return result; } - internal static string QueryContextAssociatedName(SafeDeleteContext securityContext) + internal static string? QueryContextAssociatedName(SafeDeleteContext securityContext) { return SSPIWrapper.QueryStringContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES); } @@ -90,7 +90,7 @@ internal static int Encrypt( int count, bool isConfidential, bool isNtlm, - ref byte[] output, + ref byte[]? output, uint sequenceNumber) { SecPkgContext_Sizes sizes = default; @@ -179,7 +179,7 @@ internal static int Encrypt( internal static int Decrypt( SafeDeleteContext securityContext, - byte[] buffer, + byte[]? buffer, int offset, int count, bool isConfidential, @@ -240,7 +240,7 @@ internal static int Decrypt( private static int DecryptNtlm( SafeDeleteContext securityContext, - byte[] buffer, + byte[]? buffer, int offset, int count, bool isConfidential, diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs index a7dcea6f6162e7..74556c73180804 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs @@ -37,7 +37,7 @@ public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.Credent } [NonEvent] - public void InitializeSecurityContext(SafeFreeCredentials credential, SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags) + public void InitializeSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) { if (IsEnabled()) { @@ -45,11 +45,11 @@ public void InitializeSecurityContext(SafeFreeCredentials credential, SafeDelete } } [Event(InitializeSecurityContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void InitializeSecurityContext(string credential, string context, string targetName, Interop.SspiCli.ContextFlags inFlags) => + private void InitializeSecurityContext(string credential, string context, string? targetName, Interop.SspiCli.ContextFlags inFlags) => WriteEvent(InitializeSecurityContextId, credential, context, targetName, (int)inFlags); [NonEvent] - public void AcceptSecurityContext(SafeFreeCredentials credential, SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags) + public void AcceptSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, Interop.SspiCli.ContextFlags inFlags) { if (IsEnabled()) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs index f0ab6630876eef..7b9dcc68c6efde 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs @@ -36,7 +36,7 @@ internal sealed partial class NetEventSource private const int RemoteCertificateInvalidId = RemoteCertificateSuccesId + 1; [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void EnumerateSecurityPackages(string securityPackage) + public void EnumerateSecurityPackages(string? securityPackage) { if (IsEnabled()) { @@ -54,7 +54,7 @@ public void SspiPackageNotFound(string packageName) } [NonEvent] - public void SecureChannelCtor(SecureChannel secureChannel, string hostname, X509CertificateCollection clientCertificates, EncryptionPolicy encryptionPolicy) + public void SecureChannelCtor(SecureChannel secureChannel, string hostname, X509CertificateCollection? clientCertificates, EncryptionPolicy encryptionPolicy) { if (IsEnabled()) { @@ -114,7 +114,7 @@ private void NotFoundCertInStore(int secureChannelHash) => WriteEvent(NotFoundCertInStoreId, secureChannelHash); [NonEvent] - public void RemoteCertificate(X509Certificate remoteCertificate) + public void RemoteCertificate(X509Certificate? remoteCertificate) { if (IsEnabled()) { @@ -122,7 +122,7 @@ public void RemoteCertificate(X509Certificate remoteCertificate) } } [Event(RemoteCertificateId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void RemoteCertificate(string remoteCertificate) => + private void RemoteCertificate(string? remoteCertificate) => WriteEvent(RemoteCertificateId, remoteCertificate); [NonEvent] @@ -162,7 +162,7 @@ private void NoDelegateButClientCert(int secureChannelHash) => WriteEvent(NoDelegateButClientCertId, secureChannelHash); [NonEvent] - public void AttemptingRestartUsingCert(X509Certificate clientCertificate, SecureChannel secureChannel) + public void AttemptingRestartUsingCert(X509Certificate? clientCertificate, SecureChannel secureChannel) { if (IsEnabled()) { @@ -170,7 +170,7 @@ public void AttemptingRestartUsingCert(X509Certificate clientCertificate, Secure } } [Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void AttemptingRestartUsingCert(string clientCertificate, int secureChannelHash) => + private void AttemptingRestartUsingCert(string? clientCertificate, int secureChannelHash) => WriteEvent(AttemptingRestartUsingCertId, clientCertificate, secureChannelHash); [NonEvent] @@ -206,7 +206,7 @@ public void SelectedCert(X509Certificate clientCertificate, SecureChannel secure } } [Event(SelectedCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void SelectedCert(string clientCertificate, int secureChannelHash) => + private void SelectedCert(string? clientCertificate, int secureChannelHash) => WriteEvent(SelectedCertId, clientCertificate, secureChannelHash); [NonEvent] @@ -312,9 +312,9 @@ public void RemoteCertUserDeclaredInvalid(SecureChannel secureChannel) private void RemoteCertUserDeclaredInvalid(int secureChannelHash) => WriteEvent(RemoteCertificateInvalidId, secureChannelHash); - static partial void AdditionalCustomizedToString(T value, ref string result) + static partial void AdditionalCustomizedToString(T value, ref string? result) { - X509Certificate cert = value as X509Certificate; + X509Certificate? cert = value as X509Certificate; if (cert != null) { result = cert.ToString(fVerbose: true); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs index 23c08dde5c10d8..02e672c452ab8d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs @@ -10,9 +10,9 @@ namespace System.Net.Security { internal static class EndpointChannelBindingToken { - internal static ChannelBinding Build(SafeDeleteContext securityContext) + internal static ChannelBinding? Build(SafeDeleteContext securityContext) { - using (X509Certificate2 cert = CertificateValidationPal.GetRemoteCertificate(securityContext)) + using (X509Certificate2? cert = CertificateValidationPal.GetRemoteCertificate(securityContext)) { if (cert == null) return null; @@ -61,4 +61,4 @@ private static HashAlgorithm GetHashForChannelBinding(X509Certificate2 cert) } } } -} \ No newline at end of file +} diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs index 1db55ec02444ab..222fba5549dc23 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs @@ -144,7 +144,7 @@ protected override void Dispose(bool disposing) if (null != _sslContext) { _sslContext.Dispose(); - _sslContext = null; + _sslContext = null!; } } @@ -233,7 +233,7 @@ internal void Write(ReadOnlySpan buf) internal int BytesReadyForConnection => _toConnection.Count; - internal byte[] ReadPendingWrites() + internal byte[]? ReadPendingWrites() { lock (_toConnection) { @@ -356,7 +356,7 @@ private static void SetCertificate(SafeSslHandle sslContext, X509Certificate2 ce X509Chain chain = TLSCertificateExtensions.BuildNewChain( certificate, - includeClientApplicationPolicy: false); + includeClientApplicationPolicy: false)!; using (chain) { @@ -377,7 +377,7 @@ private static void SetCertificate(SafeSslHandle sslContext, X509Certificate2 ce for (int i = 0; i < intermediateCerts.Length; i++) { - X509Certificate2 intermediateCert = elements[i + 1].Certificate; + X509Certificate2 intermediateCert = elements[i + 1].Certificate!; if (intermediateCert.HasPrivateKey) { @@ -402,7 +402,7 @@ private static void SetCertificate(SafeSslHandle sslContext, X509Certificate2 ce // And since the intermediateCerts could have been new instances, Dispose them, too for (int i = 0; i < elements.Count; i++) { - elements[i].Certificate.Dispose(); + elements[i].Certificate!.Dispose(); if (i < intermediateCerts.Length) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs index 488ffc9acf7c62..1b4b47c7ff58e1 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeFreeSslCredentials.cs @@ -18,7 +18,7 @@ public SafeFreeSslCredentials(X509Certificate certificate, SslProtocols protocol certificate == null || certificate is X509Certificate2, "Only X509Certificate2 certificates are supported at this time"); - X509Certificate2 cert = (X509Certificate2)certificate; + X509Certificate2? cert = (X509Certificate2?)certificate; if (cert != null) { @@ -43,7 +43,7 @@ public SafeFreeSslCredentials(X509Certificate certificate, SslProtocols protocol public SslProtocols Protocols { get; } - public X509Certificate2 Certificate { get; } + public X509Certificate2? Certificate { get; } public override bool IsInvalid => false; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs index 164ea48e7ad6f3..82aab9fe951968 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs @@ -21,11 +21,11 @@ internal class SecureChannel // When reading a frame from the wire first read this many bytes for the header. internal const int ReadHeaderSize = 5; - private SafeFreeCredentials _credentialsHandle; - private SafeDeleteSslContext _securityContext; + private SafeFreeCredentials? _credentialsHandle; + private SafeDeleteSslContext? _securityContext; - private SslConnectionInfo _connectionInfo; - private X509Certificate _selectedClientCertificate; + private SslConnectionInfo? _connectionInfo; + private X509Certificate? _selectedClientCertificate; private bool _isRemoteCertificateAvailable; // These are the MAX encrypt buffer output sizes, not the actual sizes. @@ -46,7 +46,7 @@ internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions) if (NetEventSource.IsEnabled) { NetEventSource.Enter(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates); - NetEventSource.Log.SecureChannelCtor(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy); + NetEventSource.Log.SecureChannelCtor(this, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy); } SslStreamPal.VerifyPackageInfo(); @@ -73,7 +73,7 @@ internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions) // HeaderSize - Header & trailer sizes used in the TLS stream // TrailerSize - // - internal X509Certificate LocalServerCertificate + internal X509Certificate? LocalServerCertificate { get { @@ -81,7 +81,7 @@ internal X509Certificate LocalServerCertificate } } - internal X509Certificate LocalClientCertificate + internal X509Certificate? LocalClientCertificate { get { @@ -97,12 +97,12 @@ internal bool IsRemoteCertificateAvailable } } - internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) + internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, kind); - ChannelBinding result = null; + ChannelBinding? result = null; if (_securityContext != null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); @@ -129,7 +129,7 @@ internal int MaxDataSize } } - internal SslConnectionInfo ConnectionInfo + internal SslConnectionInfo? ConnectionInfo { get { @@ -186,7 +186,7 @@ internal void Close() // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // - private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) + private X509Certificate2? EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) { @@ -199,7 +199,7 @@ private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) try { // Protecting from X509Certificate2 derived classes. - X509Certificate2 certEx = MakeEx(certificate); + X509Certificate2? certEx = MakeEx(certificate); if (certEx != null) { @@ -218,11 +218,11 @@ private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) } X509Certificate2Collection collectionEx; - string certHash = certEx.Thumbprint; + string certHash = certEx!.Thumbprint; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. - X509Store store = CertificateValidationPal.EnsureStoreOpened(_sslAuthenticationOptions.IsServer); + X509Store? store = CertificateValidationPal.EnsureStoreOpened(_sslAuthenticationOptions.IsServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); @@ -255,7 +255,7 @@ private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) return null; } - private static X509Certificate2 MakeEx(X509Certificate certificate) + private static X509Certificate2? MakeEx(X509Certificate certificate) { Debug.Assert(certificate != null, "certificate != null"); @@ -264,7 +264,7 @@ private static X509Certificate2 MakeEx(X509Certificate certificate) return (X509Certificate2)certificate; } - X509Certificate2 certificateEx = null; + X509Certificate2? certificateEx = null; try { if (certificate.Handle != IntPtr.Zero) @@ -288,7 +288,7 @@ private string[] GetRequestCertificateAuthorities() if (IsValidContext) { - issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext); + issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext!); } return issuers; } @@ -330,14 +330,14 @@ This will not restart a session but helps minimizing the number of handles we cr --*/ - private bool AcquireClientCredentials(ref byte[] thumbPrint) + private bool AcquireClientCredentials(ref byte[]? thumbPrint) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // Acquire possible Client Certificate information and set it on the handle. - X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart. - List filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet. + X509Certificate? clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart. + List? filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers; // This is a list of issuers sent by the server, only valid is we do know what the server cert is. bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds. @@ -349,15 +349,15 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling CertificateSelectionCallback"); - X509Certificate2 remoteCert = null; + X509Certificate2? remoteCert = null; try { - remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext); + remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext!); if (_sslAuthenticationOptions.ClientCertificates == null) { _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); } - clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); + clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost!, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); } finally { @@ -433,8 +433,8 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) // if (issuers != null && issuers.Length != 0) { - X509Certificate2 certificateEx = null; - X509Chain chain = null; + X509Certificate2? certificateEx = null; + X509Chain? chain = null; try { certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]); @@ -461,7 +461,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) int elementsCount = chain.ChainElements.Count; for (int ii = 0; ii < elementsCount; ++ii) { - string issuer = chain.ChainElements[ii].Certificate.Issuer; + string issuer = chain.ChainElements[ii].Certificate!.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { @@ -488,7 +488,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) int elementsCount = chain.ChainElements.Count; for (int element = 0; element < elementsCount; element++) { - chain.ChainElements[element].Certificate.Dispose(); + chain.ChainElements[element].Certificate!.Dispose(); } } @@ -507,7 +507,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) } bool cachedCred = false; // This is a return result from this method. - X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it). + X509Certificate2? selectedCert = null; // This is a final selected cert (ensured that it does have private key with it). clientCertificate = null; @@ -547,7 +547,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) } } - if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert)) + if ((object?)clientCertificate != (object?)selectedCert && !clientCertificate!.Equals(selectedCert)) { NetEventSource.Fail(this, "'selectedCert' does not match 'clientCertificate'."); } @@ -561,8 +561,8 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // - byte[] guessedThumbPrint = selectedCert?.GetCertHash(); - SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); + byte[]? guessedThumbPrint = selectedCert?.GetCertHash(); + SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential @@ -579,7 +579,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. - if ((object)clientCertificate != (object)selectedCert) + if ((object?)clientCertificate != (object?)selectedCert) { selectedCert.Dispose(); } @@ -600,7 +600,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) } else { - _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer); + _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert!, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. _selectedClientCertificate = clientCertificate; @@ -609,7 +609,7 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) finally { // An extra cert could have been created, dispose it now. - if (selectedCert != null && (object)clientCertificate != (object)selectedCert) + if (selectedCert != null && (object?)clientCertificate != (object?)selectedCert) { selectedCert.Dispose(); } @@ -620,17 +620,17 @@ private bool AcquireClientCredentials(ref byte[] thumbPrint) return cachedCred; } - private static List EnsureInitialized(ref List list) => list ?? (list = new List()); + private static List EnsureInitialized(ref List? list) => list ?? (list = new List()); // // Acquire Server Side Certificate information and set it on the class. // - private bool AcquireServerCredentials(ref byte[] thumbPrint, ReadOnlySpan clientHello) + private bool AcquireServerCredentials(ref byte[]? thumbPrint, ReadOnlySpan clientHello) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); - X509Certificate localCertificate = null; + X509Certificate? localCertificate = null; bool cachedCred = false; // There are three options for selecting the server certificate. When @@ -639,7 +639,7 @@ private bool AcquireServerCredentials(ref byte[] thumbPrint, ReadOnlySpan // with .NET Framework), and if neither is set we fall back to using ServerCertificate. if (_sslAuthenticationOptions.ServerCertSelectionDelegate != null) { - string serverIdentity = SniHelper.GetServerName(clientHello); + string? serverIdentity = SniHelper.GetServerName(clientHello); localCertificate = _sslAuthenticationOptions.ServerCertSelectionDelegate(serverIdentity); if (localCertificate == null) @@ -650,7 +650,7 @@ private bool AcquireServerCredentials(ref byte[] thumbPrint, ReadOnlySpan else if (_sslAuthenticationOptions.CertSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); - tempCollection.Add(_sslAuthenticationOptions.ServerCertificate); + tempCollection.Add(_sslAuthenticationOptions.ServerCertificate!); // We pass string.Empty here to maintain strict compatability with .NET Framework. localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty()); if (NetEventSource.IsEnabled) @@ -669,7 +669,7 @@ private bool AcquireServerCredentials(ref byte[] thumbPrint, ReadOnlySpan // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. - X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate); + X509Certificate2? selectedCert = EnsurePrivateKey(localCertificate); if (selectedCert == null) { @@ -687,7 +687,7 @@ private bool AcquireServerCredentials(ref byte[] thumbPrint, ReadOnlySpan byte[] guessedThumbPrint = selectedCert.GetCertHash(); try { - SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); + SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); if (cachedCredentialHandle != null) { @@ -722,7 +722,7 @@ internal ProtocolToken NextMessage(ReadOnlySpan incomingBuffer) if (NetEventSource.IsEnabled) NetEventSource.Enter(this); - byte[] nextmsg = null; + byte[]? nextmsg = null; SecurityStatusPal status = GenerateToken(incomingBuffer, ref nextmsg); if (!_sslAuthenticationOptions.IsServer && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded) @@ -740,7 +740,7 @@ internal ProtocolToken NextMessage(ReadOnlySpan incomingBuffer) { if (token.Failed) { - NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException().Message}"); + NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException()!.Message}"); } NetEventSource.Exit(this, token); @@ -763,14 +763,14 @@ server in response Return: status - error information --*/ - private SecurityStatusPal GenerateToken(ReadOnlySpan inputBuffer, ref byte[] output) + private SecurityStatusPal GenerateToken(ReadOnlySpan inputBuffer, ref byte[]? output) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}"); - byte[] result = Array.Empty(); + byte[]? result = Array.Empty(); SecurityStatusPal status = default; bool cachedCreds = false; - byte[] thumbPrint = null; + byte[]? thumbPrint = null; // // Looping through ASC or ISC with potentially cached credential that could have been @@ -791,7 +791,7 @@ private SecurityStatusPal GenerateToken(ReadOnlySpan inputBuffer, ref byte if (_sslAuthenticationOptions.IsServer) { status = SslStreamPal.AcceptSecurityContext( - ref _credentialsHandle, + ref _credentialsHandle!, ref _securityContext, inputBuffer, ref result, @@ -800,7 +800,7 @@ private SecurityStatusPal GenerateToken(ReadOnlySpan inputBuffer, ref byte else { status = SslStreamPal.InitializeSecurityContext( - ref _credentialsHandle, + ref _credentialsHandle!, ref _securityContext, _sslAuthenticationOptions.TargetHost, inputBuffer, @@ -856,11 +856,11 @@ internal void ProcessHandshakeSuccess() if (_negotiatedApplicationProtocol == default) { // try to get ALPN info unless we already have it. (renegotiation) - byte[] alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext); + byte[]? alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext!); _negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false); } - SslStreamPal.QueryContextStreamSizes(_securityContext, out StreamSizes streamSizes); + SslStreamPal.QueryContextStreamSizes(_securityContext!, out StreamSizes streamSizes); try { @@ -876,7 +876,7 @@ internal void ProcessHandshakeSuccess() throw; } - SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo); + SslStreamPal.QueryContextConnectionInfo(_securityContext!, out _connectionInfo); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); @@ -905,7 +905,7 @@ internal SecurityStatusPal Encrypt(ReadOnlyMemory buffer, ref byte[] outpu byte[] writeBuffer = output; SecurityStatusPal secStatus = SslStreamPal.EncryptMessage( - _securityContext, + _securityContext!, buffer, _headerSize, _trailerSize, @@ -927,7 +927,7 @@ internal SecurityStatusPal Encrypt(ReadOnlyMemory buffer, ref byte[] outpu return secStatus; } - internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count) + internal SecurityStatusPal Decrypt(byte[]? payload, ref int offset, ref int count) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, payload, offset, count); @@ -944,7 +944,7 @@ internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count throw new ArgumentOutOfRangeException(nameof(count)); } - return SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count); + return SslStreamPal.DecryptMessage(_securityContext!, payload!, ref offset, ref count); } /*++ @@ -955,7 +955,7 @@ internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count --*/ //This method validates a remote certificate. - internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback, ref ProtocolToken alertToken) + internal bool VerifyRemoteCertificate(RemoteCertValidationCallback? remoteCertValidationCallback, ref ProtocolToken? alertToken) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); @@ -964,9 +964,9 @@ internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertVal // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true. bool success = false; - X509Chain chain = null; - X509Certificate2 remoteCertificateEx = null; - X509Certificate2Collection remoteCertificateStore = null; + X509Chain? chain = null; + X509Certificate2? remoteCertificateEx = null; + X509Certificate2Collection? remoteCertificateStore = null; try { @@ -994,7 +994,7 @@ internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertVal } sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties( - _securityContext, + _securityContext!, chain, remoteCertificateEx, _sslAuthenticationOptions.CheckCertName, @@ -1020,14 +1020,14 @@ internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertVal if (NetEventSource.IsEnabled) { - LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain); + LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain!); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Cert validation, remote cert = {remoteCertificateEx}"); } if (!success) { - alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain); + alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain!); } } finally @@ -1040,7 +1040,7 @@ internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertVal int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) { - chain.ChainElements[i].Certificate.Dispose(); + chain.ChainElements[i].Certificate!.Dispose(); } chain.Dispose(); @@ -1064,7 +1064,7 @@ internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertVal return success; } - public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain) + public ProtocolToken? CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); @@ -1110,13 +1110,13 @@ public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErr return token; } - public ProtocolToken CreateShutdownToken() + public ProtocolToken? CreateShutdownToken() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); SecurityStatusPal status; - status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext); + status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext!); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { @@ -1139,7 +1139,7 @@ public ProtocolToken CreateShutdownToken() private ProtocolToken GenerateAlertToken() { - byte[] nextmsg = null; + byte[]? nextmsg = null; SecurityStatusPal status; status = GenerateToken(default, ref nextmsg); @@ -1199,7 +1199,7 @@ private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain) return TlsAlertMessage.BadCertificate; } - private void LogCertificateValidation(RemoteCertValidationCallback remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain) + private void LogCertificateValidation(RemoteCertValidationCallback? remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain) { if (!NetEventSource.IsEnabled) return; @@ -1253,7 +1253,7 @@ private void LogCertificateValidation(RemoteCertValidationCallback remoteCertVal internal class ProtocolToken { internal SecurityStatusPal Status; - internal byte[] Payload; + internal byte[]? Payload; internal int Size; internal bool Failed @@ -1288,14 +1288,14 @@ internal bool CloseConnection } } - internal ProtocolToken(byte[] data, SecurityStatusPal status) + internal ProtocolToken(byte[]? data, SecurityStatusPal status) { Status = status; Payload = data; Size = data != null ? data.Length : 0; } - internal Exception GetException() + internal Exception? GetException() { // If it's not done, then there's got to be an error, even if it's // a Handshake message up, and we only have a Warning message. diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SniHelper.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SniHelper.cs index c52e0ba84e75e7..ffbf730e7d9712 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SniHelper.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SniHelper.cs @@ -16,7 +16,7 @@ internal class SniHelper private static readonly IdnMapping s_idnMapping = CreateIdnMapping(); private static readonly Encoding s_encoding = CreateEncoding(); - public static string GetServerName(ReadOnlySpan sslPlainText) + public static string? GetServerName(ReadOnlySpan sslPlainText) { // https://tools.ietf.org/html/rfc6101#section-5.2.1 // struct { @@ -49,7 +49,7 @@ public static string GetServerName(ReadOnlySpan sslPlainText) return GetSniFromSslHandshake(sslHandshake); } - private static string GetSniFromSslHandshake(ReadOnlySpan sslHandshake) + private static string? GetSniFromSslHandshake(ReadOnlySpan sslHandshake) { // https://tools.ietf.org/html/rfc6101#section-5.6 // struct { @@ -81,7 +81,7 @@ private static string GetSniFromSslHandshake(ReadOnlySpan sslHandshake) return GetSniFromClientHello(clientHello); } - private static string GetSniFromClientHello(ReadOnlySpan clientHello) + private static string? GetSniFromClientHello(ReadOnlySpan clientHello) { // Basic structure: https://tools.ietf.org/html/rfc6101#section-5.6.1.2 // Extended structure: https://tools.ietf.org/html/rfc3546#section-2.1 @@ -119,11 +119,11 @@ private static string GetSniFromClientHello(ReadOnlySpan clientHello) return null; } - string ret = null; + string? ret = null; while (!p.IsEmpty) { bool invalid; - string sni = GetSniFromExtension(p, out p, out invalid); + string? sni = GetSniFromExtension(p, out p, out invalid); if (invalid) { return null; @@ -143,7 +143,7 @@ private static string GetSniFromClientHello(ReadOnlySpan clientHello) return ret; } - private static string GetSniFromExtension(ReadOnlySpan extension, out ReadOnlySpan remainingBytes, out bool invalid) + private static string? GetSniFromExtension(ReadOnlySpan extension, out ReadOnlySpan remainingBytes, out bool invalid) { // https://tools.ietf.org/html/rfc3546#section-2.3 // struct { @@ -173,7 +173,7 @@ private static string GetSniFromExtension(ReadOnlySpan extension, out Read } } - private static string GetSniFromServerNameList(ReadOnlySpan serverNameListExtension, out ReadOnlySpan remainingBytes, out bool invalid) + private static string? GetSniFromServerNameList(ReadOnlySpan serverNameListExtension, out ReadOnlySpan remainingBytes, out bool invalid) { // https://tools.ietf.org/html/rfc3546#section-3.1 // struct { @@ -205,7 +205,7 @@ private static string GetSniFromServerNameList(ReadOnlySpan serverNameList return GetSniFromServerName(serverName, out invalid); } - private static string GetSniFromServerName(ReadOnlySpan serverName, out bool invalid) + private static string? GetSniFromServerName(ReadOnlySpan serverName, out bool invalid) { // https://tools.ietf.org/html/rfc3546#section-3.1 // struct { @@ -239,7 +239,7 @@ private static string GetSniFromServerName(ReadOnlySpan serverName, out bo return GetSniFromHostNameStruct(hostNameStruct, out invalid); } - private static string GetSniFromHostNameStruct(ReadOnlySpan hostNameStruct, out bool invalid) + private static string? GetSniFromHostNameStruct(ReadOnlySpan hostNameStruct, out bool invalid) { // https://tools.ietf.org/html/rfc3546#section-3.1 // HostName is an opaque type (length of sufficient size for max data length is prepended) @@ -258,7 +258,7 @@ private static string GetSniFromHostNameStruct(ReadOnlySpan hostNameStruct return DecodeString(hostName); } - private static string DecodeString(ReadOnlySpan bytes) + private static string? DecodeString(ReadOnlySpan bytes) { // https://tools.ietf.org/html/rfc3546#section-3.1 // Per spec: diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs index f15e0c8ca6fcb0..9e22964fc07359 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; @@ -54,7 +55,7 @@ public SslApplicationProtocol(string protocol) : public bool Equals(SslApplicationProtocol other) => ((ReadOnlySpan)_readOnlyProtocol).SequenceEqual(other._readOnlyProtocol); - public override bool Equals(object obj) => obj is SslApplicationProtocol protocol && Equals(protocol); + public override bool Equals(object? obj) => obj is SslApplicationProtocol protocol && Equals(protocol); public override int GetHashCode() { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs index 05a8bdc71290a6..4895d91c2e3967 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs @@ -10,7 +10,7 @@ namespace System.Net.Security { internal class SslAuthenticationOptions { - internal SslAuthenticationOptions(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback localCallback) + internal SslAuthenticationOptions(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback? localCallback) { // Common options. AllowRenegotiation = sslClientAuthenticationOptions.AllowRenegotiation; @@ -68,19 +68,19 @@ private static SslProtocols FilterOutIncompatibleSslProtocols(SslProtocols proto } internal bool AllowRenegotiation { get; set; } - internal string TargetHost { get; set; } - internal X509CertificateCollection ClientCertificates { get; set; } - internal List ApplicationProtocols { get; } + internal string? TargetHost { get; set; } + internal X509CertificateCollection? ClientCertificates { get; set; } + internal List? ApplicationProtocols { get; } internal bool IsServer { get; set; } - internal X509Certificate ServerCertificate { get; set; } + internal X509Certificate? ServerCertificate { get; set; } internal SslProtocols EnabledSslProtocols { get; set; } internal X509RevocationMode CertificateRevocationCheckMode { get; set; } internal EncryptionPolicy EncryptionPolicy { get; set; } internal bool RemoteCertRequired { get; set; } internal bool CheckCertName { get; set; } - internal RemoteCertValidationCallback CertValidationDelegate { get; set; } - internal LocalCertSelectionCallback CertSelectionDelegate { get; set; } - internal ServerCertSelectionCallback ServerCertSelectionDelegate { get; set; } - internal CipherSuitesPolicy CipherSuitesPolicy { get; set; } + internal RemoteCertValidationCallback? CertValidationDelegate { get; set; } + internal LocalCertSelectionCallback? CertSelectionDelegate { get; set; } + internal ServerCertSelectionCallback? ServerCertSelectionDelegate { get; set; } + internal CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslClientAuthenticationOptions.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslClientAuthenticationOptions.cs index bffa7d4dec8e11..b27568ac355acd 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslClientAuthenticationOptions.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslClientAuthenticationOptions.cs @@ -22,15 +22,15 @@ public bool AllowRenegotiation set => _allowRenegotiation = value; } - public LocalCertificateSelectionCallback LocalCertificateSelectionCallback { get; set; } + public LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get; set; } - public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } + public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; } - public List ApplicationProtocols { get; set; } + public List? ApplicationProtocols { get; set; } - public string TargetHost { get; set; } + public string? TargetHost { get; set; } - public X509CertificateCollection ClientCertificates { get; set; } + public X509CertificateCollection? ClientCertificates { get; set; } public X509RevocationMode CertificateRevocationCheckMode { @@ -71,6 +71,6 @@ public SslProtocols EnabledSslProtocols /// When set to null operating system default will be used. /// Use extreme caution when changing this setting. /// - public CipherSuitesPolicy CipherSuitesPolicy { get; set; } + public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslServerAuthenticationOptions.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslServerAuthenticationOptions.cs index 7fba1234c50372..ca345ad4fe0355 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslServerAuthenticationOptions.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslServerAuthenticationOptions.cs @@ -23,13 +23,13 @@ public bool AllowRenegotiation public bool ClientCertificateRequired { get; set; } - public List ApplicationProtocols { get; set; } + public List? ApplicationProtocols { get; set; } - public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } + public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; } - public ServerCertificateSelectionCallback ServerCertificateSelectionCallback { get; set; } + public ServerCertificateSelectionCallback? ServerCertificateSelectionCallback { get; set; } - public X509Certificate ServerCertificate { get; set; } + public X509Certificate? ServerCertificate { get; set; } public SslProtocols EnabledSslProtocols { @@ -70,6 +70,6 @@ public EncryptionPolicy EncryptionPolicy /// When set to null operating system default will be used. /// Use extreme caution when changing this setting. /// - public CipherSuitesPolicy CipherSuitesPolicy { get; set; } + public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs index 4975228664f5e7..b776fba580498b 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs @@ -31,7 +31,7 @@ internal static class SslSessionsCache // the caller of this ctor has to ensure that a user cert object was inspected and // optionally cloned. // - internal SslCredKey(byte[] thumbPrint, int allowedProtocols, bool isServerMode, EncryptionPolicy encryptionPolicy) + internal SslCredKey(byte[]? thumbPrint, int allowedProtocols, bool isServerMode, EncryptionPolicy encryptionPolicy) { _thumbPrint = thumbPrint ?? Array.Empty(); _allowedProtocols = allowedProtocols; @@ -69,7 +69,7 @@ public override int GetHashCode() return hashCode; } - public override bool Equals(object obj) => (obj is SslCredKey && Equals((SslCredKey)obj)); + public override bool Equals(object? obj) => (obj is SslCredKey && Equals((SslCredKey)obj)); public bool Equals(SslCredKey other) { @@ -114,7 +114,7 @@ public bool Equals(SslCredKey other) // ATTN: The returned handle can be invalid, the callers of InitializeSecurityContext and AcceptSecurityContext // must be prepared to execute a back-out code if the call fails. // - internal static SafeFreeCredentials TryCachedCredential(byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) + internal static SafeFreeCredentials? TryCachedCredential(byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { if (s_cachedCreds.Count == 0) { @@ -124,7 +124,7 @@ internal static SafeFreeCredentials TryCachedCredential(byte[] thumbPrint, SslPr var key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); - SafeCredentialReference cached; + SafeCredentialReference? cached; if (!s_cachedCreds.TryGetValue(key, out cached) || cached.IsClosed || cached.Target.IsInvalid) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Not found or invalid, Current Cache Coun = {s_cachedCreds.Count}"); @@ -141,14 +141,14 @@ internal static SafeFreeCredentials TryCachedCredential(byte[] thumbPrint, SslPr // // ATTN: The thumbPrint must be from inspected and possibly cloned user Cert object or we get a security hole in SslCredKey ctor. // - internal static void CacheCredential(SafeFreeCredentials creds, byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) + internal static void CacheCredential(SafeFreeCredentials creds, byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { if (creds == null) { NetEventSource.Fail(null, "creds == null"); } - if (creds.IsInvalid) + if (creds!.IsInvalid) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Refused to cache an Invalid Handle {creds}, Current Cache Count = {s_cachedCreds.Count}"); return; @@ -156,7 +156,7 @@ internal static void CacheCredential(SafeFreeCredentials creds, byte[] thumbPrin var key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); - SafeCredentialReference cached; + SafeCredentialReference? cached; if (!s_cachedCreds.TryGetValue(key, out cached) || cached.IsClosed || cached.Target.IsInvalid) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs index af703e0481be66..5bd0bdb1bfb8c2 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs @@ -18,7 +18,7 @@ public partial class SslStream { private static int s_uniqueNameInteger = 123; - private SslAuthenticationOptions _sslAuthenticationOptions; + private SslAuthenticationOptions? _sslAuthenticationOptions; private int _nestedAuth; @@ -61,7 +61,7 @@ private enum FrameType : byte private int _lockWriteState; private int _lockReadState; - private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback localCallback) + private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback? localCallback) { ThrowIfExceptional(); @@ -84,7 +84,7 @@ private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthe try { _sslAuthenticationOptions = new SslAuthenticationOptions(sslClientAuthenticationOptions, remoteCallback, localCallback); - if (_sslAuthenticationOptions.TargetHost.Length == 0) + if (_sslAuthenticationOptions.TargetHost!.Length == 0) { _sslAuthenticationOptions.TargetHost = "?" + Interlocked.Increment(ref s_uniqueNameInteger).ToString(NumberFormatInfo.InvariantInfo); } @@ -125,9 +125,9 @@ private void ValidateCreateContext(SslAuthenticationOptions sslAuthenticationOpt private bool RemoteCertRequired => _context == null || _context.RemoteCertRequired; - private object SyncLock => _context; + private object? SyncLock => _context; - private int MaxDataSize => _context.MaxDataSize; + private int MaxDataSize => _context!.MaxDataSize; private void SetException(Exception e) { @@ -155,7 +155,7 @@ private void CloseInternal() // subsequent Reads first check if the context is still available. if (Interlocked.CompareExchange(ref _nestedRead, 1, 0) == 0) { - byte[] buffer = _internalBuffer; + byte[]? buffer = _internalBuffer; if (buffer != null) { _internalBuffer = null; @@ -175,7 +175,7 @@ private void CloseInternal() private SecurityStatusPal EncryptData(ReadOnlyMemory buffer, ref byte[] outBuffer, out int outSize) { ThrowIfExceptionalOrNotAuthenticated(); - return _context.Encrypt(buffer, ref outBuffer, out outSize); + return _context!.Encrypt(buffer, ref outBuffer, out outSize); } private SecurityStatusPal DecryptData() @@ -184,28 +184,29 @@ private SecurityStatusPal DecryptData() return PrivateDecryptData(_internalBuffer, ref _decryptedBytesOffset, ref _decryptedBytesCount); } - private SecurityStatusPal PrivateDecryptData(byte[] buffer, ref int offset, ref int count) + private SecurityStatusPal PrivateDecryptData(byte[]? buffer, ref int offset, ref int count) { - return _context.Decrypt(buffer, ref offset, ref count); + return _context!.Decrypt(buffer, ref offset, ref count); } // // 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 ProcessAuthentication(bool isAsync = false, bool isApm = false, CancellationToken cancellationToken = default) + private Task? ProcessAuthentication(bool isAsync = false, bool isApm = false, CancellationToken cancellationToken = default) { - Task result = null; + Task? result; ThrowIfExceptional(); if (isAsync) { - result = ForceAuthenticationAsync(new AsyncSslIOAdapter(this, cancellationToken), _context.IsServer, null, isApm); + result = ForceAuthenticationAsync(new AsyncSslIOAdapter(this, cancellationToken), _context!.IsServer, null, isApm); } else { - ForceAuthenticationAsync(new SyncSslIOAdapter(this), _context.IsServer, null).GetAwaiter().GetResult(); + ForceAuthenticationAsync(new SyncSslIOAdapter(this), _context!.IsServer, null).GetAwaiter().GetResult(); + result = null; } return result; @@ -214,10 +215,10 @@ private Task ProcessAuthentication(bool isAsync = false, bool isApm = false, Can // // This is used to reply on re-handshake when received SEC_I_RENEGOTIATE on Read(). // - private async Task ReplyOnReAuthenticationAsync(TIOAdapter adapter, byte[] buffer) + private async Task ReplyOnReAuthenticationAsync(TIOAdapter adapter, byte[]? buffer) where TIOAdapter : ISslIOAdapter { - lock (SyncLock) + lock (SyncLock!) { // Note we are already inside the read, so checking for already going concurrent handshake. _lockReadState = LockHandshake; @@ -228,7 +229,7 @@ private async Task ReplyOnReAuthenticationAsync(TIOAdapter adapter, } // reAuthenticationData is only used on Windows in case of renegotiation. - private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool receiveFirst, byte[] reAuthenticationData, bool isApm = false) + private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool receiveFirst, byte[]? reAuthenticationData, bool isApm = false) where TIOAdapter : ISslIOAdapter { _framing = Framing.Unknown; @@ -248,10 +249,10 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool if (!receiveFirst) { - message = _context.NextMessage(reAuthenticationData); + message = _context!.NextMessage(reAuthenticationData); if (message.Size > 0) { - await adapter.WriteAsync(message.Payload, 0, message.Size).ConfigureAwait(false); + await adapter.WriteAsync(message.Payload!, 0, message.Size).ConfigureAwait(false); } if (message.Failed) @@ -268,7 +269,7 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool if (message.Size > 0) { // If there is message send it out even if call failed. It may contain TLS Alert. - await adapter.WriteAsync(message.Payload, 0, message.Size).ConfigureAwait(false); + await adapter.WriteAsync(message.Payload!, 0, message.Size).ConfigureAwait(false); } if (message.Failed) @@ -285,7 +286,7 @@ private async Task ForceAuthenticationAsync(TIOAdapter adapter, bool _internalBufferCount = _handshakeBuffer.ActiveLength; } - ProtocolToken alertToken = null; + ProtocolToken? alertToken = null; if (!CompleteHandshake(ref alertToken)) { SendAuthResetSignal(alertToken, ExceptionDispatchInfo.Capture(new AuthenticationException(SR.net_ssl_io_cert_validation, null))); @@ -337,7 +338,7 @@ private async ValueTask ReceiveBlobAsync(TIOAdapter a await FillHandshakeBufferAsync(adapter, frameSize).ConfigureAwait(false); } - ProtocolToken token = _context.NextMessage(_handshakeBuffer.ActiveReadOnlySpan.Slice(0, frameSize)); + ProtocolToken token = _context!.NextMessage(_handshakeBuffer.ActiveReadOnlySpan.Slice(0, frameSize)); _handshakeBuffer.Discard(frameSize); return token; @@ -347,7 +348,7 @@ private async ValueTask ReceiveBlobAsync(TIOAdapter a // This is to reset auth state on remote side. // If this write succeeds we will allow auth retrying. // - private void SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception) + private void SendAuthResetSignal(ProtocolToken? message, ExceptionDispatchInfo exception) { SetException(exception.SourceException); @@ -359,7 +360,7 @@ private void SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo ex exception.Throw(); } - InnerStream.Write(message.Payload, 0, message.Size); + InnerStream.Write(message.Payload!, 0, message.Size); exception.Throw(); } @@ -372,14 +373,14 @@ private void SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo ex // // - Returns false if failed to verify the Remote Cert // - private bool CompleteHandshake(ref ProtocolToken alertToken) + private bool CompleteHandshake(ref ProtocolToken? alertToken) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); - _context.ProcessHandshakeSuccess(); + _context!.ProcessHandshakeSuccess(); - if (!_context.VerifyRemoteCertificate(_sslAuthenticationOptions.CertValidationDelegate, ref alertToken)) + if (!_context.VerifyRemoteCertificate(_sslAuthenticationOptions!.CertValidationDelegate, ref alertToken)) { _handshakeCompleted = false; @@ -397,7 +398,7 @@ private bool CompleteHandshake(ref ProtocolToken alertToken) private void FinishHandshakeRead(int newState) { - lock (SyncLock) + lock (SyncLock!) { // Lock is redundant here. Included for clarity. int lockState = Interlocked.Exchange(ref _lockReadState, newState); @@ -426,8 +427,8 @@ private int CheckEnqueueRead(Memory buffer) return -1; } - LazyAsyncResult lazyResult = null; - lock (SyncLock) + LazyAsyncResult? lazyResult = null; + lock (SyncLock!) { // Check again under lock. if (_lockReadState != LockHandshake) @@ -440,7 +441,7 @@ private int CheckEnqueueRead(Memory buffer) _lockReadState = LockPendingRead; } // Need to exit from lock before waiting. - lazyResult.InternalWaitForCompletion(); + lazyResult!.InternalWaitForCompletion(); ThrowIfExceptionalOrNotAuthenticated(); return -1; } @@ -456,7 +457,7 @@ private ValueTask CheckEnqueueReadAsync(Memory buffer) return new ValueTask(-1); } - lock (SyncLock) + lock (SyncLock!) { // Check again under lock. if (_lockReadState != LockHandshake) @@ -483,7 +484,7 @@ private Task CheckEnqueueWriteAsync() return Task.CompletedTask; } - lock (SyncLock) + lock (SyncLock!) { if (_lockWriteState != LockHandshake) { @@ -507,8 +508,8 @@ private void CheckEnqueueWrite() return; } - LazyAsyncResult lazyResult = null; - lock (SyncLock) + LazyAsyncResult? lazyResult = null; + lock (SyncLock!) { if (_lockWriteState != LockHandshake) { @@ -521,7 +522,7 @@ private void CheckEnqueueWrite() } // Need to exit from lock before waiting. - lazyResult.InternalWaitForCompletion(); + lazyResult!.InternalWaitForCompletion(); ThrowIfExceptionalOrNotAuthenticated(); return; } @@ -537,7 +538,7 @@ private void FinishWrite() private void FinishHandshake(Exception e) { - lock (SyncLock) + lock (SyncLock!) { if (e != null) { @@ -742,11 +743,11 @@ private async ValueTask ReadAsyncInternal(TIOAdapter adapter, M if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { - byte[] extraBuffer = null; + byte[]? extraBuffer = null; if (_decryptedBytesCount != 0) { extraBuffer = new byte[_decryptedBytesCount]; - Buffer.BlockCopy(_internalBuffer, _decryptedBytesOffset, extraBuffer, 0, _decryptedBytesCount); + Buffer.BlockCopy(_internalBuffer!, _decryptedBytesOffset, extraBuffer, 0, _decryptedBytesCount); _decryptedBytesCount = 0; } @@ -756,7 +757,7 @@ private async ValueTask ReadAsyncInternal(TIOAdapter adapter, M if (status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate) { - if (!_sslAuthenticationOptions.AllowRenegotiation) + if (!_sslAuthenticationOptions!.AllowRenegotiation) { if (NetEventSource.IsEnabled) NetEventSource.Fail(this, "Renegotiation was requested but it is disallowed"); throw new IOException(SR.net_ssl_io_renego); @@ -952,7 +953,7 @@ private static byte[] EnsureBufferSize(byte[] buffer, int copyCount, int size) { if (buffer == null || buffer.Length < size) { - byte[] saved = buffer; + byte[]? saved = buffer; buffer = new byte[size]; if (saved != null && copyCount != 0) { @@ -1131,7 +1132,7 @@ private Framing DetectFraming(ReadOnlySpan bytes) } // When server has replied the framing is already fixed depending on the prior client packet - if (!_context.IsServer || _framing == Framing.Unified) + if (!_context!.IsServer || _framing == Framing.Unified) { return Framing.BeforeSSL3; } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs index d8482103017a35..73f4417dacc215 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; @@ -27,42 +28,42 @@ public enum EncryptionPolicy } // A user delegate used to verify remote SSL certificate. - public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); + public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors); // A user delegate used to select local SSL certificate. - public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers); + public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate? remoteCertificate, string[] acceptableIssuers); - public delegate X509Certificate ServerCertificateSelectionCallback(object sender, string hostName); + public delegate X509Certificate ServerCertificateSelectionCallback(object sender, string? hostName); // Internal versions of the above delegates. - internal delegate bool RemoteCertValidationCallback(string host, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); - internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2 remoteCertificate, string[] acceptableIssuers); - internal delegate X509Certificate ServerCertSelectionCallback(string hostName); + internal delegate bool RemoteCertValidationCallback(string? host, X509Certificate2? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors); + internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2? remoteCertificate, string[] acceptableIssuers); + internal delegate X509Certificate ServerCertSelectionCallback(string? hostName); public partial class SslStream : AuthenticatedStream { /// Set as the _exception when the instance is disposed. - private static readonly ExceptionDispatchInfo s_disposedSentinel = ExceptionDispatchInfo.Capture(new ObjectDisposedException(nameof(SslStream), (string)null)); + private static readonly ExceptionDispatchInfo s_disposedSentinel = ExceptionDispatchInfo.Capture(new ObjectDisposedException(nameof(SslStream), (string?)null)); - private X509Certificate2 _remoteCertificate; + private X509Certificate2? _remoteCertificate; private bool _remoteCertificateExposed; - internal RemoteCertificateValidationCallback _userCertificateValidationCallback; - internal LocalCertificateSelectionCallback _userCertificateSelectionCallback; - internal ServerCertificateSelectionCallback _userServerCertificateSelectionCallback; + internal RemoteCertificateValidationCallback? _userCertificateValidationCallback; + internal LocalCertificateSelectionCallback? _userCertificateSelectionCallback; + internal ServerCertificateSelectionCallback? _userServerCertificateSelectionCallback; internal RemoteCertValidationCallback _certValidationDelegate; - internal LocalCertSelectionCallback _certSelectionDelegate; + internal LocalCertSelectionCallback? _certSelectionDelegate; internal EncryptionPolicy _encryptionPolicy; private readonly Stream _innerStream; - private SecureChannel _context; + private SecureChannel? _context; - private ExceptionDispatchInfo _exception; + private ExceptionDispatchInfo? _exception; private bool _shutdown; private bool _handshakeCompleted; // Never updated directly, special properties are used. This is the read buffer. - internal byte[] _internalBuffer; + internal byte[]? _internalBuffer; internal int _internalOffset; internal int _internalBufferCount; internal int _decryptedBytesOffset; @@ -81,19 +82,19 @@ public SslStream(Stream innerStream, bool leaveInnerStreamOpen) { } - public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) + public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption) { } - public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback) + public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback, + LocalCertificateSelectionCallback? userCertificateSelectionCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption) { } - public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) + public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback, + LocalCertificateSelectionCallback? userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption) @@ -121,7 +122,7 @@ public SslApplicationProtocol NegotiatedApplicationProtocol } } - private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback callback) + private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback? callback) { if (_userCertificateValidationCallback == null) { @@ -134,7 +135,7 @@ private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback } } - private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback callback) + private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback? callback) { if (_userCertificateSelectionCallback == null) { @@ -147,7 +148,7 @@ private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback cal } } - private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + private bool UserCertValidationCallbackWrapper(string? hostName, X509Certificate2? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) { _remoteCertificate = certificate == null ? null : new X509Certificate2(certificate); if (_userCertificateValidationCallback == null) @@ -165,12 +166,12 @@ private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 } } - private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) + private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate? remoteCertificate, string[] acceptableIssuers) { - return _userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); + return _userCertificateSelectionCallback!(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); } - private X509Certificate ServerCertSelectionCallbackWrapper(string targetHost) => _userServerCertificateSelectionCallback(this, targetHost); + private X509Certificate ServerCertSelectionCallbackWrapper(string? targetHost) => _userServerCertificateSelectionCallback!(this, targetHost); private SslAuthenticationOptions CreateAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthenticationOptions) { @@ -198,21 +199,21 @@ private SslAuthenticationOptions CreateAuthenticationOptions(SslServerAuthentica // // Client side auth. // - public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } - public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, - bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, + bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } - public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, + public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, - AsyncCallback asyncCallback, object asyncState) + AsyncCallback? asyncCallback, object? asyncState) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions { @@ -226,15 +227,15 @@ public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509Cer return BeginAuthenticateAsClient(options, CancellationToken.None, asyncCallback, asyncState); } - internal IAsyncResult BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, object asyncState) => - TaskToApm.Begin(AuthenticateAsClientApm(sslClientAuthenticationOptions, cancellationToken), asyncCallback, asyncState); + internal IAsyncResult BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback? asyncCallback, object? asyncState) => + TaskToApm.Begin(AuthenticateAsClientApm(sslClientAuthenticationOptions, cancellationToken)!, asyncCallback, asyncState); public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); // // Server side auth. // - public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState) + public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false, @@ -243,15 +244,15 @@ public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCert } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, - bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) + bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, - AsyncCallback asyncCallback, - object asyncState) + AsyncCallback? asyncCallback, + object? asyncState) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { @@ -265,18 +266,18 @@ public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCert return BeginAuthenticateAsServer(options, CancellationToken.None, asyncCallback, asyncState); } - private IAsyncResult BeginAuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, object asyncState) => - TaskToApm.Begin(AuthenticateAsServerApm(sslServerAuthenticationOptions, cancellationToken), asyncCallback, asyncState); + private IAsyncResult BeginAuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback? asyncCallback, object? asyncState) => + TaskToApm.Begin(AuthenticateAsServerApm(sslServerAuthenticationOptions, cancellationToken)!, asyncCallback, asyncState); public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); - internal IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(ShutdownAsync(), asyncCallback, asyncState); + internal IAsyncResult BeginShutdown(AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ShutdownAsync(), asyncCallback, asyncState); internal void EndShutdown(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public TransportContext TransportContext => new SslStreamContext(this); - internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) => _context?.GetChannelBinding(kind); + internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) => _context?.GetChannelBinding(kind); #region Synchronous methods public virtual void AuthenticateAsClient(string targetHost) @@ -284,12 +285,12 @@ public virtual void AuthenticateAsClient(string targetHost) AuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false); } - public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) + public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } - public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) + public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions { @@ -348,9 +349,9 @@ private void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthen #region Task-based async public methods public virtual Task AuthenticateAsClientAsync(string targetHost) => AuthenticateAsClientAsync(targetHost, null, false); - public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) => AuthenticateAsClientAsync(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); + public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) => AuthenticateAsClientAsync(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); - public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) + public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions() { @@ -371,7 +372,7 @@ public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAu ValidateCreateContext(sslClientAuthenticationOptions, _certValidationDelegate, _certSelectionDelegate); - return ProcessAuthentication(true, false, cancellationToken); + return ProcessAuthentication(true, false, cancellationToken)!; } private Task AuthenticateAsClientApm(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken = default) @@ -381,7 +382,7 @@ private Task AuthenticateAsClientApm(SslClientAuthenticationOptions sslClientAut ValidateCreateContext(sslClientAuthenticationOptions, _certValidationDelegate, _certSelectionDelegate); - return ProcessAuthentication(true, true, cancellationToken); + return ProcessAuthentication(true, true, cancellationToken)!; } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) => @@ -419,7 +420,7 @@ public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAu SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); - return ProcessAuthentication(true, false, cancellationToken); + return ProcessAuthentication(true, false, cancellationToken)!; } private Task AuthenticateAsServerApm(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken = default) @@ -427,14 +428,14 @@ private Task AuthenticateAsServerApm(SslServerAuthenticationOptions sslServerAut SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); - return ProcessAuthentication(true, true, cancellationToken); + return ProcessAuthentication(true, true, cancellationToken)!; } public virtual Task ShutdownAsync() { ThrowIfExceptionalOrNotAuthenticatedOrShutdown(); - ProtocolToken message = _context.CreateShutdownToken(); + ProtocolToken message = _context!.CreateShutdownToken()!; _shutdown = true; return InnerStream.WriteAsync(message.Payload, default).AsTask(); } @@ -448,7 +449,7 @@ public override bool IsMutuallyAuthenticated { return IsAuthenticated && - (_context.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate) != null && + (_context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate) != null && _context.IsRemoteCertificateAvailable; /* does not work: Context.IsMutualAuthFlag;*/ } } @@ -464,7 +465,7 @@ public virtual SslProtocols SslProtocol get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return SslProtocols.None; @@ -515,16 +516,16 @@ public virtual SslProtocols SslProtocol // // This will return selected local cert for both client/server streams // - public virtual X509Certificate LocalCertificate + public virtual X509Certificate? LocalCertificate { get { ThrowIfExceptionalOrNotAuthenticated(); - return _context.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate; + return _context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate; } } - public virtual X509Certificate RemoteCertificate + public virtual X509Certificate? RemoteCertificate { get { @@ -540,7 +541,7 @@ public virtual TlsCipherSuite NegotiatedCipherSuite get { ThrowIfExceptionalOrNotAuthenticated(); - return _context.ConnectionInfo?.TlsCipherSuite ?? default(TlsCipherSuite); + return _context!.ConnectionInfo?.TlsCipherSuite ?? default(TlsCipherSuite); } } @@ -549,7 +550,7 @@ public virtual CipherAlgorithmType CipherAlgorithm get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return CipherAlgorithmType.None; @@ -563,7 +564,7 @@ public virtual int CipherStrength get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; @@ -578,7 +579,7 @@ public virtual HashAlgorithmType HashAlgorithm get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return (HashAlgorithmType)0; @@ -592,7 +593,7 @@ public virtual int HashStrength get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; @@ -607,7 +608,7 @@ public virtual ExchangeAlgorithmType KeyExchangeAlgorithm get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return (ExchangeAlgorithmType)0; @@ -622,7 +623,7 @@ public virtual int KeyExchangeStrength get { ThrowIfExceptionalOrNotAuthenticated(); - SslConnectionInfo info = _context.ConnectionInfo; + SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; @@ -714,7 +715,7 @@ public override int ReadByte() { if (_decryptedBytesCount > 0) { - int b = _internalBuffer[_decryptedBytesOffset++]; + int b = _internalBuffer![_decryptedBytesOffset++]; _decryptedBytesCount--; ReturnReadBufferIfEmpty(); return b; @@ -760,7 +761,7 @@ public override void Write(byte[] buffer, int offset, int count) vt.GetAwaiter().GetResult(); } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); @@ -772,7 +773,7 @@ public override int EndRead(IAsyncResult asyncResult) return TaskToApm.End(asyncResult); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); @@ -815,7 +816,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken private void ThrowIfExceptional() { - ExceptionDispatchInfo e = _exception; + ExceptionDispatchInfo? e = _exception; if (e != null) { ThrowExceptional(e); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs index c91cf4665cb25d..7c6d13ac22bd69 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs @@ -34,9 +34,9 @@ public static void VerifyPackageInfo() public static SecurityStatusPal AcceptSecurityContext( ref SafeFreeCredentials credential, - ref SafeDeleteSslContext context, + ref SafeDeleteSslContext? context, ReadOnlySpan inputBuffer, - ref byte[] outputBuffer, + ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions); @@ -44,10 +44,10 @@ public static SecurityStatusPal AcceptSecurityContext( public static SecurityStatusPal InitializeSecurityContext( ref SafeFreeCredentials credential, - ref SafeDeleteSslContext context, - string targetName, + ref SafeDeleteSslContext? context, + string? targetName, ReadOnlySpan inputBuffer, - ref byte[] outputBuffer, + ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions); @@ -62,7 +62,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle( return new SafeFreeSslCredentials(certificate, protocols, policy); } - internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context) + internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext? context) { if (context == null) return null; @@ -116,7 +116,7 @@ public static SecurityStatusPal EncryptMessage( } else { - output = sslContext.ReadPendingWrites(); + output = sslContext.ReadPendingWrites()!; resultSize = output.Length; } @@ -199,7 +199,7 @@ public static SecurityStatusPal DecryptMessage( } } - public static ChannelBinding QueryContextChannelBinding( + public static ChannelBinding? QueryContextChannelBinding( SafeDeleteContext securityContext, ChannelBindingKind attribute) { @@ -217,7 +217,7 @@ public static ChannelBinding QueryContextChannelBinding( } public static void QueryContextStreamSizes( - SafeDeleteContext securityContext, + SafeDeleteContext? securityContext, out StreamSizes streamSizes) { streamSizes = StreamSizes.Default; @@ -232,20 +232,20 @@ public static void QueryContextConnectionInfo( private static SecurityStatusPal HandshakeInternal( SafeFreeCredentials credential, - ref SafeDeleteSslContext context, + ref SafeDeleteSslContext? context, ReadOnlySpan inputBuffer, - ref byte[] outputBuffer, + ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Debug.Assert(!credential.IsInvalid); try { - SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)context); + SafeDeleteSslContext? sslContext = ((SafeDeleteSslContext?)context); if ((null == context) || context.IsInvalid) { - sslContext = new SafeDeleteSslContext(credential as SafeFreeSslCredentials, sslAuthenticationOptions); + sslContext = new SafeDeleteSslContext((credential as SafeFreeSslCredentials)!, sslAuthenticationOptions); context = sslContext; if (!string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost)) @@ -262,10 +262,10 @@ private static SecurityStatusPal HandshakeInternal( if (inputBuffer.Length > 0) { - sslContext.Write(inputBuffer); + sslContext!.Write(inputBuffer); } - SafeSslHandle sslHandle = sslContext.SslContext; + SafeSslHandle sslHandle = sslContext!.SslContext; SecurityStatusPal status; lock (sslHandle) @@ -312,8 +312,8 @@ private static SecurityStatusPal PerformHandshake(SafeSslHandle sslHandle) } public static SecurityStatusPal ApplyAlertToken( - ref SafeFreeCredentials credentialsHandle, - SafeDeleteContext securityContext, + ref SafeFreeCredentials? credentialsHandle, + SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { @@ -324,7 +324,7 @@ public static SecurityStatusPal ApplyAlertToken( } public static SecurityStatusPal ApplyShutdownToken( - ref SafeFreeCredentials credentialsHandle, + ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext securityContext) { SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)securityContext); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs index 9d0d78dcebff16..24b06b92e1b89d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs @@ -25,19 +25,19 @@ public static void VerifyPackageInfo() { } - public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteSslContext context, - ReadOnlySpan inputBuffer, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) + public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, + ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { - return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions); + return HandshakeInternal(credential!, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions); } - public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteSslContext context, string targetName, - ReadOnlySpan inputBuffer, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) + public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, string? targetName, + ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { - return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions); + return HandshakeInternal(credential!, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions); } - public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, + public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate? certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { return new SafeFreeSslCredentials(certificate, protocols, policy); @@ -59,9 +59,9 @@ public static SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext return retVal; } - public static ChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) + public static ChannelBinding? QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { - ChannelBinding bindingHandle; + ChannelBinding? bindingHandle; if (attribute == ChannelBindingKind.Endpoint) { @@ -82,7 +82,7 @@ public static ChannelBinding QueryContextChannelBinding(SafeDeleteContext securi return bindingHandle; } - public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes) + public static void QueryContextStreamSizes(SafeDeleteContext? securityContext, out StreamSizes streamSizes) { streamSizes = StreamSizes.Default; } @@ -97,19 +97,19 @@ public static byte[] ConvertAlpnProtocolListToByteArray(List inputBuffer, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) + private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credential, ref SafeDeleteSslContext? context, + ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Debug.Assert(!credential.IsInvalid); - byte[] output = null; + byte[]? output = null; int outputSize = 0; try { if ((null == context) || context.IsInvalid) { - context = new SafeDeleteSslContext(credential as SafeFreeSslCredentials, sslAuthenticationOptions); + context = new SafeDeleteSslContext((credential as SafeFreeSslCredentials)!, sslAuthenticationOptions); } bool done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, inputBuffer, out output, out outputSize); @@ -126,7 +126,7 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia outputBuffer = outputSize == 0 ? null : - outputSize == output.Length ? output : + outputSize == output!.Length ? output : new Span(output, 0, outputSize).ToArray(); return new SecurityStatusPal(done ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.ContinueNeeded); @@ -136,14 +136,14 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia // Even if handshake failed we may have Alert to sent. if (outputSize > 0) { - outputBuffer = outputSize == output.Length ? output : new Span(output, 0, outputSize).ToArray(); + outputBuffer = outputSize == output!.Length ? output : new Span(output, 0, outputSize).ToArray(); } return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, exc); } } - internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context) + internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext? context) { if (context == null) return null; @@ -187,7 +187,7 @@ private static SecurityStatusPal EncryptDecryptHelper(SafeDeleteContext security } } - public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) + public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { // There doesn't seem to be an exposed API for writing an alert, // the API seems to assume that all alerts are generated internally by @@ -195,7 +195,7 @@ public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credenti return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } - public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext) + public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext securityContext) { SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)securityContext); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs index aac05484241872..75b0e0f1444384 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs @@ -46,7 +46,7 @@ public static byte[] ConvertAlpnProtocolListToByteArray(List inputBuffer, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) + public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; @@ -76,7 +76,7 @@ public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials cr return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } - public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteSslContext context, string targetName, ReadOnlySpan inputBuffer, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) + public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, string? targetName, ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; @@ -106,7 +106,7 @@ public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredential return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } - public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer) + public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate? certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCHANNEL_CRED.Flags flags; @@ -145,7 +145,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certi return AcquireCredentialsHandle(direction, secureCredential); } - internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context) + internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext context) { Interop.SecPkgContext_ApplicationProtocol alpnContext = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, context, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL, ref alpnContext); @@ -228,7 +228,7 @@ public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteSslContext secur } } - public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext securityContext, byte[] buffer, ref int offset, ref int count) + public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext? securityContext, byte[] buffer, ref int offset, ref int count) { const int NumSecBuffers = 4; // data + empty + empty + empty fixed (byte* bufferPtr = buffer) @@ -251,7 +251,7 @@ public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext secur { pBuffers = unmanagedBuffer }; - Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext, ref sdcInOut, 0); + Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext!, ref sdcInOut, 0); // Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty. // We need to find the data. @@ -277,7 +277,7 @@ public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext secur } } - public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) + public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { var alertToken = new Interop.SChannel.SCHANNEL_ALERT_TOKEN { @@ -298,7 +298,7 @@ public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credenti private static readonly byte[] s_schannelShutdownBytes = BitConverter.GetBytes(Interop.SChannel.SCHANNEL_SHUTDOWN); - public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext) + public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext) { var securityBuffer = new SecurityBuffer(s_schannelShutdownBytes, SecurityBufferType.SECBUFFER_TOKEN); @@ -310,7 +310,7 @@ public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials crede return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } - public static unsafe SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) + public static unsafe SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); } @@ -363,7 +363,7 @@ private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential( int version, - X509Certificate certificate, + X509Certificate? certificate, Interop.SspiCli.SCHANNEL_CRED.Flags flags, int protocols, EncryptionPolicy policy) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/TlsCipherSuiteData.cs b/src/libraries/System.Net.Security/src/System/Net/Security/TlsCipherSuiteData.cs index 3cd0732be58ef0..b5c793d15f07b7 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/TlsCipherSuiteData.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/TlsCipherSuiteData.cs @@ -24,8 +24,9 @@ static TlsCipherSuiteData() s_tlsLookup.Count == LookupCount, $"Lookup dictionary was of size {s_tlsLookup.Count} instead of {LookupCount}"); - foreach (TlsCipherSuite val in Enum.GetValues(typeof(TlsCipherSuite))) + foreach (object? value in Enum.GetValues(typeof(TlsCipherSuite))) { + TlsCipherSuite val = (TlsCipherSuite)value!; Debug.Assert(s_tlsLookup.ContainsKey(val), $"No mapping found for {val} ({(int)val})"); } } diff --git a/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs b/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs index 8993dd6d8757b7..eda52c9d784ef9 100644 --- a/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs +++ b/src/libraries/System.Net.Security/src/System/Net/SslStreamContext.cs @@ -16,10 +16,10 @@ internal SslStreamContext(SslStream sslStream) NetEventSource.Fail(this, "Not expecting a null sslStream!"); } - _sslStream = sslStream; + _sslStream = sslStream!; } - public override ChannelBinding GetChannelBinding(ChannelBindingKind kind) + public override ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { return _sslStream.GetChannelBinding(kind); } diff --git a/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs b/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs index 1f6395ab66fabb..dc494ca17e1b0b 100644 --- a/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs +++ b/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs @@ -67,7 +67,7 @@ public Stream Transport } } - public byte[] ReadMessage() + public byte[]? ReadMessage() { if (_eof) { @@ -160,7 +160,7 @@ private void ReadFrameCallback(IAsyncResult transportResult) return; } - WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; + WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState!; try { @@ -198,7 +198,7 @@ private void ReadFrameComplete(IAsyncResult transportResult) NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } - WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; + WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState!; int bytesRead = TaskToApm.End(transportResult); workerResult.Offset += bytesRead; @@ -212,7 +212,7 @@ private void ReadFrameComplete(IAsyncResult transportResult) { // (by design) This indicates the stream has receives EOF // If we are in the middle of a Frame - fail, otherwise - produce EOF - object result = null; + object? result = null; if (!workerResult.HeaderDone && workerResult.Offset == 0) { result = (object)-1; @@ -232,7 +232,7 @@ private void ReadFrameComplete(IAsyncResult transportResult) { workerResult.HeaderDone = true; // This indicates the header has been read successfully - _curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier); + _curReadHeader.CopyFrom(workerResult.Buffer!, 0, _readVerifier); int payloadSize = _curReadHeader.PayloadSize; if (payloadSize < 0) { @@ -272,7 +272,7 @@ private void ReadFrameComplete(IAsyncResult transportResult) } // This means we need more data to complete the data block. - transportResult = TaskToApm.Begin(_transport.ReadAsync(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset), + transportResult = TaskToApm.Begin(_transport.ReadAsync(workerResult.Buffer!, workerResult.Offset, workerResult.End - workerResult.Offset), _readFrameCallback, workerResult); } while (transportResult.CompletedSynchronously); } @@ -284,13 +284,13 @@ private void ReadFrameComplete(IAsyncResult transportResult) // The Result property represents either a number of bytes read or an // exception put by our async state machine. // - public byte[] EndReadMessage(IAsyncResult asyncResult) + public byte[]? EndReadMessage(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } - WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; + WorkerAsyncResult? workerResult = asyncResult as WorkerAsyncResult; if (workerResult == null) { @@ -307,7 +307,7 @@ public byte[] EndReadMessage(IAsyncResult asyncResult) ExceptionDispatchInfo.Throw(e); } - int size = (int)workerResult.Result; + int size = (int)workerResult.Result!; if (size == -1) { _eof = true; @@ -385,7 +385,7 @@ private void BeginWriteCallback(IAsyncResult transportResult) return; } - var workerResult = (WorkerAsyncResult)transportResult.AsyncState; + var workerResult = (WorkerAsyncResult)transportResult.AsyncState!; try { @@ -410,7 +410,7 @@ private void BeginWriteComplete(IAsyncResult transportResult) { do { - WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; + WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState!; // First, complete the previous portion write. TaskToApm.End(transportResult); @@ -426,7 +426,7 @@ private void BeginWriteComplete(IAsyncResult transportResult) workerResult.Offset = workerResult.End; // Write next portion (frame body) using Async IO. - transportResult = TaskToApm.Begin(_transport.WriteAsync(workerResult.Buffer, 0, workerResult.End), + transportResult = TaskToApm.Begin(_transport.WriteAsync(workerResult.Buffer!, 0, workerResult.End), _beginWriteCallback, workerResult); } while (transportResult.CompletedSynchronously); @@ -439,7 +439,7 @@ public void EndWriteMessage(IAsyncResult asyncResult) throw new ArgumentNullException(nameof(asyncResult)); } - WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; + WorkerAsyncResult? workerResult = asyncResult as WorkerAsyncResult; if (workerResult != null) { @@ -468,14 +468,14 @@ public void EndWriteMessage(IAsyncResult asyncResult) internal class WorkerAsyncResult : LazyAsyncResult { - public byte[] Buffer; + public byte[]? Buffer; public int Offset; public int End; public bool HeaderDone; // This might be reworked so we read both header and frame in one chunk. public WorkerAsyncResult(object asyncObject, object asyncState, AsyncCallback savedAsyncCallback, - byte[] buffer, int offset, int end) + byte[]? buffer, int offset, int end) : base(asyncObject, asyncState, savedAsyncCallback) { Buffer = buffer; diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/AuthenticationException.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/AuthenticationException.cs index 6e49595c594475..2b29b0e6d8e32c 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/AuthenticationException.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/AuthenticationException.cs @@ -17,9 +17,9 @@ public class AuthenticationException : SystemException { public AuthenticationException() { } - public AuthenticationException(string message) : base(message) { } + public AuthenticationException(string? message) : base(message) { } - public AuthenticationException(string message, Exception innerException) : base(message, innerException) { } + public AuthenticationException(string? message, Exception? innerException) : base(message, innerException) { } protected AuthenticationException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { @@ -39,9 +39,9 @@ public class InvalidCredentialException : AuthenticationException { public InvalidCredentialException() { } - public InvalidCredentialException(string message) : base(message) { } + public InvalidCredentialException(string? message) : base(message) { } - public InvalidCredentialException(string message, Exception innerException) : base(message, innerException) { } + public InvalidCredentialException(string? message, Exception? innerException) : base(message, innerException) { } protected InvalidCredentialException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs index e3f3019fe43cf2..bbc90213bc7e0c 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs @@ -15,14 +15,14 @@ namespace System.Security.Authentication.ExtendedProtection /// public class ExtendedProtectionPolicy : ISerializable { - private readonly ServiceNameCollection _customServiceNames; + private readonly ServiceNameCollection? _customServiceNames; private readonly PolicyEnforcement _policyEnforcement; private readonly ProtectionScenario _protectionScenario; - private readonly ChannelBinding _customChannelBinding; + private readonly ChannelBinding? _customChannelBinding; public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, ProtectionScenario protectionScenario, - ServiceNameCollection customServiceNames) + ServiceNameCollection? customServiceNames) { if (policyEnforcement == PolicyEnforcement.Never) { @@ -41,9 +41,9 @@ public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, ProtectionScenario protectionScenario, - ICollection customServiceNames) + ICollection? customServiceNames) : this(policyEnforcement, protectionScenario, - customServiceNames == null ? (ServiceNameCollection)null : new ServiceNameCollection(customServiceNames)) + customServiceNames == null ? (ServiceNameCollection?)null : new ServiceNameCollection(customServiceNames)) { } @@ -82,7 +82,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex throw new PlatformNotSupportedException(); } - public ServiceNameCollection CustomServiceNames + public ServiceNameCollection? CustomServiceNames { get { return _customServiceNames; } } @@ -97,7 +97,7 @@ public ProtectionScenario ProtectionScenario get { return _protectionScenario; } } - public ChannelBinding CustomChannelBinding + public ChannelBinding? CustomChannelBinding { get { return _customChannelBinding; } } @@ -128,7 +128,7 @@ public override string ToString() else { bool first = true; - foreach (string serviceName in _customServiceNames) + foreach (string? serviceName in _customServiceNames) { if (first) { diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs index 51b4d9c0874012..eaf14ae86cdf2c 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs @@ -5,6 +5,7 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net; @@ -48,17 +49,17 @@ private ServiceNameCollection(IList list, int additionalCapacity) Debug.Assert(list != null); Debug.Assert(additionalCapacity >= 0); - foreach (string item in list) + foreach (string? item in list) { InnerList.Add(item); } } - public bool Contains(string searchServiceName) + public bool Contains(string? searchServiceName) { - string searchName = NormalizeServiceName(searchServiceName); + string? searchName = NormalizeServiceName(searchServiceName); - foreach (string serviceName in InnerList) + foreach (string? serviceName in InnerList) { if (string.Equals(serviceName, searchName, StringComparison.OrdinalIgnoreCase)) { @@ -78,14 +79,14 @@ public bool Contains(string searchServiceName) /// private void AddIfNew(IEnumerable serviceNames, bool expectStrings) { - List list = serviceNames as List; + List? list = serviceNames as List; if (list != null) { AddIfNew(list); return; } - ServiceNameCollection snc = serviceNames as ServiceNameCollection; + ServiceNameCollection? snc = serviceNames as ServiceNameCollection; if (snc != null) { AddIfNew(snc.InnerList); @@ -94,13 +95,13 @@ private void AddIfNew(IEnumerable serviceNames, bool expectStrings) // NullReferenceException is thrown when serviceNames is null, // which is consistent with the behavior of the .NET Framework. - foreach (object item in serviceNames) + foreach (object? item in serviceNames) { // To match the behavior of the .NET Framework, when an item // in the collection is not a string: // - Throw InvalidCastException when expectStrings is true. // - Throw ArgumentException when expectStrings is false. - AddIfNew(expectStrings ? (string)item : item as string); + AddIfNew(expectStrings ? (string)item! : (item as string)!); } } @@ -124,16 +125,16 @@ private void AddIfNew(IList serviceNames) { Debug.Assert(serviceNames != null); - foreach (string serviceName in serviceNames) + foreach (string? serviceName in serviceNames) { - AddIfNew(serviceName); + AddIfNew(serviceName!); } } /// /// Normalize, check for duplicates, and add if the value is unique. /// - private void AddIfNew(string serviceName) + private void AddIfNew([MaybeNull]string serviceName) { if (string.IsNullOrEmpty(serviceName)) { @@ -153,7 +154,7 @@ private void AddIfNew(string serviceName) /// private static int GetCountOrOne(IEnumerable collection) { - ICollection c = collection as ICollection; + ICollection? c = collection as ICollection; return c != null ? c.Count : 1; } @@ -164,7 +165,7 @@ private static int GetCountOrOne(IEnumerable collection) // prefix/host:port // prefix/host/DistinguishedName // prefix/host:port/DistinguishedName - private static string NormalizeServiceName(string inputServiceName) + private static string? NormalizeServiceName(string? inputServiceName) { if (string.IsNullOrWhiteSpace(inputServiceName)) { @@ -240,7 +241,7 @@ private static string NormalizeServiceName(string inputServiceName) // Now we have a valid DNS host, normalize it. - Uri constructedUri; + Uri? constructedUri; // We need to avoid any unexpected exceptions on this code path. if (!Uri.TryCreate(UriScheme.Http + UriScheme.SchemeDelimiter + host, UriKind.Absolute, out constructedUri)) diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj b/src/libraries/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj index 966a46da2b7cc5..cf5eaa0d21c01b 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj @@ -3,6 +3,7 @@ true true $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-OSX + annotations diff --git a/src/libraries/System.Net.Security/tests/UnitTests/Fakes/FakeSslStream.Implementation.cs b/src/libraries/System.Net.Security/tests/UnitTests/Fakes/FakeSslStream.Implementation.cs index 85eb337a3e1b24..3dffb86a4da38a 100644 --- a/src/libraries/System.Net.Security/tests/UnitTests/Fakes/FakeSslStream.Implementation.cs +++ b/src/libraries/System.Net.Security/tests/UnitTests/Fakes/FakeSslStream.Implementation.cs @@ -11,7 +11,7 @@ namespace System.Net.Security { public partial class SslStream { - private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback localCallback) + private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback? localCallback) { // Without setting (or using) these members you will get a build exception in the unit test project. // The code that normally uses these in the main solution is in the implementation of SslStream. diff --git a/src/libraries/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj b/src/libraries/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj index be0e5019e2143d..036fba9049b936 100644 --- a/src/libraries/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj +++ b/src/libraries/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj @@ -11,6 +11,7 @@ $(NoWarn);3021 $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-OSX + annotations