Twisted listenSSL virtualhosts

前端 未结 3 541
天命终不由人
天命终不由人 2021-01-26 19:22

Currently using a really simple Twisted NameVirtualHost coupled with some JSON config files to serve really basic content in one Site object. The reso

3条回答
  •  耶瑟儿~
    2021-01-26 19:59

    Just to add some closure to this one, and for future searches, here is the example code for the echo server from the examples that prints the SNI:

    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()
    

    And because getting OpenSSL to work can always be tricky, here is the OpenSSL statement you can use to connect to it:

    openssl s_client -connect localhost:8000 -servername hello_world -cert keys/client.crt -key keys/client.key
    

    Running the above python code against pyOpenSSL==0.13, and then running the s_client command above, will print this to the screen:

    ('Received SNI: ', 'hello_world')
    

提交回复
热议问题