On this page
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
- Never disable verification (
CERT_NONE/check_hostname = False) in production: Doing so silently exposes connections to trivial man-in-the-middle attacks. - Always pass
server_hostname=on clientwrap_socket(): Required for SNI on virtual-hosted HTTPS servers and hostname verification. - Set
ctx.minimum_version = ssl.TLSVersion.TLSv1_2(orTLSv1_3) explicitly if hardening a server context (ssl.Purpose.CLIENT_AUTH). - Use
ssl.create_default_context()instead of deprecatedssl.wrap_socket()(removed in Python 3.12).
Common Functions
- ssl.cert_time_to_seconds() —
cert_time_to_seconds(cert_time)— Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in"%b %d %H:%M:%S %Y %Z"strptime format (C locale). - ssl.create_connection() —
create_connection(address, timeout=<object object at 0x1040b4980>, source_address=None, *, all_errors=False)— Connect to address and return the socket object. - ssl.create_default_context() —
create_default_context(purpose=<Purpose.SERVER_AUTH: _ASN1Object(nid=129, shortname='serverAuth', longname='TLS Web Server Authentication', oid='1.3.6.1.5.5.7.3.1')>, *, cafile=None, capath=None, cadata=None)— Create a SSLContext object with default settings. - ssl.DER_cert_to_PEM_cert() —
DER_cert_to_PEM_cert(der_cert_bytes)— Takes a certificate in binary DER format and returns the PEM version of it as a string. - ssl.get_default_verify_paths() —
get_default_verify_paths()— Return paths to default cafile and capath. - ssl.get_protocol_name() —
get_protocol_name(protocol_code)—ssl.get_protocol_name()function. - ssl.get_server_certificate() —
get_server_certificate(addr, ssl_version=<_SSLMethod.PROTOCOL_TLS_CLIENT: 16>, ca_certs=None, timeout=<object object at 0x1040b4980>)— Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. - ssl.namedtuple() —
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)— Returns a new subclass of tuple with named fields. - ssl.PEM_cert_to_DER_cert() —
PEM_cert_to_DER_cert(pem_cert_string)— Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence - ssl.RAND_add() —
RAND_add(string, entropy, /)— Mix string into the OpenSSL PRNG state. - ssl.RAND_bytes() —
RAND_bytes(n, /)— Generate n cryptographically strong pseudo-random bytes. - ssl.RAND_status() —
RAND_status()— Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
Classes & Objects
- ssl.AlertDescription — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - ssl.CertificateError — A certificate could not be verified. (Methods:
.add_note(),.with_traceback()) - ssl.DefaultVerifyPaths — DefaultVerifyPaths(cafile, capath, openssl_cafile_env, openssl_cafile, openssl_capath_env, openssl_capath) (Methods:
.count(),.index()) - ssl.MemoryBIO —
ssl.MemoryBIOclass. (Methods:.read(),.write(),.write_eof()) - ssl.Options — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - ssl.Purpose — SSLContext purpose flags with X509v3 Extended Key Usage objects (Methods:
.count(),.fromname(),.fromnid(),.index()) - ssl.socket — A subclass of _socket.socket adding the makefile() method. (Methods:
.accept(),.bind(),.close(),.connect(),.connect_ex(),.detach()) - ssl.socket_error — Base class for I/O related errors. (Methods:
.add_note(),.with_traceback()) - ssl.SSLCertVerificationError — A certificate could not be verified. (Methods:
.add_note(),.with_traceback()) - ssl.SSLContext — An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key. (Methods:
.cert_store_stats(),.get_ca_certs(),.get_ciphers(),.hostname_checks_common_name(),.load_cert_chain(),.load_default_certs()) - ssl.SSLEOFError — SSL/TLS connection terminated abruptly. (Methods:
.add_note(),.with_traceback()) - ssl.SSLError — An error occurred in the SSL implementation. (Methods:
.add_note(),.with_traceback()) - ssl.SSLErrorNumber — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - ssl.SSLObject — This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed (Methods:
.cipher(),.compression(),.context(),.do_handshake(),.get_channel_binding(),.get_unverified_chain()) - ssl.SSLSession —
ssl.SSLSessionclass. - ssl.SSLSocket — This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel. (Methods:
.accept(),.bind(),.cipher(),.close(),.compression(),.connect()) - ssl.SSLSyscallError — System error when attempting SSL operation. (Methods:
.add_note(),.with_traceback()) - ssl.SSLWantReadError — Non-blocking SSL socket needs to read more data before the requested operation can be completed. (Methods:
.add_note(),.with_traceback()) - ssl.SSLWantWriteError — Non-blocking SSL socket needs to write more data before the requested operation can be completed. (Methods:
.add_note(),.with_traceback()) - ssl.SSLZeroReturnError — SSL/TLS session closed cleanly. (Methods:
.add_note(),.with_traceback())
Constants & Attributes
ssl.ALERT_DESCRIPTION_ACCESS_DENIED(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_ACCESS_DENIED: 49>ssl.ALERT_DESCRIPTION_BAD_CERTIFICATE(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE: 42>ssl.ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_...ssl.ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_STATU...ssl.ALERT_DESCRIPTION_BAD_RECORD_MAC(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_BAD_RECORD_MAC: 20>ssl.ALERT_DESCRIPTION_CERTIFICATE_EXPIRED(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: 45>ssl.ALERT_DESCRIPTION_CERTIFICATE_REVOKED(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_REVOKED: 44>ssl.ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: 46>ssl.ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINA...ssl.ALERT_DESCRIPTION_CLOSE_NOTIFY(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_CLOSE_NOTIFY: 0>ssl.ALERT_DESCRIPTION_DECODE_ERROR(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_DECODE_ERROR: 50>ssl.ALERT_DESCRIPTION_DECOMPRESSION_FAILURE(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_DECOMPRESSION_FAILURE...ssl.ALERT_DESCRIPTION_DECRYPT_ERROR(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_DECRYPT_ERROR: 51>ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_HANDSHAKE_FAILURE: 40>ssl.ALERT_DESCRIPTION_ILLEGAL_PARAMETER(AlertDescription) =<AlertDescription.ALERT_DESCRIPTION_ILLEGAL_PARAMETER: 47>
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/sre_parse
- tuts/python3/stdlib_module/ssl/AlertDescription
- tuts/python3/stdlib_module/ssl/cert_time_to_seconds
- tuts/python3/stdlib_module/ssl/CertificateError
- tuts/python3/stdlib_module/ssl/create_connection
- tuts/python3/stdlib_module/ssl/create_default_context
- tuts/python3/stdlib_module/ssl/DefaultVerifyPaths
- tuts/python3/stdlib_module/ssl/DER_cert_to_PEM_cert
- tuts/python3/stdlib_module/ssl/get_default_verify_paths
- tuts/python3/stdlib_module/ssl/get_protocol_name
- tuts/python3/stdlib_module/ssl/get_server_certificate
- tuts/python3/stdlib_module/ssl/MemoryBIO
- tuts/python3/stdlib_module/ssl/namedtuple
- tuts/python3/stdlib_module/ssl/Options
- tuts/python3/stdlib_module/ssl/PEM_cert_to_DER_cert
- tuts/python3/stdlib_module/ssl/Purpose
- tuts/python3/stdlib_module/ssl/RAND_add
- tuts/python3/stdlib_module/ssl/RAND_bytes
- tuts/python3/stdlib_module/ssl/RAND_status
- tuts/python3/stdlib_module/ssl/socket
- tuts/python3/stdlib_module/ssl/socket_error
- tuts/python3/stdlib_module/ssl/SSLCertVerificationError
- tuts/python3/stdlib_module/ssl/SSLContext
- tuts/python3/stdlib_module/ssl/SSLEOFError
- tuts/python3/stdlib_module/ssl/SSLError
- tuts/python3/stdlib_module/ssl/SSLErrorNumber
- tuts/python3/stdlib_module/ssl/SSLObject
- tuts/python3/stdlib_module/ssl/SSLSession
- tuts/python3/stdlib_module/ssl/SSLSocket
- tuts/python3/stdlib_module/ssl/SSLSyscallError
- tuts/python3/stdlib_module/ssl/SSLWantReadError
- tuts/python3/stdlib_module/ssl/SSLWantWriteError
- tuts/python3/stdlib_module/ssl/SSLZeroReturnError
- tuts/python3/stdlib_module/stat
- tuts/python3/stdlib_module/stdlib_module
Related notes
- tuts/python3/stdlib_module/socket Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sre_parse Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/AlertDescription Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/cert_time_to_seconds Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/CertificateError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/create_connection Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/create_default_context Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/DefaultVerifyPaths Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/DER_cert_to_PEM_cert Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ssl/get_default_verify_paths Linked here; links to this page; shared tags: #stdlib