我跟着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\8.1\bin\x64\pvk2pfx.exe" -pvk Key.pvk -spc Certificate.cer -pfx Certificate.pfx
我正在尝试创建一个Web套接字服务器,并正确验证来自通信客户端和服务器端的证书。这是我目前正在构建的整个控制台应用程序:
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时sslPolicyErrors = RemoteCertificateNameMismatch | RemoteCertificateChainErrors
和{{ 1}}在客户端调用RemoteCertificateValidationCallback时。此外,certificate
和chain
在服务器端为空,但在客户端的回调中显示。这是为什么?我的实现有什么问题,如何让我的实现正确验证SSL证书?我尝试在线搜索SslStream
,但我还没有看到一个完整的,基于X509的TLS服务器 - 客户端实现,它实现了我需要的证书验证类型。
答案 0 :(得分:2)
我有三个不同的问题。我最初的做法很好,但是:
我在这里滥用了证书,因为在客户端使用.pfx
证书可以解决我的RemoteCertificateNotAvailable
问题。我不确定为什么.cer
不起作用。
我在调用AuthenticateAsClient
时指定了错误的主题名称,如使用"测试证书"对于第一个参数而不是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证书等的神秘面纱。快乐的编码。 :)我最终可能会在我的博客上发布最终版本。