Concept Explanation
Everything you sent in the last lesson travelled in plain text. Anyone between your machine and the server — the coffee shop router, the ISP, a compromised switch — could read your headers, your tokens, and your data, and could alter them in flight.
TLS (Transport Layer Security, the successor to SSL) fixes three separate problems at once, and it is worth naming them separately because people conflate them:
| Guarantee | Question it answers | Provided by |
|---|---|---|
| Confidentiality | Can anyone read this? | Encryption |
| Integrity | Was it modified in transit? | Message authentication codes |
| Authenticity | Am I talking to who I think? | Certificates |
Encryption alone is nearly worthless. An encrypted channel to an attacker impersonating your bank is exactly as bad as no encryption. The certificate is the part that makes TLS meaningful, and it is the part people disable when they hit an error.
How Certificate Verification Works
- The server presents a certificate: its domain name, its public key, and a signature.
- The signature comes from a Certificate Authority (CA) your system already trusts.
- Your client checks: is the signature valid, has the certificate expired, and does the name on it match the host I asked for?
- Any failure aborts the connection before a single byte of your data is sent.
That third check is what stops a valid-but-wrong certificate from working. This is why https://1.2.3.4 usually fails even when the site is fine — the certificate names a domain, not an IP.
Python's Defaults Are Correct
import requests
requests.get("https://example.com") # verifies the certificate. Full stop.
Since Python 3.6, ssl.create_default_context() verifies certificates and checks hostnames by default. Do not turn this off. The two lines below are the most dangerous snippet in Python networking, and they appear in thousands of Stack Overflow answers:
requests.get(url, verify=False) # NO
ssl._create_default_https_context = ssl._create_unverified_context # NEVER
Both convert "HTTPS" into "HTTP with extra steps and a false sense of safety."
What to Do Instead When Verification Fails
| Error | Real cause | Correct fix |
|---|---|---|
CERTIFICATE_VERIFY_FAILED: unable to get local issuer | Missing CA bundle | pip install --upgrade certifi; on macOS run Install Certificates.command |
certificate has expired | Server's cert lapsed | Tell the server's owner |
hostname mismatch | Wrong domain, or connecting by IP | Use the name on the certificate |
self-signed certificate | Corporate proxy or internal service | Pass that CA explicitly: verify="/path/corp-ca.pem" |
The last row is the one that matters in practice. Corporate networks intercept TLS with their own CA. The fix is to trust that specific CA, not to trust everything.
Code Example #1 (Basic)
Inspecting the certificate a server presents.
import socket
import ssl
from datetime import datetime, timezone
host, port = "example.com", 443
context = ssl.create_default_context() # verifies certs + hostname by default
with socket.create_connection((host, port), timeout=10) as raw:
with context.wrap_socket(raw, server_hostname=host) as tls:
print("Protocol:", tls.version()) # expect TLSv1.3
print("Cipher: ", tls.cipher()[0])
cert = tls.getpeercert()
subject = dict(x[0] for x in cert["subject"])
issuer = dict(x[0] for x in cert["issuer"])
print("Issued to:", subject.get("commonName"))
print("Issued by:", issuer.get("organizationName"))
expires = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
expires = expires.replace(tzinfo=timezone.utc)
days_left = (expires - datetime.now(timezone.utc)).days
print(f"Expires: {expires:%Y-%m-%d} ({days_left} days left)")
names = [v for k, v in cert.get("subjectAltName", []) if k == "DNS"]
print("Valid for:", ", ".join(names[:5]))
server_hostname=host is not optional. It does two jobs: it sends SNI so a shared server knows which certificate to present, and it enables the hostname check. Omit it and you have encryption without authenticity.
Code Example #2 (Intermediate)
A certificate-expiry monitor — a genuinely useful ops script.
import socket
import ssl
from datetime import datetime, timezone
WARN_DAYS = 30
def check_certificate(host, port=443, timeout=8):
"""Return (status, detail) for one host's TLS certificate."""
context = ssl.create_default_context()
try:
with socket.create_connection((host, port), timeout=timeout) as raw:
with context.wrap_socket(raw, server_hostname=host) as tls:
cert = tls.getpeercert()
proto = tls.version()
except ssl.SSLCertVerificationError as err:
return "INVALID", err.verify_message or str(err)
except (socket.timeout, socket.gaierror, ConnectionRefusedError) as err:
return "UNREACHABLE", str(err)
expires = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
expires = expires.replace(tzinfo=timezone.utc)
days = (expires - datetime.now(timezone.utc)).days
if days < 0:
return "EXPIRED", f"lapsed {abs(days)} days ago"
if days < WARN_DAYS:
return "EXPIRING", f"{days} days left ({proto})"
return "OK", f"{days} days left ({proto})"
HOSTS = ["example.com", "python.org", "expired.badssl.com", "wrong.host.badssl.com"]
width = max(len(h) for h in HOSTS)
for host in HOSTS:
status, detail = check_certificate(host)
print(f"{host:<{width}} {status:<12} {detail}")
The two badssl.com hosts exist precisely so you can watch verification fail correctly. Run this and see INVALID for both — that is TLS protecting you, not TLS being broken.
Common Mistakes
verify=Falseto "fix" an error: it does not fix anything. It disables the only check that makes HTTPS worth using, and it hides the real problem — usually a stale CA bundle you could have updated in ten seconds.- Omitting
server_hostnameinwrap_socket: no hostname verification, and no SNI, so shared hosts hand you the wrong certificate. - Using
ssl.wrap_socket(): removed in Python 3.12, and it never verified anything. UseSSLContext.wrap_socket. - Suppressing the InsecureRequestWarning:
urllib3.disable_warnings()silences the alarm without addressing the fire. - Confusing encryption with authentication: an encrypted tunnel to the wrong server is a successful attack, not a secure connection.
- Hardcoding a certificate path: use
certifi.where(), which is kept up to date bypip. - Forgetting certificates expire: they now last 90 days or less. An unmonitored certificate is a scheduled outage.
- *Assuming HTTPS makes the application secure*: TLS protects the channel. It does nothing about SQL injection, weak passwords, or a token you wrote into a log file.
Best Practices
- Keep the defaults:
ssl.create_default_context()andrequests' built-in verification are already correct. Every change you make to them is a downgrade unless you can explain otherwise. - Update
certifiregularly:pip install --upgrade certifiresolves most "unable to get local issuer" reports. - Trust a specific CA rather than all of them:
verify="/etc/ssl/corp-ca.pem"for an internal service; neververify=False. - Require TLS 1.2 as a floor:
context.minimum_version = ssl.TLSVersion.TLSv1_2. TLS 1.0 and 1.1 are deprecated and broken. - Monitor expiry automatically: run the script above on a schedule and alert 30 days out.
- Use HTTPS even internally: "it's on the private network" has been an insufficient defence for a decade.
- Test against
badssl.com: it offers expired, self-signed, and wrong-host endpoints so you can prove your client rejects them. - Never log the decrypted body of an authenticated request: TLS protects the wire, not your log files.
Practice Exercises
- The Certificate Reader: Print the issuer, expiry date, and all
subjectAltNameentries for three sites you use daily. Note how many distinct domains one certificate covers. - The Failure Tour: Connect to
expired.badssl.com,self-signed.badssl.com, andwrong.host.badssl.com, catchingssl.SSLCertVerificationErrorand printing the specific reason for each. Then re-run one of them withverify=Falseand write a comment explaining precisely what protection you just gave up. - The Expiry Alarm: Extend the monitor to read hostnames from a text file, exit with a non-zero status code if any certificate has under 30 days left, and print a summary table. That exit code is what makes it usable from cron or CI.