doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
ssl.HAS_NPN Whether the OpenSSL library has built-in support for the Next Protocol Negotiation as described in the Application Layer Protocol Negotiation. When true, you can use the SSLContext.set_npn_protocols() method to advertise which protocols you want to support. New in version 3.3.
python.library.ssl#ssl.HAS_NPN
ssl.HAS_SNI Whether the OpenSSL library has built-in support for the Server Name Indication extension (as defined in RFC 6066). New in version 3.2.
python.library.ssl#ssl.HAS_SNI
ssl.HAS_SSLv2 Whether the OpenSSL library has built-in support for the SSL 2.0 protocol. New in version 3.7.
python.library.ssl#ssl.HAS_SSLv2
ssl.HAS_SSLv3 Whether the OpenSSL library has built-in support for the SSL 3.0 protocol. New in version 3.7.
python.library.ssl#ssl.HAS_SSLv3
ssl.HAS_TLSv1 Whether the OpenSSL library has built-in support for the TLS 1.0 protocol. New in version 3.7.
python.library.ssl#ssl.HAS_TLSv1
ssl.HAS_TLSv1_1 Whether the OpenSSL library has built-in support for the TLS 1.1 protocol. New in version 3.7.
python.library.ssl#ssl.HAS_TLSv1_1
ssl.HAS_TLSv1_2 Whether the OpenSSL library has built-in support for the TLS 1.2 protocol. New in version 3.7.
python.library.ssl#ssl.HAS_TLSv1_2
ssl.HAS_TLSv1_3 Whether the OpenSSL library has built-in support for the TLS 1.3 protocol. New in version 3.7.
python.library.ssl#ssl.HAS_TLSv1_3
ssl.match_hostname(cert, hostname) Verify that cert (in decoded format as returned by SSLSocket.getpeercert()) matches the given hostname. The rules applied are those for checking the identity of HTTPS servers as outlined in RFC 2818, RFC 5280 and RFC 6125. In addition to HTTPS, this function should be suitable for checking the identity of servers in various SSL-based protocols such as FTPS, IMAPS, POPS and others. CertificateError is raised on failure. On success, the function returns nothing: >>> cert = {'subject': ((('commonName', 'example.com'),),)} >>> ssl.match_hostname(cert, "example.com") >>> ssl.match_hostname(cert, "example.org") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/py3k/Lib/ssl.py", line 130, in match_hostname ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' New in version 3.2. Changed in version 3.3.3: The function now follows RFC 6125, section 6.4.3 and does neither match multiple wildcards (e.g. *.*.com or *a*.example.org) nor a wildcard inside an internationalized domain names (IDN) fragment. IDN A-labels such as www*.xn--pthon-kva.org are still supported, but x*.python.org no longer matches xn--tda.python.org. Changed in version 3.5: Matching of IP addresses, when present in the subjectAltName field of the certificate, is now supported. Changed in version 3.7: The function is no longer used to TLS connections. Hostname matching is now performed by OpenSSL. Allow wildcard when it is the leftmost and the only character in that segment. Partial wildcards like www*.example.com are no longer supported. Deprecated since version 3.7.
python.library.ssl#ssl.match_hostname
class ssl.MemoryBIO A memory buffer that can be used to pass data between Python and an SSL protocol instance. pending Return the number of bytes currently in the memory buffer. eof A boolean indicating whether the memory BIO is current at the end-of-file position. read(n=-1) Read up to n bytes from the memory buffer. If n is not specified or negative, all bytes are returned. write(buf) Write the bytes from buf to the memory BIO. The buf argument must be an object supporting the buffer protocol. The return value is the number of bytes written, which is always equal to the length of buf. write_eof() Write an EOF marker to the memory BIO. After this method has been called, it is illegal to call write(). The attribute eof will become true after all data currently in the buffer has been read.
python.library.ssl#ssl.MemoryBIO
eof A boolean indicating whether the memory BIO is current at the end-of-file position.
python.library.ssl#ssl.MemoryBIO.eof
pending Return the number of bytes currently in the memory buffer.
python.library.ssl#ssl.MemoryBIO.pending
read(n=-1) Read up to n bytes from the memory buffer. If n is not specified or negative, all bytes are returned.
python.library.ssl#ssl.MemoryBIO.read
write(buf) Write the bytes from buf to the memory BIO. The buf argument must be an object supporting the buffer protocol. The return value is the number of bytes written, which is always equal to the length of buf.
python.library.ssl#ssl.MemoryBIO.write
write_eof() Write an EOF marker to the memory BIO. After this method has been called, it is illegal to call write(). The attribute eof will become true after all data currently in the buffer has been read.
python.library.ssl#ssl.MemoryBIO.write_eof
ssl.OPENSSL_VERSION The version string of the OpenSSL library loaded by the interpreter: >>> ssl.OPENSSL_VERSION 'OpenSSL 1.0.2k 26 Jan 2017' New in version 3.2.
python.library.ssl#ssl.OPENSSL_VERSION
ssl.OPENSSL_VERSION_INFO A tuple of five integers representing version information about the OpenSSL library: >>> ssl.OPENSSL_VERSION_INFO (1, 0, 2, 11, 15) New in version 3.2.
python.library.ssl#ssl.OPENSSL_VERSION_INFO
ssl.OPENSSL_VERSION_NUMBER The raw version number of the OpenSSL library, as a single integer: >>> ssl.OPENSSL_VERSION_NUMBER 268443839 >>> hex(ssl.OPENSSL_VERSION_NUMBER) '0x100020bf' New in version 3.2.
python.library.ssl#ssl.OPENSSL_VERSION_NUMBER
class ssl.Options enum.IntFlag collection of OP_* constants.
python.library.ssl#ssl.Options
ssl.OP_ALL Enables workarounds for various bugs present in other SSL implementations. This option is set by default. It does not necessarily set the same flags as OpenSSL’s SSL_OP_ALL constant. New in version 3.2.
python.library.ssl#ssl.OP_ALL
ssl.OP_CIPHER_SERVER_PREFERENCE Use the server’s cipher ordering preference, rather than the client’s. This option has no effect on client sockets and SSLv2 server sockets. New in version 3.3.
python.library.ssl#ssl.OP_CIPHER_SERVER_PREFERENCE
ssl.OP_ENABLE_MIDDLEBOX_COMPAT Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make a TLS 1.3 connection look more like a TLS 1.2 connection. This option is only available with OpenSSL 1.1.1 and later. New in version 3.8.
python.library.ssl#ssl.OP_ENABLE_MIDDLEBOX_COMPAT
ssl.OP_IGNORE_UNEXPECTED_EOF Ignore unexpected shutdown of TLS connections. This option is only available with OpenSSL 3.0.0 and later. New in version 3.10.
python.library.ssl#ssl.OP_IGNORE_UNEXPECTED_EOF
ssl.OP_NO_COMPRESSION Disable compression on the SSL channel. This is useful if the application protocol supports its own compression scheme. This option is only available with OpenSSL 1.0.0 and later. New in version 3.3.
python.library.ssl#ssl.OP_NO_COMPRESSION
ssl.OP_NO_RENEGOTIATION Disable all renegotiation in TLSv1.2 and earlier. Do not send HelloRequest messages, and ignore renegotiation requests via ClientHello. This option is only available with OpenSSL 1.1.0h and later. New in version 3.7.
python.library.ssl#ssl.OP_NO_RENEGOTIATION
ssl.OP_NO_SSLv2 Prevents an SSLv2 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv2 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv2 is deprecated
python.library.ssl#ssl.OP_NO_SSLv2
ssl.OP_NO_SSLv3 Prevents an SSLv3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv3 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv3 is deprecated
python.library.ssl#ssl.OP_NO_SSLv3
ssl.OP_NO_TICKET Prevent client side from requesting a session ticket. New in version 3.6.
python.library.ssl#ssl.OP_NO_TICKET
ssl.OP_NO_TLSv1 Prevents a TLSv1 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1 as the protocol version. New in version 3.2. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0, use the new SSLContext.minimum_version and SSLContext.maximum_version instead.
python.library.ssl#ssl.OP_NO_TLSv1
ssl.OP_NO_TLSv1_1 Prevents a TLSv1.1 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.1 as the protocol version. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0.
python.library.ssl#ssl.OP_NO_TLSv1_1
ssl.OP_NO_TLSv1_2 Prevents a TLSv1.2 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.2 as the protocol version. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0.
python.library.ssl#ssl.OP_NO_TLSv1_2
ssl.OP_NO_TLSv1_3 Prevents a TLSv1.3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.3 as the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. When Python has been compiled against an older version of OpenSSL, the flag defaults to 0. New in version 3.7. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15, 3.6.3 and 3.7.0 for backwards compatibility with OpenSSL 1.0.2.
python.library.ssl#ssl.OP_NO_TLSv1_3
ssl.OP_SINGLE_DH_USE Prevents re-use of the same DH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets. New in version 3.3.
python.library.ssl#ssl.OP_SINGLE_DH_USE
ssl.OP_SINGLE_ECDH_USE Prevents re-use of the same ECDH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets. New in version 3.3.
python.library.ssl#ssl.OP_SINGLE_ECDH_USE
ssl.PEM_cert_to_DER_cert(PEM_cert_string) Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of bytes for that same certificate.
python.library.ssl#ssl.PEM_cert_to_DER_cert
ssl.PROTOCOL_SSLv2 Selects SSL version 2 as the channel encryption protocol. This protocol is not available if OpenSSL is compiled with the OPENSSL_NO_SSL2 flag. Warning SSL version 2 is insecure. Its use is highly discouraged. Deprecated since version 3.6: OpenSSL has removed support for SSLv2.
python.library.ssl#ssl.PROTOCOL_SSLv2
ssl.PROTOCOL_SSLv23 Alias for PROTOCOL_TLS. Deprecated since version 3.6: Use PROTOCOL_TLS instead.
python.library.ssl#ssl.PROTOCOL_SSLv23
ssl.PROTOCOL_SSLv3 Selects SSL version 3 as the channel encryption protocol. This protocol is not be available if OpenSSL is compiled with the OPENSSL_NO_SSLv3 flag. Warning SSL version 3 is insecure. Its use is highly discouraged. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead.
python.library.ssl#ssl.PROTOCOL_SSLv3
ssl.PROTOCOL_TLS Selects the highest protocol version that both the client and server support. Despite the name, this option can select both “SSL” and “TLS” protocols. New in version 3.6.
python.library.ssl#ssl.PROTOCOL_TLS
ssl.PROTOCOL_TLSv1 Selects TLS version 1.0 as the channel encryption protocol. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead.
python.library.ssl#ssl.PROTOCOL_TLSv1
ssl.PROTOCOL_TLSv1_1 Selects TLS version 1.1 as the channel encryption protocol. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead.
python.library.ssl#ssl.PROTOCOL_TLSv1_1
ssl.PROTOCOL_TLSv1_2 Selects TLS version 1.2 as the channel encryption protocol. This is the most modern version, and probably the best choice for maximum protection, if both sides can speak it. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead.
python.library.ssl#ssl.PROTOCOL_TLSv1_2
ssl.PROTOCOL_TLS_CLIENT Auto-negotiate the highest protocol version like PROTOCOL_TLS, but only support client-side SSLSocket connections. The protocol enables CERT_REQUIRED and check_hostname by default. New in version 3.6.
python.library.ssl#ssl.PROTOCOL_TLS_CLIENT
ssl.PROTOCOL_TLS_SERVER Auto-negotiate the highest protocol version like PROTOCOL_TLS, but only support server-side SSLSocket connections. New in version 3.6.
python.library.ssl#ssl.PROTOCOL_TLS_SERVER
Purpose.CLIENT_AUTH Option for create_default_context() and SSLContext.load_default_certs(). This value indicates that the context may be used to authenticate Web clients (therefore, it will be used to create server-side sockets). New in version 3.4.
python.library.ssl#ssl.Purpose.CLIENT_AUTH
Purpose.SERVER_AUTH Option for create_default_context() and SSLContext.load_default_certs(). This value indicates that the context may be used to authenticate Web servers (therefore, it will be used to create client-side sockets). New in version 3.4.
python.library.ssl#ssl.Purpose.SERVER_AUTH
ssl.RAND_add(bytes, entropy) Mix the given bytes into the SSL pseudo-random number generator. The parameter entropy (a float) is a lower bound on the entropy contained in string (so you can always use 0.0). See RFC 1750 for more information on sources of entropy. Changed in version 3.5: Writable bytes-like object is now accepted.
python.library.ssl#ssl.RAND_add
ssl.RAND_bytes(num) Return num cryptographically strong pseudo-random bytes. Raises an SSLError if the PRNG has not been seeded with enough data or if the operation is not supported by the current RAND method. RAND_status() can be used to check the status of the PRNG and RAND_add() can be used to seed the PRNG. For almost all applications os.urandom() is preferable. Read the Wikipedia article, Cryptographically secure pseudorandom number generator (CSPRNG), to get the requirements of a cryptographically strong generator. New in version 3.3.
python.library.ssl#ssl.RAND_bytes
ssl.RAND_egd(path) If you are running an entropy-gathering daemon (EGD) somewhere, and path is the pathname of a socket connection open to it, this will read 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator to increase the security of generated secret keys. This is typically only necessary on systems without better sources of randomness. See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources of entropy-gathering daemons. Availability: not available with LibreSSL and OpenSSL > 1.1.0.
python.library.ssl#ssl.RAND_egd
ssl.RAND_pseudo_bytes(num) Return (bytes, is_cryptographic): bytes are num pseudo-random bytes, is_cryptographic is True if the bytes generated are cryptographically strong. Raises an SSLError if the operation is not supported by the current RAND method. Generated pseudo-random byte sequences will be unique if they are of sufficient length, but are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc. For almost all applications os.urandom() is preferable. New in version 3.3. Deprecated since version 3.6: OpenSSL has deprecated ssl.RAND_pseudo_bytes(), use ssl.RAND_bytes() instead.
python.library.ssl#ssl.RAND_pseudo_bytes
ssl.RAND_status() Return True if the SSL pseudo-random number generator has been seeded with ‘enough’ randomness, and False otherwise. You can use ssl.RAND_egd() and ssl.RAND_add() to increase the randomness of the pseudo-random number generator.
python.library.ssl#ssl.RAND_status
exception ssl.SSLCertVerificationError A subclass of SSLError raised when certificate validation has failed. New in version 3.7. verify_code A numeric error number that denotes the verification error. verify_message A human readable string of the verification error.
python.library.ssl#ssl.SSLCertVerificationError
verify_code A numeric error number that denotes the verification error.
python.library.ssl#ssl.SSLCertVerificationError.verify_code
verify_message A human readable string of the verification error.
python.library.ssl#ssl.SSLCertVerificationError.verify_message
class ssl.SSLContext(protocol=PROTOCOL_TLS) Create a new SSL context. You may pass protocol which must be one of the PROTOCOL_* constants defined in this module. The parameter specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server’s choice. Most of the versions are not interoperable with the other versions. If not specified, the default is PROTOCOL_TLS; it provides the most compatibility with other versions. Here’s a table showing which versions in a client (down the side) can connect to which versions in a server (along the top): client / server SSLv2 SSLv3 TLS 3 TLSv1 TLSv1.1 TLSv1.2 SSLv2 yes no no 1 no no no SSLv3 no yes no 2 no no no TLS (SSLv23) 3 no 1 no 2 yes yes yes yes TLSv1 no no yes yes no no TLSv1.1 no no yes no yes no TLSv1.2 no no yes no no yes Footnotes 1(1,2) SSLContext disables SSLv2 with OP_NO_SSLv2 by default. 2(1,2) SSLContext disables SSLv3 with OP_NO_SSLv3 by default. 3(1,2) TLS 1.3 protocol will be available with PROTOCOL_TLS in OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3. See also create_default_context() lets the ssl module choose security settings for a given purpose. Changed in version 3.6: The context is created with secure default values. The options OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE, OP_NO_SSLv2 (except for PROTOCOL_SSLv2), and OP_NO_SSLv3 (except for PROTOCOL_SSLv3) are set by default. The initial cipher suite list contains only HIGH ciphers, no NULL ciphers and no MD5 ciphers (except for PROTOCOL_SSLv2).
python.library.ssl#ssl.SSLContext
SSLContext.cert_store_stats() Get statistics about quantities of loaded X.509 certificates, count of X.509 certificates flagged as CA certificates and certificate revocation lists as dictionary. Example for a context with one CA cert and one other cert: >>> context.cert_store_stats() {'crl': 0, 'x509_ca': 1, 'x509': 2} New in version 3.4.
python.library.ssl#ssl.SSLContext.cert_store_stats
SSLContext.check_hostname Whether to match the peer cert’s hostname in SSLSocket.do_handshake(). The context’s verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, and you must pass server_hostname to wrap_socket() in order to match the hostname. Enabling hostname checking automatically sets verify_mode from CERT_NONE to CERT_REQUIRED. It cannot be set back to CERT_NONE as long as hostname checking is enabled. The PROTOCOL_TLS_CLIENT protocol enables hostname checking by default. With other protocols, hostname checking must be enabled explicitly. Example: import socket, ssl context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_default_certs() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com') ssl_sock.connect(('www.verisign.com', 443)) New in version 3.4. Changed in version 3.7: verify_mode is now automatically changed to CERT_REQUIRED when hostname checking is enabled and verify_mode is CERT_NONE. Previously the same operation would have failed with a ValueError. Note This features requires OpenSSL 0.9.8f or newer.
python.library.ssl#ssl.SSLContext.check_hostname
SSLContext.get_ca_certs(binary_form=False) Get a list of loaded “certification authority” (CA) certificates. If the binary_form parameter is False each list entry is a dict like the output of SSLSocket.getpeercert(). Otherwise the method returns a list of DER-encoded certificates. The returned list does not contain certificates from capath unless a certificate was requested and loaded by a SSL connection. Note Certificates in a capath directory aren’t loaded unless they have been used at least once. New in version 3.4.
python.library.ssl#ssl.SSLContext.get_ca_certs
SSLContext.get_ciphers() Get a list of enabled ciphers. The list is in order of cipher priority. See SSLContext.set_ciphers(). Example: >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') >>> ctx.get_ciphers() # OpenSSL 1.0.x [{'alg_bits': 256, 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(256) Mac=AEAD', 'id': 50380848, 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1/SSLv3', 'strength_bits': 256}, {'alg_bits': 128, 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(128) Mac=AEAD', 'id': 50380847, 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1/SSLv3', 'strength_bits': 128}] On OpenSSL 1.1 and newer the cipher dict contains additional fields: >>> ctx.get_ciphers() # OpenSSL 1.1+ [{'aead': True, 'alg_bits': 256, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(256) Mac=AEAD', 'digest': None, 'id': 50380848, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1.2', 'strength_bits': 256, 'symmetric': 'aes-256-gcm'}, {'aead': True, 'alg_bits': 128, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(128) Mac=AEAD', 'digest': None, 'id': 50380847, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1.2', 'strength_bits': 128, 'symmetric': 'aes-128-gcm'}] Availability: OpenSSL 1.0.2+. New in version 3.6.
python.library.ssl#ssl.SSLContext.get_ciphers
SSLContext.hostname_checks_common_name Whether check_hostname falls back to verify the cert’s subject common name in the absence of a subject alternative name extension (default: true). Note Only writeable with OpenSSL 1.1.0 or higher. New in version 3.7. Changed in version 3.9.3: The flag had no effect with OpenSSL before version 1.1.1k. Python 3.8.9, 3.9.3, and 3.10 include workarounds for previous versions.
python.library.ssl#ssl.SSLContext.hostname_checks_common_name
SSLContext.keylog_filename Write TLS keys to a keylog file, whenever key material is generated or received. The keylog file is designed for debugging purposes only. The file format is specified by NSS and used by many traffic analyzers such as Wireshark. The log file is opened in append-only mode. Writes are synchronized between threads, but not between processes. New in version 3.8. Note This features requires OpenSSL 1.1.1 or newer.
python.library.ssl#ssl.SSLContext.keylog_filename
SSLContext.load_cert_chain(certfile, keyfile=None, password=None) Load a private key and the corresponding certificate. The certfile string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate’s authenticity. The keyfile string, if present, must point to a file containing the private key in. Otherwise the private key will be taken from certfile as well. See the discussion of Certificates for more information on how the certificate is stored in the certfile. The password argument may be a function to call to get the password for decrypting the private key. It will only be called if the private key is encrypted and a password is necessary. It will be called with no arguments, and it should return a string, bytes, or bytearray. If the return value is a string it will be encoded as UTF-8 before using it to decrypt the key. Alternatively a string, bytes, or bytearray value may be supplied directly as the password argument. It will be ignored if the private key is not encrypted and no password is needed. If the password argument is not specified and a password is required, OpenSSL’s built-in password prompting mechanism will be used to interactively prompt the user for a password. An SSLError is raised if the private key doesn’t match with the certificate. Changed in version 3.3: New optional argument password.
python.library.ssl#ssl.SSLContext.load_cert_chain
SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH) Load a set of default “certification authority” (CA) certificates from default locations. On Windows it loads CA certs from the CA and ROOT system stores. On other systems it calls SSLContext.set_default_verify_paths(). In the future the method may load CA certificates from other locations, too. The purpose flag specifies what kind of CA certificates are loaded. The default settings Purpose.SERVER_AUTH loads certificates, that are flagged and trusted for TLS web server authentication (client side sockets). Purpose.CLIENT_AUTH loads CA certificates for client certificate verification on the server side. New in version 3.4.
python.library.ssl#ssl.SSLContext.load_default_certs
SSLContext.load_dh_params(dhfile) Load the key generation parameters for Diffie-Hellman (DH) key exchange. Using DH key exchange improves forward secrecy at the expense of computational resources (both on the server and on the client). The dhfile parameter should be the path to a file containing DH parameters in PEM format. This setting doesn’t apply to client sockets. You can also use the OP_SINGLE_DH_USE option to further improve security. New in version 3.3.
python.library.ssl#ssl.SSLContext.load_dh_params
SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None) Load a set of “certification authority” (CA) certificates used to validate other peers’ certificates when verify_mode is other than CERT_NONE. At least one of cafile or capath must be specified. This method can also load certification revocation lists (CRLs) in PEM or DER format. In order to make use of CRLs, SSLContext.verify_flags must be configured properly. The cafile string, if present, is the path to a file of concatenated CA certificates in PEM format. See the discussion of Certificates for more information about how to arrange the certificates in this file. The capath string, if present, is the path to a directory containing several CA certificates in PEM format, following an OpenSSL specific layout. The cadata object, if present, is either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates. Like with capath extra lines around PEM-encoded certificates are ignored but at least one certificate must be present. Changed in version 3.4: New optional argument cadata
python.library.ssl#ssl.SSLContext.load_verify_locations
SSLContext.maximum_version A TLSVersion enum member representing the highest supported TLS version. The value defaults to TLSVersion.MAXIMUM_SUPPORTED. The attribute is read-only for protocols other than PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, and PROTOCOL_TLS_SERVER. The attributes maximum_version, minimum_version and SSLContext.options all affect the supported SSL and TLS versions of the context. The implementation does not prevent invalid combination. For example a context with OP_NO_TLSv1_2 in options and maximum_version set to TLSVersion.TLSv1_2 will not be able to establish a TLS 1.2 connection. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. New in version 3.7.
python.library.ssl#ssl.SSLContext.maximum_version
SSLContext.minimum_version Like SSLContext.maximum_version except it is the lowest supported version or TLSVersion.MINIMUM_SUPPORTED. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. New in version 3.7.
python.library.ssl#ssl.SSLContext.minimum_version
SSLContext.num_tickets Control the number of TLS 1.3 session tickets of a TLS_PROTOCOL_SERVER context. The setting has no impact on TLS 1.0 to 1.2 connections. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.1 or newer. New in version 3.8.
python.library.ssl#ssl.SSLContext.num_tickets
SSLContext.options An integer representing the set of SSL options enabled on this context. The default value is OP_ALL, but you can specify other options such as OP_NO_SSLv2 by ORing them together. Note With versions of OpenSSL older than 0.9.8m, it is only possible to set options, not to clear them. Attempting to clear an option (by resetting the corresponding bits) will raise a ValueError. Changed in version 3.6: SSLContext.options returns Options flags: >>> ssl.create_default_context().options <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>
python.library.ssl#ssl.SSLContext.options
SSLContext.post_handshake_auth Enable TLS 1.3 post-handshake client authentication. Post-handshake auth is disabled by default and a server can only request a TLS client certificate during the initial handshake. When enabled, a server may request a TLS client certificate at any time after the handshake. When enabled on client-side sockets, the client signals the server that it supports post-handshake authentication. When enabled on server-side sockets, SSLContext.verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, too. The actual client cert exchange is delayed until SSLSocket.verify_client_post_handshake() is called and some I/O is performed. Note Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the property value is None and can’t be modified New in version 3.8.
python.library.ssl#ssl.SSLContext.post_handshake_auth
SSLContext.protocol The protocol version chosen when constructing the context. This attribute is read-only.
python.library.ssl#ssl.SSLContext.protocol
SSLContext.session_stats() Get statistics about the SSL sessions created or managed by this context. A dictionary is returned which maps the names of each piece of information to their numeric values. For example, here is the total number of hits and misses in the session cache since the context was created: >>> stats = context.session_stats() >>> stats['hits'], stats['misses'] (0, 0)
python.library.ssl#ssl.SSLContext.session_stats
SSLContext.set_alpn_protocols(protocols) Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of ASCII strings, like ['http/1.1', 'spdy/2'], ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to RFC 7301. After a successful handshake, the SSLSocket.selected_alpn_protocol() method will return the agreed-upon protocol. This method will raise NotImplementedError if HAS_ALPN is False. OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise SSLError when both sides support ALPN but cannot agree on a protocol. 1.1.0f+ behaves like 1.0.2, SSLSocket.selected_alpn_protocol() returns None. New in version 3.5.
python.library.ssl#ssl.SSLContext.set_alpn_protocols
SSLContext.set_ciphers(ciphers) Set the available ciphers for sockets created with this context. It should be a string in the OpenSSL cipher list format. If no cipher can be selected (because compile-time options or other configuration forbids use of all the specified ciphers), an SSLError will be raised. Note when connected, the SSLSocket.cipher() method of SSL sockets will give the currently selected cipher. OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites cannot be disabled with set_ciphers().
python.library.ssl#ssl.SSLContext.set_ciphers
SSLContext.set_default_verify_paths() Load a set of default “certification authority” (CA) certificates from a filesystem path defined when building the OpenSSL library. Unfortunately, there’s no easy way to know whether this method succeeds: no error is returned if no certificates are to be found. When the OpenSSL library is provided as part of the operating system, though, it is likely to be configured properly.
python.library.ssl#ssl.SSLContext.set_default_verify_paths
SSLContext.set_ecdh_curve(curve_name) Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key exchange. ECDH is significantly faster than regular DH while arguably as secure. The curve_name parameter should be a string describing a well-known elliptic curve, for example prime256v1 for a widely supported curve. This setting doesn’t apply to client sockets. You can also use the OP_SINGLE_ECDH_USE option to further improve security. This method is not available if HAS_ECDH is False. New in version 3.3. See also SSL/TLS & Perfect Forward Secrecy Vincent Bernat.
python.library.ssl#ssl.SSLContext.set_ecdh_curve
SSLContext.set_npn_protocols(protocols) Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of strings, like ['http/1.1', 'spdy/2'], ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to the Application Layer Protocol Negotiation. After a successful handshake, the SSLSocket.selected_npn_protocol() method will return the agreed-upon protocol. This method will raise NotImplementedError if HAS_NPN is False. New in version 3.3.
python.library.ssl#ssl.SSLContext.set_npn_protocols
SSLContext.set_servername_callback(server_name_callback) This is a legacy API retained for backwards compatibility. When possible, you should use sni_callback instead. The given server_name_callback is similar to sni_callback, except that when the server hostname is an IDN-encoded internationalized domain name, the server_name_callback receives a decoded U-label ("pythön.org"). If there is an decoding error on the server name, the TLS connection will terminate with an ALERT_DESCRIPTION_INTERNAL_ERROR fatal TLS alert message to the client. New in version 3.4.
python.library.ssl#ssl.SSLContext.set_servername_callback
SSLContext.sni_callback Register a callback function that will be called after the TLS Client Hello handshake message has been received by the SSL/TLS server when the TLS client specifies a server name indication. The server name indication mechanism is specified in RFC 6066 section 3 - Server Name Indication. Only one callback can be set per SSLContext. If sni_callback is set to None then the callback is disabled. Calling this function a subsequent time will disable the previously registered callback. The callback function will be called with three arguments; the first being the ssl.SSLSocket, the second is a string that represents the server name that the client is intending to communicate (or None if the TLS Client Hello does not contain a server name) and the third argument is the original SSLContext. The server name argument is text. For internationalized domain name, the server name is an IDN A-label ("xn--pythn-mua.org"). A typical use of this callback is to change the ssl.SSLSocket’s SSLSocket.context attribute to a new object of type SSLContext representing a certificate chain that matches the server name. Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like SSLSocket.selected_alpn_protocol() and SSLSocket.context. SSLSocket.getpeercert(), SSLSocket.getpeercert(), SSLSocket.cipher() and SSLSocket.compress() methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore will not contain return meaningful values nor can they be called safely. The sni_callback function must return None to allow the TLS negotiation to continue. If a TLS failure is required, a constant ALERT_DESCRIPTION_* can be returned. Other return values will result in a TLS fatal error with ALERT_DESCRIPTION_INTERNAL_ERROR. If an exception is raised from the sni_callback function the TLS connection will terminate with a fatal TLS alert message ALERT_DESCRIPTION_HANDSHAKE_FAILURE. This method will raise NotImplementedError if the OpenSSL library had OPENSSL_NO_TLSEXT defined when it was built. New in version 3.7.
python.library.ssl#ssl.SSLContext.sni_callback
SSLContext.sslobject_class The return type of SSLContext.wrap_bio(), defaults to SSLObject. The attribute can be overridden on instance of class in order to return a custom subclass of SSLObject. New in version 3.7.
python.library.ssl#ssl.SSLContext.sslobject_class
SSLContext.sslsocket_class The return type of SSLContext.wrap_socket(), defaults to SSLSocket. The attribute can be overridden on instance of class in order to return a custom subclass of SSLSocket. New in version 3.7.
python.library.ssl#ssl.SSLContext.sslsocket_class
SSLContext.verify_flags The flags for certificate verification operations. You can set flags like VERIFY_CRL_CHECK_LEAF by ORing them together. By default OpenSSL does neither require nor verify certificate revocation lists (CRLs). Available only with openssl version 0.9.8+. New in version 3.4. Changed in version 3.6: SSLContext.verify_flags returns VerifyFlags flags: >>> ssl.create_default_context().verify_flags <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>
python.library.ssl#ssl.SSLContext.verify_flags
SSLContext.verify_mode Whether to try to verify other peers’ certificates and how to behave if verification fails. This attribute must be one of CERT_NONE, CERT_OPTIONAL or CERT_REQUIRED. Changed in version 3.6: SSLContext.verify_mode returns VerifyMode enum: >>> ssl.create_default_context().verify_mode <VerifyMode.CERT_REQUIRED: 2>
python.library.ssl#ssl.SSLContext.verify_mode
SSLContext.wrap_bio(incoming, outgoing, server_side=False, server_hostname=None, session=None) Wrap the BIO objects incoming and outgoing and return an instance of SSLContext.sslobject_class (default SSLObject). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO. The server_side, server_hostname and session parameters have the same meaning as in SSLContext.wrap_socket(). Changed in version 3.6: session argument was added. Changed in version 3.7: The method returns on instance of SSLContext.sslobject_class instead of hard-coded SSLObject.
python.library.ssl#ssl.SSLContext.wrap_bio
SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None) Wrap an existing Python socket sock and return an instance of SSLContext.sslsocket_class (default SSLSocket). The returned SSL socket is tied to the context, its settings and certificates. sock must be a SOCK_STREAM socket; other socket types are unsupported. The parameter server_side is a boolean which identifies whether server-side or client-side behavior is desired from this socket. For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed after connect() is called on the socket. For server-side sockets, if the socket has no remote peer, it is assumed to be a listening socket, and the server-side SSL wrapping is automatically performed on client connections accepted via the accept() method. The method may raise SSLError. On client connections, the optional parameter server_hostname specifies the hostname of the service which we are connecting to. This allows a single server to host multiple SSL-based services with distinct certificates, quite similarly to HTTP virtual hosts. Specifying server_hostname will raise a ValueError if server_side is true. The parameter do_handshake_on_connect specifies whether to do the SSL handshake automatically after doing a socket.connect(), or whether the application program will call it explicitly, by invoking the SSLSocket.do_handshake() method. Calling SSLSocket.do_handshake() explicitly gives the program control over the blocking behavior of the socket I/O involved in the handshake. The parameter suppress_ragged_eofs specifies how the SSLSocket.recv() method should signal unexpected EOF from the other end of the connection. If specified as True (the default), it returns a normal EOF (an empty bytes object) in response to unexpected EOF errors raised from the underlying socket; if False, it will raise the exceptions back to the caller. session, see session. Changed in version 3.5: Always allow a server_hostname to be passed, even if OpenSSL does not have SNI. Changed in version 3.6: session argument was added. Changed in version 3.7: The method returns on instance of SSLContext.sslsocket_class instead of hard-coded SSLSocket.
python.library.ssl#ssl.SSLContext.wrap_socket
exception ssl.SSLEOFError A subclass of SSLError raised when the SSL connection has been terminated abruptly. Generally, you shouldn’t try to reuse the underlying transport when this error is encountered. New in version 3.3.
python.library.ssl#ssl.SSLEOFError
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 of SSLError instances are provided by the OpenSSL library. Changed in version 3.3: SSLError used to be a subtype of socket.error. library A string mnemonic designating the OpenSSL submodule in which the error occurred, such as SSL, PEM or X509. The range of possible values depends on the OpenSSL version. New in version 3.3. reason A string mnemonic designating the reason this error occurred, for example CERTIFICATE_VERIFY_FAILED. The range of possible values depends on the OpenSSL version. New in version 3.3.
python.library.ssl#ssl.SSLError
library A string mnemonic designating the OpenSSL submodule in which the error occurred, such as SSL, PEM or X509. The range of possible values depends on the OpenSSL version. New in version 3.3.
python.library.ssl#ssl.SSLError.library
reason A string mnemonic designating the reason this error occurred, for example CERTIFICATE_VERIFY_FAILED. The range of possible values depends on the OpenSSL version. New in version 3.3.
python.library.ssl#ssl.SSLError.reason
class ssl.SSLErrorNumber enum.IntEnum collection of SSL_ERROR_* constants. New in version 3.6.
python.library.ssl#ssl.SSLErrorNumber
class ssl.SSLObject A reduced-scope variant of SSLSocket representing an SSL protocol instance that does not contain any network IO methods. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers. 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 through separate “BIO” objects which are OpenSSL’s IO abstraction layer. This class has no public constructor. An SSLObject instance must be created using the wrap_bio() method. This method will create the SSLObject instance and bind it to a pair of BIOs. The incoming BIO is used to pass data from Python to the SSL protocol instance, while the outgoing BIO is used to pass data the other way around. The following methods are available: context server_side server_hostname session session_reused read() write() getpeercert() selected_alpn_protocol() selected_npn_protocol() cipher() shared_ciphers() compression() pending() do_handshake() verify_client_post_handshake() unwrap() get_channel_binding() version() When compared to SSLSocket, this object lacks the following features: Any form of network IO; recv() and send() read and write only to the underlying MemoryBIO buffers. There is no do_handshake_on_connect machinery. You must always manually call do_handshake() to start the handshake. There is no handling of suppress_ragged_eofs. All end-of-file conditions that are in violation of the protocol are reported via the SSLEOFError exception. The method unwrap() call does not return anything, unlike for an SSL socket where it returns the underlying socket. The server_name_callback callback passed to SSLContext.set_servername_callback() will get an SSLObject instance instead of a SSLSocket instance as its first parameter. Some notes related to the use of SSLObject: All IO on an SSLObject is non-blocking. This means that for example read() will raise an SSLWantReadError if it needs more data than the incoming BIO has available. There is no module-level wrap_bio() call like there is for wrap_socket(). An SSLObject is always created via an SSLContext. Changed in version 3.7: SSLObject instances must to created with wrap_bio(). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.
python.library.ssl#ssl.SSLObject
class ssl.SSLSession Session object used by session. id time timeout ticket_lifetime_hint has_ticket
python.library.ssl#ssl.SSLSession
has_ticket
python.library.ssl#ssl.SSLSession.has_ticket
id
python.library.ssl#ssl.SSLSession.id
ticket_lifetime_hint
python.library.ssl#ssl.SSLSession.ticket_lifetime_hint
time
python.library.ssl#ssl.SSLSession.time
timeout
python.library.ssl#ssl.SSLSession.timeout
class ssl.SSLSocket(socket.socket) SSL sockets provide the following methods of Socket Objects: accept() bind() close() connect() detach() fileno() getpeername(), getsockname() getsockopt(), setsockopt() gettimeout(), settimeout(), setblocking() listen() makefile() recv(), recv_into() (but passing a non-zero flags argument is not allowed) send(), sendall() (with the same limitation) sendfile() (but os.sendfile will be used for plain-text sockets only, else send() will be used) shutdown() However, since the SSL (and TLS) protocol has its own framing atop of TCP, the SSL sockets abstraction can, in certain respects, diverge from the specification of normal, OS-level sockets. See especially the notes on non-blocking sockets. Instances of SSLSocket must be created using the SSLContext.wrap_socket() method. Changed in version 3.5: The sendfile() method was added. Changed in version 3.5: The shutdown() does not reset the socket timeout each time bytes are received or sent. The socket timeout is now to maximum total duration of the shutdown. Deprecated since version 3.6: It is deprecated to create a SSLSocket instance directly, use SSLContext.wrap_socket() to wrap a socket. Changed in version 3.7: SSLSocket instances must to created with wrap_socket(). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.
python.library.ssl#ssl.SSLSocket
SSLSocket.cipher() Returns a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used. If no connection has been established, returns None.
python.library.ssl#ssl.SSLSocket.cipher
SSLSocket.compression() Return the compression algorithm being used as a string, or None if the connection isn’t compressed. If the higher-level protocol supports its own compression mechanism, you can use OP_NO_COMPRESSION to disable SSL-level compression. New in version 3.3.
python.library.ssl#ssl.SSLSocket.compression