Merge branch 'main' of github.com:dotnet/runtime into feature/use-dllimport-generator
authorJeremy Koritzinsky <jekoritz@microsoft.com>
Thu, 29 Jul 2021 17:44:59 +0000 (10:44 -0700)
committerJeremy Koritzinsky <jekoritz@microsoft.com>
Thu, 29 Jul 2021 17:44:59 +0000 (10:44 -0700)
33 files changed:
1  2 
Directory.Build.targets
NuGet.config
eng/Versions.props
src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Keychain.macOS.cs
src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.X509.cs
src/libraries/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs
src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadLink.cs
src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs
src/libraries/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.IsNtlmInstalled.cs
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Rsa.cs
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs
src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetConsoleCtrlHandler.cs
src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs
src/libraries/Common/src/Interop/Windows/WinHttp/Interop.winhttp.cs
src/libraries/Common/src/System/Net/Security/CertificateValidation.Windows.cs
src/libraries/System.Console/src/System/ConsolePal.Windows.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs
src/libraries/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj
src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs
src/libraries/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj
src/libraries/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
src/libraries/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs
src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs
src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System.Runtime.InteropServices.RuntimeInformation.csproj
src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.Windows.cs
src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/OpenSslX509CertificateReader.cs
src/libraries/System.Security.Cryptography.X509Certificates/tests/System.Security.Cryptography.X509Certificates.Tests.csproj
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs

Simple merge
diff --cc NuGet.config
      <add key="dotnet-eng" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json" />
      <add key="dotnet6" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6/nuget/v3/index.json" />
      <add key="dotnet6-transport" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6-transport/nuget/v3/index.json" />
+     <!-- Used for dotnet pack task -->
+     <add key="nuget-build" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/nuget-build/nuget/v3/index.json" />
      <!-- Used for the Rich Navigation indexing task -->
      <add key="richnav" value="https://pkgs.dev.azure.com/azure-public/vside/_packaging/vs-buildservices/nuget/v3/index.json" />
 +    <!-- Used for DllImportGenerator -->
 +    <add key="dotnet-experimental" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental/nuget/v3/index.json" />
    </packageSources>
    <disabledPackageSources>
      <clear />
      <!-- Docs -->
      <MicrosoftPrivateIntellisenseVersion>5.0.0-preview-20201009.2</MicrosoftPrivateIntellisenseVersion>
      <!-- ILLink -->
-     <MicrosoftNETILLinkTasksVersion>6.0.100-preview.6.21310.3</MicrosoftNETILLinkTasksVersion>
+     <MicrosoftNETILLinkTasksVersion>6.0.100-preview.6.21376.2</MicrosoftNETILLinkTasksVersion>
      <MicrosoftNETILLinkAnalyzerPackageVersion>$(MicrosoftNETILLinkTasksVersion)</MicrosoftNETILLinkAnalyzerPackageVersion>
      <!-- ICU -->
-     <MicrosoftNETCoreRuntimeICUTransportVersion>6.0.0-preview.6.21307.1</MicrosoftNETCoreRuntimeICUTransportVersion>
+     <MicrosoftNETCoreRuntimeICUTransportVersion>6.0.0-rc.1.21369.1</MicrosoftNETCoreRuntimeICUTransportVersion>
+     <!-- MsQuic -->
+     <SystemNetMsQuicTransportVersion>6.0.0-preview.7.21376.1</SystemNetMsQuicTransportVersion>
      <!-- Mono LLVM -->
-     <runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21308.1</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
-     <runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21308.1</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
-     <runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21308.1</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
-     <runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21308.1</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
-     <runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21308.1</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
-     <runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21308.1</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
-     <runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21308.1</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
-     <runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21308.1</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
+     <runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21369.1</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
+     <runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21369.1</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
+     <runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21369.1</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
+     <runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21369.1</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
+     <runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21369.1</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
+     <runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21369.1</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
+     <runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.21369.1</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
+     <runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.21369.1</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
      <!-- emscripten / Node -->
-     <MicrosoftNETRuntimeEmscripten2021Nodewinx64Version>6.0.0-preview.6.21275.1</MicrosoftNETRuntimeEmscripten2021Nodewinx64Version>
-     <MicrosoftNETRuntimeEmscriptenVersion>$(MicrosoftNETRuntimeEmscripten2021Nodewinx64Version)</MicrosoftNETRuntimeEmscriptenVersion>
+     <MicrosoftNETWorkloadEmscriptenManifest60100Version>6.0.0-rc.1.21369.1</MicrosoftNETWorkloadEmscriptenManifest60100Version>
+     <MicrosoftNETRuntimeEmscriptenVersion>$(MicrosoftNETWorkloadEmscriptenManifest60100Version)</MicrosoftNETRuntimeEmscriptenVersion>
+     <!-- workloads -->
+     <SwixPackageVersion>1.1.87-gba258badda</SwixPackageVersion>
+     <WixPackageVersion>3.14.0-dotnet</WixPackageVersion>
+     <MonoWorkloadManifestVersion>6.0.0-preview.5.21275.7</MonoWorkloadManifestVersion>
 +    <!-- Experimental -->
 +    <MicrosoftInteropDllImportGeneratorVersion>1.0.0-alpha.21301.2</MicrosoftInteropDllImportGeneratorVersion>
    </PropertyGroup>
  </Project>
@@@ -20,25 -20,22 +20,30 @@@ internal static partial class Intero
              out SafeCFDataHandle cfDataOut,
              out int pOSStatus);
  
 -        [DllImport(Libraries.AppleCryptoNative)]
 +        [GeneratedDllImport(Libraries.AppleCryptoNative)]
-         private static partial int AppleCryptoNative_X509GetPublicKey(SafeSecCertificateHandle cert, out SafeSecKeyRefHandle publicKey, out int pOSStatus);
+         private static extern int AppleCryptoNative_X509GetSubjectSummary(
+             SafeSecCertificateHandle cert,
+             out SafeCFStringHandle cfSubjectSummaryOut);
 -        [DllImport(Libraries.AppleCryptoNative)]
++        [GeneratedDllImport(Libraries.AppleCryptoNative)]
+         private static extern int AppleCryptoNative_X509GetPublicKey(SafeSecCertificateHandle cert, out SafeSecKeyRefHandle publicKey, out int pOSStatus);
  
          internal static X509ContentType X509GetContentType(ReadOnlySpan<byte> data)
 -            => X509GetContentType(ref MemoryMarshal.GetReference(data), data.Length);
 +        {
 +            unsafe
 +            {
 +                fixed (byte* dataPtr = &MemoryMarshal.GetReference(data))
 +                {
 +                    return X509GetContentType(dataPtr, data.Length);
 +                }
 +            }
 +        }
  
          [DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_X509GetContentType")]
 -        private static extern X509ContentType X509GetContentType(ref byte pbData, int cbData);
 +        private static unsafe extern X509ContentType X509GetContentType(byte* pbData, int cbData);
  
 -        [DllImport(Libraries.AppleCryptoNative)]
 -        private static extern int AppleCryptoNative_X509CopyCertFromIdentity(
 +        [GeneratedDllImport(Libraries.AppleCryptoNative)]
 +        private static partial int AppleCryptoNative_X509CopyCertFromIdentity(
              SafeSecIdentityHandle identity,
              out SafeSecCertificateHandle cert);
  
@@@ -19,8 -20,8 +20,8 @@@ internal static partial class Intero
          /// <returns>
          /// Returns the number of bytes placed into the buffer on success; bufferSize if the buffer is too small; and -1 on error.
          /// </returns>
-         [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true, CharSet = CharSet.Ansi)]
-         private static partial int ReadLink(string path, byte[] buffer, int bufferSize);
 -        [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true)]
++        [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true)]
+         private static extern int ReadLink(ref byte path, byte[] buffer, int bufferSize);
  
          /// <summary>
          /// Takes a path to a symbolic link and returns the link target path.
@@@ -9,12 -9,8 +9,8 @@@ internal static partial class Intero
  {
      internal static partial class Sys
      {
-         // Unix max paths are typically 1K or 4K UTF-8 bytes, 256 should handle the majority of paths
-         // without putting too much pressure on the stack.
-         private const int StackBufferSize = 256;
 -        [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)]
 +        [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)]
-         internal static partial int Stat(ref byte path, out FileStatus output);
+         internal static extern int Stat(ref byte path, out FileStatus output);
  
          internal static int Stat(ReadOnlySpan<char> path, out FileStatus output)
          {
@@@ -9,6 -9,30 +9,30 @@@ internal static partial class Intero
      internal static partial class NetSecurityNative
      {
          [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_IsNtlmInstalled")]
 -        internal static extern bool IsNtlmInstalled();
 +        internal static extern int IsNtlmInstalled();
+         [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_EnsureGssInitialized")]
+         private static extern int EnsureGssInitialized();
+         static NetSecurityNative()
+         {
+             GssInitializer.Initialize();
+         }
+         internal static class GssInitializer
+         {
+             static GssInitializer()
+             {
+                 if (EnsureGssInitialized() != 0)
+                 {
+                     throw new InvalidOperationException();
+                 }
+             }
+             internal static void Initialize()
+             {
+                 // No-op that exists to provide a hook for other static constructors.
+             }
+         }
      }
  }
@@@ -11,8 -11,26 +11,26 @@@ internal static partial class Intero
  {
      internal static partial class Crypto
      {
 -        [DllImport(Libraries.CryptoNative)]
 +        [GeneratedDllImport(Libraries.CryptoNative)]
-         private static partial SafeEvpPKeyHandle CryptoNative_RsaGenerateKey(int keySize);
+         private static extern SafeEvpPKeyHandle CryptoNative_EvpPKeyCreateRsa(IntPtr rsa);
+         internal static SafeEvpPKeyHandle EvpPKeyCreateRsa(IntPtr rsa)
+         {
+             Debug.Assert(rsa != IntPtr.Zero);
+             SafeEvpPKeyHandle pkey = CryptoNative_EvpPKeyCreateRsa(rsa);
+             if (pkey.IsInvalid)
+             {
+                 pkey.Dispose();
+                 throw CreateOpenSslCryptographicException();
+             }
+             return pkey;
+         }
+         [DllImport(Libraries.CryptoNative)]
+         private static extern SafeEvpPKeyHandle CryptoNative_RsaGenerateKey(int keySize);
  
          internal static SafeEvpPKeyHandle RsaGenerateKey(int keySize)
          {
@@@ -9,16 -10,208 +10,208 @@@ internal static partial class Intero
  {
      internal static partial class Crypto
      {
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyCreate")]
 -        internal static extern SafeEvpPKeyHandle EvpPkeyCreate();
 +        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyCreate")]
 +        internal static partial SafeEvpPKeyHandle EvpPkeyCreate();
  
+         [DllImport(Libraries.CryptoNative)]
+         private static extern SafeEvpPKeyHandle CryptoNative_EvpPKeyDuplicate(
+             SafeEvpPKeyHandle currentKey,
+             EvpAlgorithmId algorithmId);
+         internal static SafeEvpPKeyHandle EvpPKeyDuplicate(
+             SafeEvpPKeyHandle currentKey,
+             EvpAlgorithmId algorithmId)
+         {
+             Debug.Assert(!currentKey.IsInvalid);
+             SafeEvpPKeyHandle pkey = CryptoNative_EvpPKeyDuplicate(
+                 currentKey,
+                 algorithmId);
+             if (pkey.IsInvalid)
+             {
+                 pkey.Dispose();
+                 throw CreateOpenSslCryptographicException();
+             }
+             return pkey;
+         }
          [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyDestroy")]
          internal static extern void EvpPkeyDestroy(IntPtr pkey);
  
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeySize")]
 -        internal static extern int EvpPKeySize(SafeEvpPKeyHandle pkey);
 +        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeySize")]
 +        internal static partial int EvpPKeySize(SafeEvpPKeyHandle pkey);
  
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_UpRefEvpPkey")]
 +        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_UpRefEvpPkey")]
-         internal static partial int UpRefEvpPkey(SafeEvpPKeyHandle handle);
+         internal static extern int UpRefEvpPkey(SafeEvpPKeyHandle handle);
+         [DllImport(Libraries.CryptoNative)]
+         private static extern unsafe SafeEvpPKeyHandle CryptoNative_DecodeSubjectPublicKeyInfo(
+             byte* buf,
+             int len,
+             int algId);
+         [DllImport(Libraries.CryptoNative)]
+         private static extern unsafe SafeEvpPKeyHandle CryptoNative_DecodePkcs8PrivateKey(
+             byte* buf,
+             int len,
+             int algId);
+         internal static unsafe SafeEvpPKeyHandle DecodeSubjectPublicKeyInfo(
+             ReadOnlySpan<byte> source,
+             EvpAlgorithmId algorithmId)
+         {
+             SafeEvpPKeyHandle handle;
+             fixed (byte* sourcePtr = source)
+             {
+                 handle = CryptoNative_DecodeSubjectPublicKeyInfo(
+                     sourcePtr,
+                     source.Length,
+                     (int)algorithmId);
+             }
+             if (handle.IsInvalid)
+             {
+                 handle.Dispose();
+                 throw CreateOpenSslCryptographicException();
+             }
+             return handle;
+         }
+         internal static unsafe SafeEvpPKeyHandle DecodePkcs8PrivateKey(
+             ReadOnlySpan<byte> source,
+             EvpAlgorithmId algorithmId)
+         {
+             SafeEvpPKeyHandle handle;
+             fixed (byte* sourcePtr = source)
+             {
+                 handle = CryptoNative_DecodePkcs8PrivateKey(
+                     sourcePtr,
+                     source.Length,
+                     (int)algorithmId);
+             }
+             if (handle.IsInvalid)
+             {
+                 handle.Dispose();
+                 throw CreateOpenSslCryptographicException();
+             }
+             return handle;
+         }
+         [DllImport(Libraries.CryptoNative)]
+         private static extern int CryptoNative_GetPkcs8PrivateKeySize(IntPtr pkey);
+         private static int GetPkcs8PrivateKeySize(IntPtr pkey)
+         {
+             int ret = CryptoNative_GetPkcs8PrivateKeySize(pkey);
+             if (ret < 0)
+             {
+                 throw CreateOpenSslCryptographicException();
+             }
+             return ret;
+         }
+         [DllImport(Libraries.CryptoNative)]
+         private static extern unsafe int CryptoNative_EncodePkcs8PrivateKey(IntPtr pkey, byte* buf);
+         internal static ArraySegment<byte> RentEncodePkcs8PrivateKey(SafeEvpPKeyHandle pkey)
+         {
+             bool addedRef = false;
+             try
+             {
+                 pkey.DangerousAddRef(ref addedRef);
+                 IntPtr handle = pkey.DangerousGetHandle();
+                 int size = GetPkcs8PrivateKeySize(handle);
+                 byte[] rented = CryptoPool.Rent(size);
+                 int written;
+                 unsafe
+                 {
+                     fixed (byte* buf = rented)
+                     {
+                         written = CryptoNative_EncodePkcs8PrivateKey(handle, buf);
+                     }
+                 }
+                 Debug.Assert(written == size);
+                 return new ArraySegment<byte>(rented, 0, written);
+             }
+             finally
+             {
+                 if (addedRef)
+                 {
+                     pkey.DangerousRelease();
+                 }
+             }
+         }
+         [DllImport(Libraries.CryptoNative)]
+         private static extern int CryptoNative_GetSubjectPublicKeyInfoSize(IntPtr pkey);
+         private static int GetSubjectPublicKeyInfoSize(IntPtr pkey)
+         {
+             int ret = CryptoNative_GetSubjectPublicKeyInfoSize(pkey);
+             if (ret < 0)
+             {
+                 throw CreateOpenSslCryptographicException();
+             }
+             return ret;
+         }
+         [DllImport(Libraries.CryptoNative)]
+         private static extern unsafe int CryptoNative_EncodeSubjectPublicKeyInfo(IntPtr pkey, byte* buf);
+         internal static ArraySegment<byte> RentEncodeSubjectPublicKeyInfo(SafeEvpPKeyHandle pkey)
+         {
+             bool addedRef = false;
+             try
+             {
+                 pkey.DangerousAddRef(ref addedRef);
+                 IntPtr handle = pkey.DangerousGetHandle();
+                 int size = GetSubjectPublicKeyInfoSize(handle);
+                 byte[] rented = CryptoPool.Rent(size);
+                 int written;
+                 unsafe
+                 {
+                     fixed (byte* buf = rented)
+                     {
+                         written = CryptoNative_EncodeSubjectPublicKeyInfo(handle, buf);
+                     }
+                 }
+                 Debug.Assert(written == size);
+                 return new ArraySegment<byte>(rented, 0, written);
+             }
+             finally
+             {
+                 if (addedRef)
+                 {
+                     pkey.DangerousRelease();
+                 }
+             }
+         }
+         internal enum EvpAlgorithmId
+         {
+             Unknown = 0,
+             RSA = 6,
+             DSA = 116,
+             ECC = 408,
+         }
      }
  }
@@@ -68,15 -68,18 +68,18 @@@ internal static partial class Intero
              return result;
          }
  
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite", SetLastError = true)]
 -        internal static extern int SslWrite(SafeSslHandle ssl, ref byte buf, int num);
 +        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite", SetLastError = true)]
 +        internal static partial int SslWrite(SafeSslHandle ssl, ref byte buf, int num);
  
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead", SetLastError = true)]
 -        internal static extern int SslRead(SafeSslHandle ssl, ref byte buf, int num);
 +        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead", SetLastError = true)]
 +        internal static partial int SslRead(SafeSslHandle ssl, ref byte buf, int num);
  
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRenegotiate")]
++        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRenegotiate")]
+         internal static extern int SslRenegotiate(SafeSslHandle ssl);
 -        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
 +        [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
          [return: MarshalAs(UnmanagedType.Bool)]
 -        internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl);
 +        internal static partial bool IsSslRenegotiatePending(SafeSslHandle ssl);
  
          [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
          internal static extern int SslShutdown(IntPtr ssl);
@@@ -11,15 -9,11 +9,16 @@@ internal static partial class Intero
      {
          internal const int CTRL_C_EVENT = 0;
          internal const int CTRL_BREAK_EVENT = 1;
-         internal delegate bool ConsoleCtrlHandlerRoutine(int controlType);
+         internal const int CTRL_CLOSE_EVENT = 2;
+         internal const int CTRL_LOGOFF_EVENT = 5;
+         internal const int CTRL_SHUTDOWN_EVENT = 6;
  
-         internal static partial bool SetConsoleCtrlHandler(ConsoleCtrlHandlerRoutine handler, bool addOrRemove);
 +#if DLLIMPORTGENERATOR_ENABLED
 +        [GeneratedDllImport(Libraries.Kernel32, SetLastError = true)]
++        internal static partial bool SetConsoleCtrlHandler(delegate* unmanaged<int, BOOL> handler, bool addOrRemove);
 +#else
          [DllImport(Libraries.Kernel32, SetLastError = true)]
-         internal static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerRoutine handler, bool addOrRemove);
+         internal static extern unsafe bool SetConsoleCtrlHandler(delegate* unmanaged<int, BOOL> HandlerRoutine, bool Add);
 +#endif
      }
  }
@@@ -315,149 -316,183 +316,171 @@@ internal static partial class Intero
              }
          }
  
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern int EncryptMessage(
 -              ref CredHandle contextHandle,
 -              [In] uint qualityOfProtection,
 -              [In, Out] ref SecBufferDesc inputOutput,
 -              [In] uint sequenceNumber
 -              );
+         [StructLayout(LayoutKind.Sequential)]
+         internal unsafe struct SecPkgCred_ClientCertPolicy
+         {
+             public uint dwFlags;
+             public Guid guidPolicyId;
+             public uint dwCertFlags;
+             public uint dwUrlRetrievalTimeout;
+             public BOOL fCheckRevocationFreshnessTime;
+             public uint dwRevocationFreshnessTime;
+             public BOOL fOmitUsageCheck;
+             public char* pwszSslCtlStoreName;
+             public char* pwszSslCtlIdentifier;
+         }
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial int EncryptMessage(
 +            ref CredHandle contextHandle,
 +            uint qualityOfProtection,
 +            ref SecBufferDesc inputOutput,
 +            uint sequenceNumber);
  
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern unsafe int DecryptMessage(
 -              [In] ref CredHandle contextHandle,
 -              [In, Out] ref SecBufferDesc inputOutput,
 -              [In] uint sequenceNumber,
 -                   uint* qualityOfProtection
 -              );
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static unsafe partial int DecryptMessage(
 +            ref CredHandle contextHandle,
 +            ref SecBufferDesc inputOutput,
 +            uint sequenceNumber,
 +            uint* qualityOfProtection);
  
          [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
          internal static extern int QuerySecurityContextToken(
              ref CredHandle phContext,
 -            [Out] out SecurityContextTokenHandle handle);
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern int FreeContextBuffer(
 -            [In] IntPtr contextBuffer);
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern int FreeCredentialsHandle(
 -              ref CredHandle handlePtr
 -              );
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern int DeleteSecurityContext(
 -              ref CredHandle handlePtr
 -              );
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern unsafe int AcceptSecurityContext(
 -                  ref CredHandle credentialHandle,
 -                  [In] void* inContextPtr,
 -                  [In] SecBufferDesc* inputBuffer,
 -                  [In] ContextFlags inFlags,
 -                  [In] Endianness endianness,
 -                  ref CredHandle outContextPtr,
 -                  [In, Out] ref SecBufferDesc outputBuffer,
 -                  [In, Out] ref ContextFlags attributes,
 -                  out long timeStamp
 -                  );
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern unsafe int QueryContextAttributesW(
 +            out SecurityContextTokenHandle handle);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial int FreeContextBuffer(
 +            IntPtr contextBuffer);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial int FreeCredentialsHandle(
 +            ref CredHandle handlePtr);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial int DeleteSecurityContext(
 +            ref CredHandle handlePtr);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static unsafe partial int AcceptSecurityContext(
 +            ref CredHandle credentialHandle,
 +            void* inContextPtr,
 +            SecBufferDesc* inputBuffer,
 +            ContextFlags inFlags,
 +            Endianness endianness,
 +            ref CredHandle outContextPtr,
 +            ref SecBufferDesc outputBuffer,
 +            ref ContextFlags attributes,
 +            out long timeStamp);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static unsafe partial int QueryContextAttributesW(
              ref CredHandle contextHandle,
 -            [In] ContextAttribute attribute,
 -            [In] void* buffer);
 +            ContextAttribute attribute,
 +            void* buffer);
  
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern int SetContextAttributesW(
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial int SetContextAttributesW(
              ref CredHandle contextHandle,
 -            [In] ContextAttribute attribute,
 -            [In] byte[] buffer,
 -            [In] int bufferSize);
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern int EnumerateSecurityPackagesW(
 -            [Out] out int pkgnum,
 -            [Out] out SafeFreeContextBuffer_SECURITY handle);
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 -        internal static extern unsafe int AcquireCredentialsHandleW(
 -                  [In] string? principal,
 -                  [In] string moduleName,
 -                  [In] int usage,
 -                  [In] void* logonID,
 -                  [In] IntPtr zero,
 -                  [In] void* keyCallback,
 -                  [In] void* keyArgument,
 -                  ref CredHandle handlePtr,
 -                  [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 moduleName,
 -                  [In] int usage,
 -                  [In] void* logonID,
 -                  [In] SafeSspiAuthDataHandle authdata,
 -                  [In] void* keyCallback,
 -                  [In] void* keyArgument,
 -                  ref CredHandle handlePtr,
 -                  [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 moduleName,
 -                  [In] int usage,
 -                  [In] void* logonID,
 -                  [In] SCHANNEL_CRED* authData,
 -                  [In] void* keyCallback,
 -                  [In] void* keyArgument,
 -                  ref CredHandle handlePtr,
 -                  [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 moduleName,
 -          [In] int usage,
 -          [In] void* logonID,
 -          [In] SCH_CREDENTIALS* authData,
 -          [In] void* keyCallback,
 -          [In] void* keyArgument,
 -          ref CredHandle handlePtr,
 -          [Out] out long timeStamp
 -          );
 -
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern unsafe int InitializeSecurityContextW(
 -                  ref CredHandle credentialHandle,
 -                  [In] void* inContextPtr,
 -                  [In] byte* targetName,
 -                  [In] ContextFlags inFlags,
 -                  [In] int reservedI,
 -                  [In] Endianness endianness,
 -                  [In] SecBufferDesc* inputBuffer,
 -                  [In] int reservedII,
 -                  ref CredHandle outContextPtr,
 -                  [In, Out] ref SecBufferDesc outputBuffer,
 -                  [In, Out] ref ContextFlags attributes,
 -                  out long timeStamp
 -                  );
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern unsafe int CompleteAuthToken(
 -                  [In] void* inContextPtr,
 -                  [In, Out] ref SecBufferDesc inputBuffers
 -                  );
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern unsafe int ApplyControlToken(
 -          [In] void* inContextPtr,
 -          [In, Out] ref SecBufferDesc inputBuffers
 -          );
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 -        internal static extern SECURITY_STATUS SspiFreeAuthIdentity(
 -            [In] IntPtr authData);
 -
 -        [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 -        internal static extern SECURITY_STATUS SspiEncodeStringsAsAuthIdentity(
 -            [In] string userName,
 -            [In] string domainName,
 -            [In] string password,
 -            [Out] out SafeSspiAuthDataHandle authData);
 -
 +            ContextAttribute attribute,
 +            byte[] buffer,
 +            int bufferSize);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial int EnumerateSecurityPackagesW(
 +            out int pkgnum,
 +            out SafeFreeContextBuffer_SECURITY handle);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 +        internal static unsafe partial int AcquireCredentialsHandleW(
 +            string? principal,
 +            string moduleName,
 +            int usage,
 +            void* logonID,
 +            IntPtr zero,
 +            void* keyCallback,
 +            void* keyArgument,
 +            ref CredHandle handlePtr,
 +            out long timeStamp);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 +        internal static unsafe partial int AcquireCredentialsHandleW(
 +            string? principal,
 +            string moduleName,
 +            int usage,
 +            void* logonID,
 +            SafeSspiAuthDataHandle authdata,
 +            void* keyCallback,
 +            void* keyArgument,
 +            ref CredHandle handlePtr,
 +            out long timeStamp);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 +        internal static unsafe partial int AcquireCredentialsHandleW(
 +            string? principal,
 +            string moduleName,
 +            int usage,
 +            void* logonID,
 +            SCHANNEL_CRED* authData,
 +            void* keyCallback,
 +            void* keyArgument,
 +            ref CredHandle handlePtr,
 +            out long timeStamp);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 +        internal static unsafe partial int AcquireCredentialsHandleW(
 +            string? principal,
 +            string moduleName,
 +            int usage,
 +            void* logonID,
 +            SCH_CREDENTIALS* authData,
 +            void* keyCallback,
 +            void* keyArgument,
 +            ref CredHandle handlePtr,
 +            out long timeStamp);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static unsafe partial int InitializeSecurityContextW(
 +            ref CredHandle credentialHandle,
 +            void* inContextPtr,
 +            byte* targetName,
 +            ContextFlags inFlags,
 +            int reservedI,
 +            Endianness endianness,
 +            SecBufferDesc* inputBuffer,
 +            int reservedII,
 +            ref CredHandle outContextPtr,
 +            ref SecBufferDesc outputBuffer,
 +            ref ContextFlags attributes,
 +            out long timeStamp);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static unsafe partial int CompleteAuthToken(
 +            void* inContextPtr,
 +            ref SecBufferDesc inputBuffers);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static unsafe partial int ApplyControlToken(
 +            void* inContextPtr,
 +            ref SecBufferDesc inputBuffers);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)]
 +        internal static partial SECURITY_STATUS SspiFreeAuthIdentity(
 +            IntPtr authData);
 +
 +        [GeneratedDllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
 +        internal static partial SECURITY_STATUS SspiEncodeStringsAsAuthIdentity(
 +            string userName,
 +            string domainName,
 +            string password,
 +            out SafeSspiAuthDataHandle authData);
++
++        // TODO: Switch to use GeneratedDllImport once we annotate blittable types used in interop in CoreLib (like Guid)
+         [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
+         internal static extern SECURITY_STATUS SetCredentialsAttributesW(
 -            [In] ref CredHandle handlePtr,
 -            [In] long ulAttribute,
 -            [In] ref SecPkgCred_ClientCertPolicy pBuffer,
 -            [In] long cbBuffer);
++            in CredHandle handlePtr,
++            long ulAttribute,
++            in SecPkgCred_ClientCertPolicy pBuffer,
++            long cbBuffer);
      }
  }
@@@ -9,23 -9,13 +9,23 @@@ internal static partial class Intero
  {
      internal static partial class WinHttp
      {
 +#if DLLIMPORTGENERATOR_ENABLED
 +        [GeneratedDllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
 +        public static partial SafeWinHttpHandle WinHttpOpen(
 +#else
          [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
          public static extern SafeWinHttpHandle WinHttpOpen(
 +#endif
              IntPtr userAgent,
              uint accessType,
-             string proxyName,
-             string proxyBypass, int flags);
+             string? proxyName,
+             string? proxyBypass, int flags);
  
 +#if DLLIMPORTGENERATOR_ENABLED
 +        [GeneratedDllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
 +        [return: MarshalAs(UnmanagedType.Bool)]
 +        public static partial bool WinHttpCloseHandle(
 +#else
          [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
          [return: MarshalAs(UnmanagedType.Bool)]
          public static extern bool WinHttpCloseHandle(
              SafeWinHttpHandle requestHandle,
              uint authTargets,
              uint authScheme,
-             string userName,
-             string password,
+             string? userName,
+             string? password,
              IntPtr reserved);
  
 +#if DLLIMPORTGENERATOR_ENABLED
 +        [GeneratedDllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
 +        [return: MarshalAs(UnmanagedType.Bool)]
 +        public static partial bool WinHttpQueryAuthSchemes(
 +#else
          [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
          [return: MarshalAs(UnmanagedType.Bool)]
          public static extern bool WinHttpQueryAuthSchemes(
index 0000000,41d1276..5bd923a
mode 000000,100644..100644
--- /dev/null
@@@ -1,0 -1,90 +1,90 @@@
 -                        eppStruct.pwszServerName = namePtr;
+ // Licensed to the .NET Foundation under one or more agreements.
+ // The .NET Foundation licenses this file to you under the MIT license.
+ using Microsoft.Win32.SafeHandles;
+ using System.Diagnostics;
+ using System.Net.Security;
+ using System.Runtime.InteropServices;
+ using System.Security.Cryptography;
+ using System.Security.Cryptography.X509Certificates;
+ using System.Security.Principal;
+ namespace System.Net
+ {
+     internal static partial class CertificateValidation
+     {
+         internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, 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.
+             {
+                 throw new CryptographicException(Marshal.GetLastPInvokeError());
+             }
+             if (checkCertName)
+             {
+                 unsafe
+                 {
+                     uint status = 0;
+                     var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA()
+                     {
+                         cbSize = (uint)sizeof(Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA),
+                         // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client).
+                         dwAuthType = isServer ? Interop.Crypt32.AuthType.AUTHTYPE_CLIENT : Interop.Crypt32.AuthType.AUTHTYPE_SERVER,
+                         fdwChecks = 0,
+                         pwszServerName = null
+                     };
+                     var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA()
+                     {
+                         cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_PARA),
+                         dwFlags = 0,
+                         pvExtraPolicyPara = &eppStruct
+                     };
+                     fixed (char* namePtr = hostName)
+                     {
++                        eppStruct.pwszServerName = (ushort*)namePtr;
+                         cppStruct.dwFlags |=
+                             (Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL &
+                              ~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG);
+                         SafeX509ChainHandle chainContext = chain.SafeHandle!;
+                         status = Verify(chainContext, ref cppStruct);
+                         if (status == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH)
+                         {
+                             sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
+                         }
+                     }
+                 }
+             }
+             if (!chainBuildResult)
+             {
+                 sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
+             }
+             return sslPolicyErrors;
+         }
+         private static unsafe uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp)
+         {
+             Interop.Crypt32.CERT_CHAIN_POLICY_STATUS status = default;
+             status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS);
+             bool errorCode =
+                 Interop.Crypt32.CertVerifyCertificateChainPolicy(
+                     (IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL,
+                     chainContext,
+                     ref cpp,
+                     ref status);
+             if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(chainContext, $"CertVerifyCertificateChainPolicy returned: {errorCode}. Status: {status.dwError}");
+             return status.dwError;
+         }
+     }
+ }
@@@ -121,9 -123,36 +123,36 @@@ namespace System.Net.Securit
          public static SafeFreeCredentials AcquireCredentialsHandle(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
          {
              // New crypto API supports TLS1.3 but it does not allow to force NULL encryption.
-             return !UseNewCryptoApi || policy == EncryptionPolicy.NoEncryption ?
+             SafeFreeCredentials cred = !UseNewCryptoApi || policy == EncryptionPolicy.NoEncryption ?
                          AcquireCredentialsHandleSchannelCred(certificateContext?.Certificate, protocols, policy, isServer) :
                          AcquireCredentialsHandleSchCredentials(certificateContext?.Certificate, protocols, policy, isServer);
 -                            ref cred._handle,
+             if (certificateContext != null && certificateContext.Trust != null && certificateContext.Trust._sendTrustInHandshake)
+             {
+                 AttachCertificateStore(cred, certificateContext.Trust._store!);
+             }
+             return cred;
+         }
+         private static unsafe void AttachCertificateStore(SafeFreeCredentials cred, X509Store store)
+         {
+             Interop.SspiCli.SecPkgCred_ClientCertPolicy clientCertPolicy = default;
+             fixed (char* ptr = store.Name)
+             {
+                 clientCertPolicy.pwszSslCtlStoreName = ptr;
+                 Interop.SECURITY_STATUS errorCode = Interop.SspiCli.SetCredentialsAttributesW(
 -                            ref clientCertPolicy,
++                            cred._handle,
+                             (long)Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_CERT_POLICY,
++                            clientCertPolicy,
+                             sizeof(Interop.SspiCli.SecPkgCred_ClientCertPolicy));
+                 if (errorCode != Interop.SECURITY_STATUS.OK)
+                 {
+                     throw new Win32Exception((int)errorCode);
+                 }
+             }
+             return;
          }
  
          // This is legacy crypto API used on .NET Framework and older Windows versions.
@@@ -55,9 -55,8 +55,9 @@@ namespace Syste
                  // send a WM_SETTINGCHANGE message to all windows
                  fixed (char* lParam = "Environment")
                  {
 -                    IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, (IntPtr)lParam, 0, 1000, out IntPtr _);
 +                    IntPtr unused;
 +                    IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, (IntPtr)lParam, 0, 1000, &unused);
-                     Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastPInvokeError());
+                     Debug.Assert(r != IntPtr.Zero, $"SetEnvironmentVariable failed: {Marshal.GetLastPInvokeError()}");
                  }
              }
          }
               Link="Common\Interop\Windows\Kernel32\Interop.GetSystemInfo.cs" />
    </ItemGroup>
    <ItemGroup>
 +    <Reference Include="System.Memory" />
      <Reference Include="System.Reflection" />
      <Reference Include="System.Reflection.Extensions" />
+     <Reference Include="System.Memory" />
      <Reference Include="System.Runtime" />
      <Reference Include="System.Runtime.InteropServices" />
      <Reference Include="System.Threading" />
@@@ -488,33 -492,35 +492,35 @@@ namespace Internal.Cryptography.Pa
          {
              get
              {
-                 int extensionCount = Interop.Crypto.X509GetExtCount(_cert);
-                 X509Extension[] extensions = new X509Extension[extensionCount];
+                 return UseCertInteriorData(static cert => {
+                     int extensionCount = Interop.Crypto.X509GetExtCount(cert);
+                     X509Extension[] extensions = new X509Extension[extensionCount];
  
-                 for (int i = 0; i < extensionCount; i++)
-                 {
-                     IntPtr ext = Interop.Crypto.X509GetExt(_cert, i);
+                     for (int i = 0; i < extensionCount; i++)
+                     {
+                         IntPtr ext = Interop.Crypto.X509GetExt(cert, i);
  
-                     Interop.Crypto.CheckValidOpenSslHandle(ext);
+                         Interop.Crypto.CheckValidOpenSslHandle(ext);
  
-                     IntPtr oidPtr = Interop.Crypto.X509ExtensionGetOid(ext);
+                         IntPtr oidPtr = Interop.Crypto.X509ExtensionGetOid(ext);
  
-                     Interop.Crypto.CheckValidOpenSslHandle(oidPtr);
+                         Interop.Crypto.CheckValidOpenSslHandle(oidPtr);
  
-                     string oidValue = Interop.Crypto.GetOidValue(oidPtr);
-                     Oid oid = new Oid(oidValue);
+                         string oidValue = Interop.Crypto.GetOidValue(oidPtr);
+                         Oid oid = new Oid(oidValue);
  
-                     IntPtr dataPtr = Interop.Crypto.X509ExtensionGetData(ext);
+                         IntPtr dataPtr = Interop.Crypto.X509ExtensionGetData(ext);
  
-                     Interop.Crypto.CheckValidOpenSslHandle(dataPtr);
+                         Interop.Crypto.CheckValidOpenSslHandle(dataPtr);
  
-                     byte[] extData = Interop.Crypto.GetAsn1StringBytes(dataPtr);
-                     bool critical = Interop.Crypto.X509ExtensionGetCritical(ext) != 0;
+                         byte[] extData = Interop.Crypto.GetAsn1StringBytes(dataPtr);
 -                        bool critical = Interop.Crypto.X509ExtensionGetCritical(ext);
++                        bool critical = Interop.Crypto.X509ExtensionGetCritical(ext) != 0;
  
-                     extensions[i] = new X509Extension(oid, extData, critical);
-                 }
+                         extensions[i] = new X509Extension(oid, extData, critical);
+                     }
  
-                 return extensions;
+                     return extensions;
+                 });
              }
          }
  
@@@ -4,8 -4,8 +4,9 @@@
      <DefineConstants>$(DefineConstants);HAVE_THUMBPRINT_OVERLOADS</DefineConstants>
      <DefineConstants Condition="'$(TargetsUnix)' == 'true'">$(DefineConstants);Unix</DefineConstants>
      <IncludeRemoteExecutor>true</IncludeRemoteExecutor>
+     <NoWarn>$(NoWarn);SYSLIB0026;SYSLIB0027;SYSLIB0028</NoWarn>
      <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Android;$(NetCoreAppCurrent)-Browser;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS</TargetFrameworks>
 +    <EnableDllImportGenerator>true</EnableDllImportGenerator>
    </PropertyGroup>
    <PropertyGroup>
      <UseAndroidCrypto Condition="'$(TargetsAndroid)' == 'true'">true</UseAndroidCrypto>