ssl — TLS/SSL wrapper for socket objects¶
Source code: Lib/ssl.py
This module provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. This module uses the OpenSSL library.
This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see Requirements for optional modules.
Note
Some behavior may be platform dependent, since calls are made to the operating system socket APIs. The installed version of OpenSSL may also cause variations in behavior. For example, TLSv1.3 comes with OpenSSL version 1.1.1.
Warning
Don’t use this module without reading the Security considerations. Doing so may lead to a false sense of security, as the default settings of the ssl module are not necessarily appropriate for your application.
Availability: not WASI.
This module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.
This section documents the objects and functions in the ssl module; for more
general information about TLS, SSL, and certificates, the reader is referred to
the documents in the “See Also” section at the bottom.
This module provides a class, ssl.SSLSocket, which is derived from the
socket.socket type, and provides a socket-like wrapper that also
encrypts and decrypts the data going over the socket with SSL. It supports
additional methods such as getpeercert(), which retrieves the
certificate of the other side of the connection, cipher(), which
retrieves the cipher being used for the secure connection or
get_verified_chain(), get_unverified_chain() which retrieves
certificate chain.
For more sophisticated applications, the ssl.SSLContext class
helps manage settings and certificates, which can then be inherited
by SSL sockets created through the SSLContext.wrap_socket() method.
Changed in version 3.5.3: Updated to support linking with OpenSSL 1.1.0
Changed in version 3.6: OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.
Changed in version 3.10: PEP 644 has been implemented. The ssl module requires OpenSSL 1.1.1 or newer.
Use of deprecated constants and functions result in deprecation warnings.
Functions, constants, and exceptions¶
Socket creation¶
Instances of SSLSocket must be created using the
SSLContext.wrap_socket() method. The helper function
create_default_context() returns a new context with secure default
settings.
Client socket example with default context and IPv4/IPv6 dual stack:
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
Client socket example with custom context and IPv4:
hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
Server socket example listening on localhost IPv4:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind(('127.0.0.1', 8443))
sock.listen(5)
with context.wrap_socket(sock, server_side=True) as ssock:
conn, addr = ssock.accept()
...
Context creation¶
A convenience function helps create SSLContext objects for common
purposes.
- ssl.create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None)¶
Return a new
SSLContextobject with default settings for the given purpose. The settings are chosen by thesslmodule, and usually represent a higher security level than when calling theSSLContextconstructor directly.cafile, capath, cadata represent optional CA certificates to trust for certificate verification, as in
SSLContext.load_verify_locations(). If all three areNone, this function can choose to trust the system’s default CA certificates instead.The settings are:
PROTOCOL_TLS_CLIENTorPROTOCOL_TLS_SERVER,OP_NO_SSLv2, andOP_NO_SSLv3with high encryption cipher suites without RC4 and without unauthenticated cipher suites. PassingSERVER_AUTHas purpose setsverify_modetoCERT_REQUIREDand either loads CA certificates (when at least one of cafile, capath or cadata is given) or usesSSLContext.load_default_certs()to load default CA certificates.When the environment variable
SSLKEYLOGFILEis set,create_default_context()enables key logging by settingkeylog_filenameto the variable’s value.The default settings for this context include
VERIFY_X509_PARTIAL_CHAINandVERIFY_X509_STRICT. These make the underlying OpenSSL implementation behave more like a conforming implementation of RFC 5280, in exchange for a small amount of incompatibility with older X.509 certificates.Note
The protocol, options, cipher and other settings may change to more restrictive values anytime without prior deprecation. The values represent a fair balance between compatibility and security.
If your application needs specific settings, you should create a
SSLContextand apply the settings yourself.Note
If you find that when certain older clients or servers attempt to connect with a
SSLContextcreated by this function that they get an error stating “Protocol or cipher suite mismatch”, it may be that they only support SSL3.0 which this function excludes using theOP_NO_SSLv3. SSL3.0 is widely considered to be completely broken. If you still wish to continue to use this function but still allow SSL 3.0 connections you can re-enable them using:ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) ctx.options &= ~ssl.OP_NO_SSLv3
Note
This context enables
VERIFY_X509_STRICTby default, which may reject pre-RFC 5280 or malformed certificates that the underlying OpenSSL implementation otherwise would accept. While disabling this is not recommended, you can do so using:ctx = ssl.create_default_context() ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT
Added in version 3.4.
Changed in version 3.4.4: RC4 was dropped from the default cipher string.
Changed in version 3.6: ChaCha20/Poly1305 was added to the default cipher string.
3DES was dropped from the default cipher string.
Changed in version 3.8: Support for key logging to
SSLKEYLOGFILEwas added.Changed in version 3.10: The context now uses
PROTOCOL_TLS_CLIENTorPROTOCOL_TLS_SERVERprotocol instead of genericPROTOCOL_TLS.Changed in version 3.13: The context now uses
VERIFY_X509_PARTIAL_CHAINandVERIFY_X509_STRICTin its default verify flags.
Signature algorithms¶
- ssl.get_sigalgs()¶
Return a list of available TLS signature algorithm names used by servers to complete the TLS handshake or clients requesting certificate-based authentication. For example:
>>> ssl.get_sigalgs() ['ecdsa_secp256r1_sha256', 'ecdsa_secp384r1_sha384', ...]
These names can be used when building string values to pass to the
SSLContext.set_client_sigalgs()andSSLContext.set_server_sigalgs()methods.Added in version 3.15.
Exceptions¶
- exception ssl.SSLError¶
Raised to signal an error from the underlying SSL implementation (currently provided by the OpenSSL library). This signifies some problem in the higher-level encryption and authentication layer that’s superimposed on the underlying network connection. This error is a subtype of
OSError. The error code and message ofSSLErrorinstances are provided by the OpenSSL library.Changed in version 3.3:
SSLErrorused to be a subtype ofsocket.error.- library