Welcome to the documentation for network programming examples involving Transport Layer Security (TLS).
TLS is a cryptographic protocol that provides communications security over a computer network. It is widely used on the internet for applications such as web browsing, email, instant messaging, and voice over IP (VoIP).
This example demonstrates a simple TLS client and server setup. The client connects to the server over TLS, exchanging encrypted messages.
tls_server.py
)A basic Python server using the ssl
module.
import socket
import ssl
# Configuration
HOST = 'localhost'
PORT = 8443
CERTFILE = 'server.crt'
KEYFILE = 'server.key'
def handle_client(connstream):
try:
print("Client connected")
data = connstream.read()
print(f"Received: {data.decode()}")
connstream.write(b"Hello from TLS server!")
except ssl.SSLError as e:
print(f"SSL Error: {e}")
finally:
connstream.close()
print("Client disconnected")
def main():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind((HOST, PORT))
sock.listen(5)
print(f"TLS server listening on {HOST}:{PORT}")
with context.wrap_socket(sock, server_side=True) as ssock:
while True:
conn, addr = ssock.accept()
with context.wrap_socket(conn, server_side=True) as connstream:
handle_client(connstream)
if __name__ == "__main__":
# For demonstration purposes, you'd typically generate cert.pem and key.pem
# using OpenSSL:
# openssl req -new -x509 -days 365 -nodes -out server.crt -keyout server.key
# You'll need to create dummy server.crt and server.key files if they don't exist.
try:
with open(CERTFILE, 'r') as f: pass
with open(KEYFILE, 'r') as f: pass
except FileNotFoundError:
print("\n--- IMPORTANT ---")
print(f"To run this example, you need to generate TLS certificates.")
print(f"Use OpenSSL with commands like:")
print(f" openssl req -new -x509 -days 365 -nodes -out {CERTFILE} -keyout {KEYFILE}")
print("Then place the generated files in the same directory as this script.\n")
# Exit gracefully if certs are missing, as the server won't start.
import sys
sys.exit(1)
main()
tls_client.py
)A basic Python client connecting to the TLS server.
import socket
import ssl
# Configuration
HOST = 'localhost'
PORT = 8443
# For self-signed certificates, you might need to specify ca_certs
# or disable verification (not recommended for production).
# CA_CERTS = 'server.crt'
def main():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# context.load_verify_locations(cafile=CA_CERTS) # Uncomment if using CA verification
context.check_hostname = False # Disable hostname checking for localhost self-signed certs
context.verify_mode = ssl.CERT_NONE # Disable certificate verification for localhost self-signed certs
try:
with socket.create_connection((HOST, PORT)) as sock:
with context.wrap_socket(sock, server_hostname=HOST) as ssock:
print(f"Connected to {HOST}:{PORT} with TLS version {ssock.version()}")
ssock.sendall(b"Hello from TLS client!")
data = ssock.recv(1024)
print(f"Received: {data.decode()}")
except ConnectionRefusedError:
print(f"Connection refused. Ensure the server is running on {HOST}:{PORT}.")
except ssl.SSLError as e:
print(f"SSL Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
openssl req -new -x509 -days 365 -nodes -out server.crt -keyout server.key
You will be prompted for some information; you can press Enter to accept defaults for most fields, but provide a "Common Name" like localhost
.
tls_server.py
and the client code as tls_client.py
in the same directory as your server.crt
and server.key
files.
python tls_server.py
python tls_client.py