Overview:
-
The SSLSocket class is derived from the socket class and represents a secure socket in TLS context.
-
The Python examples given here use SSLSocket instances in both server and client scenarios.
Example Server program that uses TLS:
- The SSL server program creates a server socket and listens on port 15001 on localhost.
- When a client connection is accepted, a client socket is created which is wrapped into a SSLSocket.
- The SSLSocket is supplied with the CA Certificate, the certificate of the server and the corresponding private key.
- A call to the getpeercert() on the secure client connection(ie., the SSLSocket instance) gets the certificate of the client.
- The server program validates the common Name, time validity of the certificate before sending any information over the secure connection with the client.
# Example SSL server program that listens at port 15001. import ssl # IP and port number # Create a server socket # Listen for incoming connections while(True): # Create an SSL Context # Load the certificate and the private key # The program uses a self-signed root certificate. clt_subject = dict(item[0] for item in client_cert['subject']) # Check the client certificate bears the expected name as per server's policy # Check time validity of the client certificate if ts < t1: # Recieve communication from server # Send current server time to the client # Close the connection to the client |
Example Client program that uses TLS:
- The client program makes use of the SSLContext instance to load the CA certificate, client certificate and the corresponding private key.
- The client creates a stream based socket and wraps it around an SSLSocket instance.
- Through the SSLSocket instance the security aspects of the communication: Privacy, Data Integrity and Authentication are taken care.
- Once the SSLSocket instance makes a connection to the server listening on a specific IP address and Port it requests for the certificate of the server to which it is connected to.
- The fields of the certificate like commonName, notBefore and notAfter are validated before any communication is received from the server.
# Example TLS client(a.k.a SSL client) that connects to a # IP address and the port number of the server # Create an SSL context
# Ease the policy of Python3.13 towards self-signed certificates # Load client certificate # Create a client socket # Obtain the certificate from the server # Validate whether the Certificate is indeed issued to the server if not server_cert: notAfterTimestamp = ssl.cert_time_to_seconds(server_cert['notAfter']) if currentTimeStamp > notAfterTimestamp: # Safe to proceed with the communication # Close the sockets |
Output - Server:
Server listening: |
Output - Client:
X.509 certificate of the server DemoServer: |