【问题标题】:HttpListener with SSL certificate hanging on GetContext()带有 SSL 证书的 HttpListener 挂在 GetContext() 上
【发布时间】:2015-07-19 19:52:02
【问题描述】:

我创建了一个 Windows 服务,它使用 HttpListener 来响应一些使用 .NET Framework 4.0 的第三方请求。侦听器通过以下方式绑定到 https 前缀:

listener.Prefixes.Add("https://+:" + Properties.Settings.Default.ListeningPort.ToString() + "/");

该服务还通过以下方式在计算机商店中自行注册 https 证书:

X509Certificate2 certificate = new X509Certificate2(Properties.Settings.Default.HttpsCertPath, "", X509KeyStorageFlags.MachineKeySet);
X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();

此外,该服务还使用以下方式在 Http API 中注册证书 - ip:port 绑定:

ProcessStartInfo psi = new ProcessStartInfo();            
psi.FileName = "netsh";
psi.Arguments = "http add sslcert ipport=0.0.0.0:" + Properties.Settings.Default.ListeningPort.ToString() + " certhash=" + certificate.Thumbprint + " appid=" + appId;
Process proc = Process.Start(psi);                
proc.WaitForExit();
psi.Arguments = "http add sslcert ipport=[::]:" + Properties.Settings.Default.ListeningPort.ToString() + " certhash=" + certificate.Thumbprint + " appid=" + appId;
Process proc = Process.Start(psi);
proc.WaitForExit();

一切正常,正如预期的那样......除了......(这里是邪恶的部分): 在运行了一段时间(一个小时左右)后,listener.GetContext() 不再返回,并且客户端因“连接重置”之类的错误而被丢弃。

【问题讨论】:

    标签: c# .net windows ssl httplistener


    【解决方案1】:

    经过漫长而痛苦的调查,我发现错误出在 HTTP API 级别,并且在 SSL 握手期间会发生故障,因此 listener.GetContext() 根本没有返回。更重要的是,我发现对于每个失败的请求,在 Windows 事件日志的系统日志中,都会记录以下错误:

    Source Schannel: A fatal error occurred when attempting to access the SSL server credential private key. The error code returned from the cryptographic module is 0x8009030D. The internal error state is 10001.
    

    Source HttpEvent: An error occurred while using SSL configuration for endpoint 0.0.0.0:9799.  The error status code is contained within the returned data.
    

    进一步深入研究这个问题,我注意到有一次,私钥从已安装的证书中消失了。再加上我在this link 上读到的内容,让我产生了不同的想法。所以我试了一下:

    X509Certificate2 certificate = new X509Certificate2(Properties.Settings.Default.HttpsCertPath, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
    

    基本上,我已经输入了X509KeyStorageFlags.Exportable(还记得如果您没有在 IIS 上将证书标记为可导出,则在创建 SSL 绑定时出现的错误吗?)和X509KeyStorageFlags.PersistKeySet 标志。 这似乎已经完成了这项工作。该服务已经运行了将近两天,并且仍然愉快地接受传入的连接。

    希望这能让别人摆脱我所经历的麻烦。

    【讨论】:

    • 由于该解决方案仍然有效,并且没有人介入提供额外的答案,我会接受这个。
    • 天哪,你拯救了这一天,我的 httpListener 和 SSL 绑定也有同样的问题。一段时间后我失去了联系。我在 Windows 系统日志中看到了错误,幸运的是,一个链接让我来到了这里 :)
    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    相关资源
    最近更新 更多