根据 Jean-Paul Calderone 在 SO 上的建议,我正在尝试修改下面扭曲的“starttls_server”示例以支持 ssl.ClientCertificateOptions 的使用,以允许我指定我的私钥、证书和受信任的根, 根据 http://twistedmatrix.com/documents/14.0.0/api/twisted.internet.ssl.CertificateOptions.html
from twisted.internet import ssl, protocol, defer, task, endpoints
from twisted.protocols.basic import LineReceiver
from twisted.python.modules import getModule
class TLSServer(LineReceiver):
def lineReceived(self, line):
print("received: " + line)
if line == "STARTTLS":
print("-- Switching to TLS")
self.sendLine('READY')
self.transport.startTLS(self.factory.options)
def main(reactor):
certData = getModule(__name__).filePath.sibling('server.pem').getContent()
cert = ssl.PrivateCertificate.loadPEM(certData)
factory = protocol.Factory.forProtocol(TLSServer)
factory.options = cert.options()
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8000)
endpoint.listen(factory)
return defer.Deferred()
if __name__ == '__main__':
import starttls_server
task.react(starttls_server.main)
我的理解是,我实际上需要用某些东西替换 cert = ssl.PrivateCertificate...
和 cert.options = ssl.PrivateCertificate...
行像 certopts = ssl.CertificateOptions(privateKey=pKeyData, certificate=certData, trustRoot=caCertsData)
(已将适当的文件读入 certData、caCertsData 和 pKeyData),然后将其传递给 factory.options
- 但没有粘贴我尝试过的每个代码变体,我还没有正确解决这个问题 - 我的努力产生了与经典“OpenSSL.crypto.Error:[]”不同的结果 -似乎只是将我的 3 个 PEM 文件的内容转储到屏幕上并退出!
谁能教教我?谢谢:)
最佳答案
cert.options()
已经返回一个 CertificateOptions
。问题是 options
将权限(作为 Certificate
对象)作为位置参数,并且不允许您传递所有其他配置值,因此您可能想要直接构造一个CertificateOptions
。
只需将 factory.options = cert.options()
行更改为 factory.options = ssl.CertificateOptions(...)
。
但是,CertificateOptions
将 pyOpenSSL PKey
对象作为其 privateKey
,而不是 key 数据。因此,您需要使用 OpenSSL API 加载该 key ,或者您可以从 PrivateCertificate
中提取它。
If you read the signature of CertificateOptions
very carefully ,所需的类型应该相当清楚。您可能还需要咨询 pyOpenSSL文档也是如此。
关于python - Twisted Python,在从纯文本切换到安全连接时使用 ssl.CertificateOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26145252/