如何在Twisted中处理证书?Autobahn Python WSS连接故障排查
问题:Python Autobahn切换WSS协议后证书验证失败
原本基于Python Autobahn的代码通过WS协议连接Crossbar服务器,切换为WSS协议后无法连接。Crossbar端配置已完成,Javascript版本的Autobahn测试正常,服务器使用DigiCert认证证书,推测问题出在证书验证环节。
按Twisted官方文档编写的证书验证测试代码如下:
from __future__ import print_function import sys from twisted.internet import defer, endpoints, protocol, ssl, task, error def main(reactor, host, port=443): options = ssl.optionsForClientTLS(hostname=host.decode('utf-8')) port = int(port) class ShowCertificate(protocol.Protocol): def connectionMade(self): self.transport.write(b"GET / HTTP/1.0\r\n\r\n") self.done = defer.Deferred() def dataReceived(self, data): certificate = ssl.Certificate(self.transport.getPeerCertificate()) print("OK:", certificate) self.transport.abortConnection() def connectionLost(self, reason): print("Lost.") if not reason.check(error.ConnectionClosed): print("BAD:", reason.value) self.done.callback(None) return endpoints.connectProtocol( endpoints.SSL4ClientEndpoint(reactor, host, port, options), ShowCertificate() ).addCallback(lambda protocol: protocol.done) task.react(main, sys.argv[1:])
运行后报错:
('BAD:', Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],))
已安装PyPI上的service_identity和idna包,以下是解决方法:
一、正确解决证书验证问题
- 检查系统根证书信任库:Twisted默认使用系统根证书验证,确认DigiCert的根证书已在系统信任列表中。Linux可查看
/etc/ssl/certs目录;Windows通过证书管理器的「受信任根证书颁发机构」确认;Mac在钥匙串访问的系统根证书中检查。 - 手动指定根证书:若系统未包含DigiCert根证书,可下载官方根证书文件,修改代码中的SSL配置:
# 加载DigiCert根证书 digicert_root = ssl.Certificate.loadPEM(open("digicert_global_root.crt").read()) options = ssl.optionsForClientTLS( hostname=host.decode('utf-8'), trustRoot=digicert_root ) - 确认主机名匹配:确保代码中传入的
host与证书的CN字段或SAN扩展完全一致,比如证书为*.example.com,则需使用sub.example.com这类带前缀的域名连接。
二、绕过证书验证(仅测试环境使用)
注意:生产环境禁止使用,会引入严重安全风险
修改SSL配置跳过验证:
# 完全跳过证书验证 options = ssl.CertificateOptions(verify=False)
或保留主机名检查但跳过证书有效性验证:
from twisted.internet.ssl import AcceptableCertsPolicy options = ssl.optionsForClientTLS( hostname=host.decode('utf-8'), trustRoot=AcceptableCertsPolicy() )
内容的提问来源于stack exchange,提问作者Ace
相关产品推荐
相关产品推荐

