1

Following advice from Jean-Paul Calderone here on SO, I'm trying to modify the twisted "starttls_server" sample below to support the use of ssl.ClientCertificateOptions, to allow me to specify my private key, certificate, and trusted roots, as per 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)

My understanding is that I effectively need to replace the cert = ssl.PrivateCertificate... and cert.options = ssl.PrivateCertificate.... lines with something like certopts = ssl.CertificateOptions(privateKey=pKeyData, certificate=certData, trustRoot=caCertsData) (having read the appropriate files in to certData, caCertsData, and pKeyData) and then pass this in to factory.options - but without pasting every variant of code I've tried, I've yet to work this out correctly - my efforts have produced varying results from the classic "OpenSSL.crypto.Error: []" - through to seemingly just dumping the contents of my 3 PEM files to screen and exiting!

Can anyone enlighten me? Thank you :)

4

1 回答 1

1

cert.options()已经返回一个CertificateOptions. 问题在于options将权限(作为Certificate对象)作为位置参数,并且不允许您通过所有其他配置值,因此您可能想CertificateOptions直接构造一个。

只需将factory.options = cert.options()行更改为factory.options = ssl.CertificateOptions(...).

但是,CertificateOptions将 pyOpenSSLPKey对象作为其privateKey,而不是关键数据。因此,您需要使用 OpenSSL API 来加载该密钥,或者您可以从PrivateCertificate.

如果您CertificateOptions仔细阅读 的签名,所需的类型应该相当清楚。您可能还需要查阅pyOpenSSL文档。

于 2014-10-01T18:32:08.327 回答