只是为了给这个添加一些闭包,为了将来的搜索,这里是来自打印 SNI 的示例中的 echo 服务器的示例代码:
from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol
class Echo(Protocol):
def dataReceived(self, data):
self.transport.write(data)
def pick_cert(connection):
print('Received SNI: ', connection.get_servername())
if __name__ == '__main__':
factory = Factory()
factory.protocol = Echo
with open("keys/ca.pem") as certAuthCertFile:
certAuthCert = ssl.Certificate.loadPEM(certAuthCertFile.read())
with open("keys/server.key") as keyFile:
with open("keys/server.crt") as certFile:
serverCert = ssl.PrivateCertificate.loadPEM(
keyFile.read() + certFile.read())
contextFactory = serverCert.options(certAuthCert)
ctx = contextFactory.getContext()
ctx.set_tlsext_servername_callback(pick_cert)
reactor.listenSSL(8000, factory, contextFactory)
reactor.run()
而且因为让 OpenSSL 工作总是很棘手,所以您可以使用以下 OpenSSL 语句来连接它:
openssl s_client -connect localhost:8000 -servername hello_world -cert keys/client.crt -key keys/client.key
针对 pyOpenSSL==0.13 运行上面的 python 代码,然后运行上面的 s_client 命令,将把它打印到屏幕上:
('Received SNI: ', 'hello_world')