为什么不支持在同一进程中使用相同证书调用SslStream.AuthenticateAsServer和SslStream



我最近在将套接字通信转换为使用System.Net.Security.slStream而不是NetworkStream时遇到了一个问题。此次转换的目标是.Net Framework 4.8项目的解决方案。此任务的要求规定了双向TLS身份验证。这项工作以平静的方式进行,直到我转换了一个包含服务器和客户端的项目中的代码。在这一点上,行为是这样的:发生的第一个相互验证的连接(无论是客户端还是服务器(将成功,而第二个总是失败。需要指出的是,每个进程都有自己的证书。在第二次连接尝试期间引发的异常为:

System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm

经过一些实验,我发现如果每个进程有两个唯一的证书,并将一个用于所有的SslStream.AuthenticateAsServer调用,另一个用于全部的SslStream.AuthenticatedAsClient调用,我就不会有任何问题。尽管找到了解决这个问题的方法,但我仍然不明白为什么对服务器和客户端连接都使用单一证书是个问题。我在网上找不到任何解释。

我创建了一个解决方案,用很少的代码来演示这个问题。该解决方案包含一个带有TlsSample类的类库项目,以及两个试图相互连接的控制台应用程序(AServer和BServer(。

TlsSample:

using System;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace TlsSampleShared
{
public class TlsSample
{
private X509Certificate2Collection certs;
private int _listenerPort;
private int _clientPort;
private string _certificateName;
private TimeSpan _connectionDelay;
public TlsSample(int listenerPort, int clientPort, string certificateName, TimeSpan connectionDelay)
{
_listenerPort = listenerPort;
_clientPort = clientPort;
_certificateName = certificateName;
_connectionDelay = connectionDelay;
}
public async Task ConnectAsync()
{
using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
certs = store.Certificates.Find(X509FindType.FindBySubjectName, _certificateName, true);
Console.WriteLine($"Using certificate {certs[0].Subject} with thumbnail {certs[0].Thumbprint}.");
}
var listenTask = Task.Run(Listen);
await Task.Delay(_connectionDelay);
var aClient = new TcpClient();
aClient.Connect(IPAddress.Loopback, _clientPort);
var s = new SslStream(aClient.GetStream());
Authenticate(aClient, s, false);
await listenTask;
}
private async Task Listen()
{
var l = new TcpListener(new IPEndPoint(IPAddress.Any, _listenerPort));
l.Start();
var c = await l.AcceptTcpClientAsync();
var s = new SslStream(c.GetStream());
Authenticate(c, s, true);
}
private void Authenticate(TcpClient c, SslStream s, bool server)
{
try
{
if (server)
s.AuthenticateAsServer(certs[0], true, false);
else
s.AuthenticateAsClient(Dns.GetHostName(), certs, false);
Console.WriteLine($@"TLS {(server ? "server" : "client")} handshake succeeded between ({c.Client.LocalEndPoint}-{c.Client.RemoteEndPoint}):
Authenticated: {s.IsAuthenticated}
Mutually Authenticated: {s.IsMutuallyAuthenticated}
Server: {s.IsServer}
Encrypted: {s.IsEncrypted}
Signed: {s.IsSigned}
Key Exchange Algorithm: {s.KeyExchangeAlgorithm}
Key Exchange Strength: {s.KeyExchangeStrength}
Cipher Algorithm: {s.CipherAlgorithm}
Cipher Strength: {s.CipherStrength}
Hash Algorithm: {s.HashAlgorithm}
Hash Strength: {s.HashStrength}
Ssl Protocol: {s.SslProtocol}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while authenticating ({c.Client.LocalEndPoint}-{c.Client.RemoteEndPoint}) as a {(server ? "server" : "client")}{Environment.NewLine}{ex}");
}
}
}
}

A服务器/程序.cs:

using System;
using System.Threading.Tasks;
using TlsSampleShared;
namespace AServer
{
class Program
{
static async Task Main() => await new TlsSample(7000, 7001, "serverA.VM-MIL-SM", TimeSpan.FromSeconds(1)).ConnectAsync();
}
}

B服务器/程序.cs:

using System;
using System.Threading.Tasks;
using TlsSampleShared;
namespace BServer
{
class Program
{
static async Task Main() => await new TlsSample(7001, 7000, "serverB.VM-MIL-SM", TimeSpan.FromSeconds(2)).ConnectAsync();
}
}

若要进行实验,您需要在证书存储中拥有两个证书。任何关于为什么使用单个证书的客户端和服务器身份验证在同一过程中都失败的见解都将不胜感激。

我在玩我的示例时注意到的一个额外的信息是,当AServer和BServer试图基本上同时连接时,我会遇到不同的异常。这可以通过为AServer和BServer设置相同的连接延迟来实现。在这种情况下,两个连接都不成功,抛出的异常为:

System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The Local Security Authority cannot be contacted

Microsoft确认此行为是一个错误(至少在.Net Framework 4.8中是这样(。.Net 5中的SslStream类中不存在此错误。

最新更新