Skip to content

Lesson 5 of 9 · 25m

TLS in Python: Certificates, Contexts, and Verification

TLS is authentication plus encryption, not just an https prefix — configure SSLContext deliberately and understand the failures operators actually see.

A service can encrypt traffic perfectly and still be insecure because it never verified who was on the other end. TLS exists to solve both problems: authenticate one or both peers, then negotiate encryption keys for the session. Python's ssl module exposes this through SSLContext; treat the context as security policy, not ceremony.

Clients verify servers by default

import socket, ssl

ctx = ssl.create_default_context()
with socket.create_connection(("www.python.org", 443), timeout=5) as raw:
    with ctx.wrap_socket(raw, server_hostname="www.python.org") as tls:
        print(tls.version(), tls.cipher())

create_default_context() loads trust roots, requires certificate verification, and checks hostnames. server_hostname is not optional decoration: it drives SNI so the server can select the right certificate and tells the verifier which hostname must appear in that certificate.

Servers present a certificate chain

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("/etc/ssl/site/fullchain.pem", "/etc/ssl/site/privkey.pem")
ctx.minimum_version = ssl.TLSVersion.TLSv1_2

with socket.socket() as listener:
    listener.bind(("0.0.0.0", 8443))
    listener.listen(128)
    conn, addr = listener.accept()
    tls_conn = ctx.wrap_socket(conn, server_side=True)

Use the full chain file, not only the leaf certificate. A missing intermediate often works in browsers because they cache or fetch intermediates, then fails in Python clients with CERTIFICATE_VERIFY_FAILED. That is a server deployment bug.

TLS errors have meanings

  • certificate verify failed: unable to get local issuer certificate — missing or incomplete chain/trust root.
  • Hostname mismatch — certificate names do not match the DNS name used by the client.
  • certificate has expired — clock skew or actual expiry; check both.
  • WRONG_VERSION_NUMBER — often plaintext HTTP spoken to a TLS port, or TLS spoken to plaintext.
  • TLS handshake timeout — middlebox, firewall, or a listener accepting TCP but never replying.

Mutual TLS authenticates clients too

For internal service-to-service traffic, configure ctx.verify_mode = ssl.CERT_REQUIRED on the server and load a CA that signs client certificates. Clients call load_cert_chain with their own keypair. mTLS moves authentication into the transport, but revocation, rotation, and identity naming become operational work. Do not adopt it because it sounds enterprise; adopt it because you need strong machine identity.

Do not disable verification

check_hostname = False and verify_mode = ssl.CERT_NONE are acceptable only in controlled diagnostics. In production they turn TLS into encryption against a passive listener while allowing an active network attacker to impersonate the service. Self-signed certificates can be used safely by pinning or distributing the exact CA — not by disabling verification globally.

Field notes

  • Inspect certificates with openssl s_client -connect host:443 -servername host -showcerts.
  • Rotate keys before expiry and test renewal using the same client library production uses.
  • Prefer TLS 1.2 minimum; require 1.3 when clients support it.
  • Certificate validity is time-sensitive. Monitor system clocks, especially containers and VMs.
  • Never log private keys or full decrypted payloads in debug output.

Was this lesson helpful?

Sign in to rate