How to load multiple SSL certificates on server with python with sockets

229 views Asked by At

I'm creating a server that should support SSL. I have two pairs of signed cert and keyfile for two different domains.

To add both certs to the context I've tried two things:

  • Calling twice to context.load_cert_chain(certfile=certfile, keyfile=keyfile)
  • Concatenating both certfiles and keyfiles into one cerfile and one keyfile

Both tries didn't work since it seems the server is using just one of them. My understanding is that I can use Server Name Indication (SNI) to have two domain certs in the same IP.

How can I make Server Name Indication (SNI) work with python ssl? I guess the browsers should send that info to the servers for the servers to know what certificate to serve right? How can I know what cert does the client want before calling context.wrap_socket(csock, server_side=True)?

1

There are 1 answers

0
user1618465 On

I found the answer:

you need to setup a callback for sni:

self.context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
self.context.sni_callback = self.sni_callback

[...]

def sni_callback(self, sslsocket: ssl.SSLSocket, sni_name: str, sslcontext: ssl.SSLContext) -> None:
        if sni_name in self.certs:
            print(f"\tSNI: {sni_name}")
            new_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)

            certfile, keyfile = self.certs[sni_name]
            new_context.load_cert_chain(certfile=certfile, keyfile=keyfile)
            sslsocket.context = new_context

        return None