Twisted listenSSL virtualhosts

前端 未结 3 542
天命终不由人
天命终不由人 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 20:20

    TLS (the name for the modern protocol which replaces SSL) only very recently supports the feature you're looking for. The feature is called Server Name Indication (or SNI). It is supported by modern browsers on modern platforms, but not some older but still widely used platforms (see the wikipedia page for a list of browsers with support).

    Twisted has no specific, built-in support for this. However, it doesn't need any. pyOpenSSL, upon which Twisted's SSL support is based, does support SNI.

    The set_tlsext_servername_callback pyOpenSSL API gives you the basic mechanism to build the behavior you want. This lets you define a callback which is given access to the server name requested by the client. At this point, you can specify the key/certificate pair you want to use for the connection. You can find an example demonstrating the use of this API in pyOpenSSL's examples directory.

    Here's an excerpt from that example to give you the gist:

    def pick_certificate(connection):
        try:
            key, cert = certificates[connection.get_servername()]
        except KeyError:
            pass
        else:
            new_context = Context(TLSv1_METHOD)
            new_context.use_privatekey(key)
            new_context.use_certificate(cert)
            connection.set_context(new_context)
    
    server_context = Context(TLSv1_METHOD)
    server_context.set_tlsext_servername_callback(pick_certificate)
    

    You can incorporate this approach into a customized context factory and then supply that context factory to the listenSSL call.

提交回复
热议问题