Python code to print negotiated tls version at both client and server side during TLS communication

48 Views Asked by At

We can configure supported range of tls versions(at server). During the client to server TLS communication I need to print negotiated TLS version of communication, print this information both at the server and client side logs.

Here I have tried to give sample code(not a running code) from the client side, urllib3 is the client side module used to trigger URL corresponding to server. Supports both TLSv1_2 and TLSv1_3 versions.

self.__connection = ProxyManager(proxy_url=proxy_url,
                                         proxy_headers=self.__get_proxy_headers(),
                                         proxy_ssl_context=self.__get_proxy_ssl_context(proxy_url),
                                         cert_file=cert_file,
                                         key_file=cert_key,
                                         key_password=key_pwd,
                                         cert_reqs=cert_reqs,
                                         ca_certs=ca_cert,
                                         timeout=self._get_timeout(connect_timeout=self.__connect_timeout,
                                                                   read_timeout=self.__read_timeout),
                                         ssl_context=self.__get_ssl_context(),
                                         retries=False)
                                         
def __get_ssl_context():
    ssl_context = create_urllib3_context(ssl_version=ssl.PROTOCOL_TLS_CLIENT,
                                     
    ciphers=constants.SSL_TLS_CIPHER_SUITE)
    ssl_context.set_ecdh_curve(constants.SSL_TLS_CURVE)
    ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
    return ssl_context

Here is the server side code where SSL context is created and assigned to cherrypy server.

cheroot.server.ssl_adapters['ssl-password-adapter'] = SSLPasswordAdapter

class SSLPasswordAdapter(BuiltinSSLAdapter):
   def __init__(self, certificate, private_key, certificate_chain=None, ciphers=None):

    self.certificate = certificate
    self.private_key = private_key
    self.certificate_chain = certificate_chain
    self.ciphers = ciphers

    self.context = ssl.create_default_context(
        purpose=ssl.Purpose.CLIENT_AUTH,
        cafile=certificate_chain,
    )

    self.context.minimum_version = ssl.TLSVersion.TLSv1_2
    self.context.load_cert_chain(certificate, private_key, self._password)
    
    if self.ciphers is not None:
        self.context.set_ciphers(ciphers)
    else:
        self.context.set_ciphers(constants.SSL_TLS_CIPHER_SUITE)
        self.context.set_ecdh_curve(constants.SSL_TLS_CURVE)

Now, expectation is when server URL is triggered from the client side using urllib3 and it reaches the server side, negotiated TLS version has to be printed on both client and server side.

0

There are 0 best solutions below