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
ipAddress = "127.0.0.1";
# Create a server socket
# Listen for incoming connections
# Get certificate from the client
# Check the client certificate bears the expected name as per server's policy
# Check time validity of the client certificate
if ts < t1:
# 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.
# IP address and the port number of the server
# Create an SSL context
# Load CA certificate with which the client will validate the server certificate
# Load client certificate
# Create a client socket
# Make the client socket suitable for secure communication
# 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:
Securely sent 2020-04-03 00:59:13.419609 to ('127.0.0.1', 60047)
Securely sent 2020-04-03 00:59:15.225650 to ('127.0.0.1', 60048)
Output - Client:
Secure communication received from server:2020-04-03 00:59:15.225650