在 TLS 网络套接字服务器中使用 SslStream 的问题
Problems using SslStream in a TLS web socket server
我按照 this example 创建了我的测试证书。我对服务器使用 Certificate.cer
,对客户端使用 Certificate.pfx
:
makecert -r -pe -n "CN=Test Certificate" -sky exchange Certificate.cer -sv Key.pvk -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2
"C:\Program Files (x86)\Windows Kits.1\bin\x64\pvk2pfx.exe" -pvk Key.pvk -spc Certificate.cer -pfx Certificate.pfx
我正在尝试创建一个网络套接字服务器并正确验证通信的客户端和服务器端的证书。这是我目前正在构建的整个控制台应用程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace WebSockets
{
class Program
{
static void Main(string[] args)
{
CreateWebSocketClient(CreateWebSocketServer(1337), 1338);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static IPEndPoint CreateWebSocketServer(int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(endpoint);
socket.Listen(Int32.MaxValue);
socket.BeginAccept((result) =>
{
var clientSocket = socket.EndAccept(result);
Console.WriteLine("{0}: Connected to the client at {1}.", DateTime.Now, clientSocket.RemoteEndPoint);
using (var stream = new SslStream(new NetworkStream(clientSocket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
return true;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.pfx");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsServer(new X509Certificate2("Certificate.pfx"), true, SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Read \"{1}\" from the client at {2}.", DateTime.Now, stream.ReadMessage(), clientSocket.RemoteEndPoint);
}
}, null);
Console.WriteLine("{0}: Web socket server started at {1}.", DateTime.Now, socket.LocalEndPoint);
return endpoint;
}
private static void CreateWebSocketClient(IPEndPoint remoteEndpoint, int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(localEndpoint);
socket.BeginConnect(remoteEndpoint, (result) =>
{
socket.EndConnect(result);
Console.WriteLine("{0}: Connected to the server at {1}.", DateTime.Now, remoteEndpoint);
using (var stream = new SslStream(new NetworkStream(socket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
return true;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.cer");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsClient(remoteEndpoint.ToString(), new X509Certificate2Collection(new X509Certificate2[] { new X509Certificate2("Certificate.cer") }), SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Read \"{1}\" from the server at {2}.", DateTime.Now, stream.ReadMessage(), remoteEndpoint);
}
}, null);
}
}
public static class StringExtensions
{
public static Byte[] ToByteArray(this String value)
{
Byte[] bytes = new Byte[value.Length * sizeof(Char)];
Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static String FromByteArray(this Byte[] bytes)
{
Char[] characters = new Char[bytes.Length / sizeof(Char)];
Buffer.BlockCopy(bytes, 0, characters, 0, bytes.Length);
return new String(characters).Trim(new Char[] { (Char)0 });
}
public static int BufferSize = 0x400;
public static String ReadMessage(this SslStream stream)
{
var buffer = new Byte[BufferSize];
stream.Read(buffer, 0, BufferSize);
return FromByteArray(buffer);
}
}
}
当你 运行 服务器和客户端之间的通信工作正常,但我不确定我应该如何实现回调,特别是因为 sslPolicyErrors = RemoteCertificateNotAvailable
当 RemoteCertificateValidationCallback is called on the server side and sslPolicyErrors = RemoteCertificateNameMismatch | RemoteCertificateChainErrors
when the RemoteCertificateValidationCallback 被调用时客户端。此外,certificate
和 chain
在服务器端为空,但出现在客户端的回调中。这是为什么?我的实施有什么问题,我怎样才能使我的实施正确验证 SSL 证书?我曾尝试在线搜索 SslStream
,但我还没有看到一个完整的、基于 X509 的 TLS 服务器-客户端实现,它可以执行我需要的证书验证类型。
我遇到了三个不同的问题。我最初的方法很好,但是:
我在这里误用了证书,因为在客户端使用 .pfx
证书解决了我的 RemoteCertificateNotAvailable
问题。我不确定为什么 .cer
不起作用。
我在调用 AuthenticateAsClient
时指定了错误的主题名称,因为第一个参数使用 "Test Certificate" 而不是 remoteEndpoint.ToString()
解决了我的 RemoteCertificateNameMismatch
.
尽管是自签名的,但为了避免 RemoteCertificateChainErrors
错误,我必须将此证书添加到我当前用户帐户下的“受信任的人”存储中,以便信任该证书。
包括其他一些小的改进,我的结果代码现在也接受多个客户端(因为我已经修复了上面的一些错误),如下所示(请不要逐字复制它需要在不同的地方有很多 Pokemon exception handling,适当的清理逻辑,利用读取调用时读取的字节而不是修剪 NUL,以及引入一些 Unicode 字符(例如 EOT)来指定消息的结尾,解析它,以及处理不支持的奇数大小的缓冲区,因为我们的 C# 字符大小是 2 个字节,处理奇数读取等;在它看到生产系统的光芒之前,这需要大量的改进并且仅作为示例或概念证明,如果您愿意的话。):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSockets
{
class Program
{
static void Main(string[] args)
{
IPEndPoint server = CreateWebSocketServer(1337);
CreateWebSocketClient(server, 1338);
CreateWebSocketClient(server, 1339);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static IPEndPoint CreateWebSocketServer(int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(endpoint);
socket.Listen(Int32.MaxValue);
ListenForClients(socket);
Console.WriteLine("{0}: Web socket server started at {1}.", DateTime.Now, socket.LocalEndPoint);
return endpoint;
}
private static void ListenForClients(Socket socket)
{
socket.BeginAccept((result) =>
{
new Thread(() =>
{
ListenForClients(socket);
}).Start();
var clientSocket = socket.EndAccept(result);
Console.WriteLine("{0}: Connected to the client at {1}.", DateTime.Now, clientSocket.RemoteEndPoint);
using (var stream = new SslStream(new NetworkStream(clientSocket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.pfx");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsServer(new X509Certificate2("Certificate.pfx"), true, SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Read \"{1}\" from the client at {2}.", DateTime.Now, stream.ReadMessage(), clientSocket.RemoteEndPoint);
}
}, null);
}
private static void CreateWebSocketClient(IPEndPoint remoteEndpoint, int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(localEndpoint);
socket.BeginConnect(remoteEndpoint, (result) =>
{
socket.EndConnect(result);
Console.WriteLine("{0}: Client at {1} connected to the server at {2}.", DateTime.Now, localEndpoint, remoteEndpoint);
using (var stream = new SslStream(new NetworkStream(socket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.pfx");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsClient("Test Certificate", new X509Certificate2Collection(new X509Certificate2[] { new X509Certificate2("Certificate.pfx") }), SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Client at {1} read \"{2}\" from the server at {3}.", DateTime.Now, localEndpoint, stream.ReadMessage(), remoteEndpoint);
}
}, null);
}
}
public static class StringExtensions
{
public static Byte[] ToByteArray(this String value)
{
Byte[] bytes = new Byte[value.Length * sizeof(Char)];
Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static String FromByteArray(this Byte[] bytes)
{
Char[] characters = new Char[bytes.Length / sizeof(Char)];
Buffer.BlockCopy(bytes, 0, characters, 0, bytes.Length);
return new String(characters).Trim(new Char[] { (Char)0 });
}
public static int BufferSize = 0x400;
public static String ReadMessage(this SslStream stream)
{
var buffer = new Byte[BufferSize];
stream.Read(buffer, 0, BufferSize);
return FromByteArray(buffer);
}
}
}
我希望这可以帮助其他人揭开 C# 中的 Web 套接字、SSL 流、X509 证书等的神秘面纱。快乐的编码。 :) 我可能最终会在我的博客上发布它的最终版本。
我按照 this example 创建了我的测试证书。我对服务器使用 Certificate.cer
,对客户端使用 Certificate.pfx
:
makecert -r -pe -n "CN=Test Certificate" -sky exchange Certificate.cer -sv Key.pvk -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2
"C:\Program Files (x86)\Windows Kits.1\bin\x64\pvk2pfx.exe" -pvk Key.pvk -spc Certificate.cer -pfx Certificate.pfx
我正在尝试创建一个网络套接字服务器并正确验证通信的客户端和服务器端的证书。这是我目前正在构建的整个控制台应用程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace WebSockets
{
class Program
{
static void Main(string[] args)
{
CreateWebSocketClient(CreateWebSocketServer(1337), 1338);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static IPEndPoint CreateWebSocketServer(int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(endpoint);
socket.Listen(Int32.MaxValue);
socket.BeginAccept((result) =>
{
var clientSocket = socket.EndAccept(result);
Console.WriteLine("{0}: Connected to the client at {1}.", DateTime.Now, clientSocket.RemoteEndPoint);
using (var stream = new SslStream(new NetworkStream(clientSocket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
return true;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.pfx");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsServer(new X509Certificate2("Certificate.pfx"), true, SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Read \"{1}\" from the client at {2}.", DateTime.Now, stream.ReadMessage(), clientSocket.RemoteEndPoint);
}
}, null);
Console.WriteLine("{0}: Web socket server started at {1}.", DateTime.Now, socket.LocalEndPoint);
return endpoint;
}
private static void CreateWebSocketClient(IPEndPoint remoteEndpoint, int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(localEndpoint);
socket.BeginConnect(remoteEndpoint, (result) =>
{
socket.EndConnect(result);
Console.WriteLine("{0}: Connected to the server at {1}.", DateTime.Now, remoteEndpoint);
using (var stream = new SslStream(new NetworkStream(socket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
return true;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.cer");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsClient(remoteEndpoint.ToString(), new X509Certificate2Collection(new X509Certificate2[] { new X509Certificate2("Certificate.cer") }), SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Read \"{1}\" from the server at {2}.", DateTime.Now, stream.ReadMessage(), remoteEndpoint);
}
}, null);
}
}
public static class StringExtensions
{
public static Byte[] ToByteArray(this String value)
{
Byte[] bytes = new Byte[value.Length * sizeof(Char)];
Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static String FromByteArray(this Byte[] bytes)
{
Char[] characters = new Char[bytes.Length / sizeof(Char)];
Buffer.BlockCopy(bytes, 0, characters, 0, bytes.Length);
return new String(characters).Trim(new Char[] { (Char)0 });
}
public static int BufferSize = 0x400;
public static String ReadMessage(this SslStream stream)
{
var buffer = new Byte[BufferSize];
stream.Read(buffer, 0, BufferSize);
return FromByteArray(buffer);
}
}
}
当你 运行 服务器和客户端之间的通信工作正常,但我不确定我应该如何实现回调,特别是因为 sslPolicyErrors = RemoteCertificateNotAvailable
当 RemoteCertificateValidationCallback is called on the server side and sslPolicyErrors = RemoteCertificateNameMismatch | RemoteCertificateChainErrors
when the RemoteCertificateValidationCallback 被调用时客户端。此外,certificate
和 chain
在服务器端为空,但出现在客户端的回调中。这是为什么?我的实施有什么问题,我怎样才能使我的实施正确验证 SSL 证书?我曾尝试在线搜索 SslStream
,但我还没有看到一个完整的、基于 X509 的 TLS 服务器-客户端实现,它可以执行我需要的证书验证类型。
我遇到了三个不同的问题。我最初的方法很好,但是:
我在这里误用了证书,因为在客户端使用
.pfx
证书解决了我的RemoteCertificateNotAvailable
问题。我不确定为什么.cer
不起作用。我在调用
AuthenticateAsClient
时指定了错误的主题名称,因为第一个参数使用 "Test Certificate" 而不是remoteEndpoint.ToString()
解决了我的RemoteCertificateNameMismatch
.尽管是自签名的,但为了避免
RemoteCertificateChainErrors
错误,我必须将此证书添加到我当前用户帐户下的“受信任的人”存储中,以便信任该证书。
包括其他一些小的改进,我的结果代码现在也接受多个客户端(因为我已经修复了上面的一些错误),如下所示(请不要逐字复制它需要在不同的地方有很多 Pokemon exception handling,适当的清理逻辑,利用读取调用时读取的字节而不是修剪 NUL,以及引入一些 Unicode 字符(例如 EOT)来指定消息的结尾,解析它,以及处理不支持的奇数大小的缓冲区,因为我们的 C# 字符大小是 2 个字节,处理奇数读取等;在它看到生产系统的光芒之前,这需要大量的改进并且仅作为示例或概念证明,如果您愿意的话。):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSockets
{
class Program
{
static void Main(string[] args)
{
IPEndPoint server = CreateWebSocketServer(1337);
CreateWebSocketClient(server, 1338);
CreateWebSocketClient(server, 1339);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static IPEndPoint CreateWebSocketServer(int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(endpoint);
socket.Listen(Int32.MaxValue);
ListenForClients(socket);
Console.WriteLine("{0}: Web socket server started at {1}.", DateTime.Now, socket.LocalEndPoint);
return endpoint;
}
private static void ListenForClients(Socket socket)
{
socket.BeginAccept((result) =>
{
new Thread(() =>
{
ListenForClients(socket);
}).Start();
var clientSocket = socket.EndAccept(result);
Console.WriteLine("{0}: Connected to the client at {1}.", DateTime.Now, clientSocket.RemoteEndPoint);
using (var stream = new SslStream(new NetworkStream(clientSocket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.pfx");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsServer(new X509Certificate2("Certificate.pfx"), true, SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Read \"{1}\" from the client at {2}.", DateTime.Now, stream.ReadMessage(), clientSocket.RemoteEndPoint);
}
}, null);
}
private static void CreateWebSocketClient(IPEndPoint remoteEndpoint, int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Loopback, port);
socket.Bind(localEndpoint);
socket.BeginConnect(remoteEndpoint, (result) =>
{
socket.EndConnect(result);
Console.WriteLine("{0}: Client at {1} connected to the server at {2}.", DateTime.Now, localEndpoint, remoteEndpoint);
using (var stream = new SslStream(new NetworkStream(socket), false, (sender, certificate, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return new X509Certificate2("Certificate.pfx");
}, EncryptionPolicy.RequireEncryption))
{
stream.AuthenticateAsClient("Test Certificate", new X509Certificate2Collection(new X509Certificate2[] { new X509Certificate2("Certificate.pfx") }), SslProtocols.Tls12, true);
stream.Write("Hello".ToByteArray());
Console.WriteLine("{0}: Client at {1} read \"{2}\" from the server at {3}.", DateTime.Now, localEndpoint, stream.ReadMessage(), remoteEndpoint);
}
}, null);
}
}
public static class StringExtensions
{
public static Byte[] ToByteArray(this String value)
{
Byte[] bytes = new Byte[value.Length * sizeof(Char)];
Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static String FromByteArray(this Byte[] bytes)
{
Char[] characters = new Char[bytes.Length / sizeof(Char)];
Buffer.BlockCopy(bytes, 0, characters, 0, bytes.Length);
return new String(characters).Trim(new Char[] { (Char)0 });
}
public static int BufferSize = 0x400;
public static String ReadMessage(this SslStream stream)
{
var buffer = new Byte[BufferSize];
stream.Read(buffer, 0, BufferSize);
return FromByteArray(buffer);
}
}
}
我希望这可以帮助其他人揭开 C# 中的 Web 套接字、SSL 流、X509 证书等的神秘面纱。快乐的编码。 :) 我可能最终会在我的博客上发布它的最终版本。