On this page
  1. ssl
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Wrapping a Client TCP Socket with Verified TLS & SNI
  7. 2. Loading a Custom CA Bundle or Mutual TLS (mTLS) Client Cert
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

ssl

Prev: sre_parse | Up: stdlib_module | Next: stat
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — ssl
Tags: #public #python3 #stdlib


Import

import ssl

Overview

TLS/SSL encryption, certificate verification, and hostname checking over socket connections via OpenSSL (SSLContext, create_default_context). Always start from ssl.create_default_context() so modern TLS versions, strong ciphers, certificate chain validation, and hostname verification are enabled by default.

Quick Start

import ssl

ctx = ssl.create_default_context()
assert ctx.check_hostname is True
assert ctx.verify_mode == ssl.CERT_REQUIRED
assert ctx.minimum_version >= ssl.TLSVersion.TLSv1_2

Implementation Walkthrough

1. Wrapping a Client TCP Socket with Verified TLS & SNI

Always pass server_hostname= to wrap_socket()—it enables both SNI (Server Name Indication) and certificate hostname matching:

import socket
import ssl

def tls_connect(host: str, port: int = 443, *, timeout: float = 10.0) -> dict[str, object]:
    ctx = ssl.create_default_context()
    with socket.create_connection((host, port), timeout=timeout) as raw:
        with ctx.wrap_socket(raw, server_hostname=host) as tls_sock:
            return {
                "version": tls_sock.version(),
                "cipher": tls_sock.cipher(),
                "peer": tls_sock.getpeercert(),
            }

2. Loading a Custom CA Bundle or Mutual TLS (mTLS) Client Cert

import ssl

ctx = ssl.create_default_context(cafile="/path/to/internal-ca.pem")
# For mTLS client authentication:
# ctx.load_cert_chain(certfile="/path/to/client.crt", keyfile="/path/to/client.key")

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes