17.3. 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. It is available on all modern Unix systems, Windows, Mac OS X, and probably additional platforms, as long as OpenSSL is installed on that platform.
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.
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, and cipher()
,which
retrieves the cipher being used for the secure connection.
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.
17.3.1. Functions, Constants, and 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
socket.error
, which in turn is a subtype ofIOError
. The error code and message ofSSLError
instances are provided by the OpenSSL library.
-
exception
ssl.
CertificateError
¶ Raised to signal an error with a certificate (such as mismatching hostname). Certificate errors detected by OpenSSL, though, raise an
SSLError
.
17.3.1.1. Socket creation¶
The following function allows for standalone socket creation. Starting from
Python 3.2, it can be more flexible to use SSLContext.wrap_socket()
instead.
-
ssl.
wrap_socket
(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)¶ Takes an instance
sock
ofsocket.socket
, and returns an instance ofssl.SSLSocket
, a subtype ofsocket.socket
, which wraps the underlying socket in an SSL context. For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed afterconnect()
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 theaccept()
method.wrap_socket()
may raiseSSLError
.The
keyfile
andcertfile
parameters specify optional files which contain a certificate to be used to identify the local side of the connection. See the discussion of Certificates for more information on how the certificate is stored in thecertfile
.The parameter
server_side
is a boolean which identifies whether server-side or client-side behavior is desired from this socket.The parameter
cert_reqs
specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three valuesCERT_NONE
(certificates ignored),CERT_OPTIONAL
(not required, but validated if provided), orCERT_REQUIRED
(required and validated). If the value of this parameter is notCERT_NONE
, then theca_certs
parameter must point to a file of CA certificates.The
ca_certs
file contains a set of concatenated “certification authority” certificates, which are used to validate certificates passed from the other end of the connection. See the discussion of Certificates for more information about how to arrange the certificates in this file.The parameter
ssl_version
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, for client-side operation, the default SSL version is SSLv3; for server-side operation, SSLv23. These version selections provide 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 SSLv23 TLSv1 SSLv2 yes no yes no SSLv3 yes yes yes no SSLv23 yes no yes no TLSv1 no no yes yes Note
Which connections succeed will vary depending on the version of OpenSSL. For instance, in some older versions of OpenSSL (such as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an SSLv23 server. Another example: beginning with OpenSSL 1.0.0, an SSLv23 client will not actually attempt SSLv2 connections unless you explicitly enable SSLv2 ciphers; for example, you might specify
"ALL"
or"SSLv2"
as the ciphers parameter to enable them.The ciphers parameter sets the available ciphers for this SSL object. It should be a string in the OpenSSL cipher list format.
The parameter
do_handshake_on_connect
specifies whether to do the SSL handshake automatically after doing asocket.connect()
, or whether the application program will call it explicitly, by invoking theSSLSocket.do_handshake()
method. CallingSSLSocket.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 theSSLSocket.recv()
method should signal unexpected EOF from the other end of the connection. If specified asTrue
(the default), it returns a normal EOF (an empty bytes object) in response to unexpected EOF errors raised from the underlying socket; ifFalse
, it will raise the exceptions back to the caller.Changed in version 3.2:
Changed in version 3.2: New optional argument ciphers.
17.3.1.2. Random generation¶
-
ssl.
RAND_status
()¶ Returns True if the SSL pseudo-random number generator has been seeded with ‘enough’ randomness, and False otherwise. You can use
ssl.RAND_egd()
andssl.RAND_add()
to increase the randomness of the pseudo-random number generator.
-
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.
17.3.1.3. Certificate handling¶
-
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, except that IP addresses are not currently supported. 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:
New in version 3.2.
-
ssl.
cert_time_to_seconds
(timestring)¶ Returns a floating-point value containing a normal seconds-after-the-epoch time value, given the time-string representing the “notBefore” or “notAfter” date from a certificate.
Here’s an example:
>>> import ssl >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT") 1178694000.0 >>> import time >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")) 'Wed May 9 00:00:00 2007'
-
ssl.
get_server_certificate
(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)¶ Given the address
addr
of an SSL-protected server, as a (hostname, port-number) pair, fetches the server’s certificate, and returns it as a PEM-encoded string. Ifssl_version
is specified, uses that version of the SSL protocol to attempt to connect to the server. Ifca_certs
is specified, it should be a file containing a list of root certificates, the same format as used for the same parameter inwrap_socket()
. The call will attempt to validate the server certificate against that set of root certificates, and will fail if the validation attempt fails.
-
ssl.
DER_cert_to_PEM_cert
(DER_cert_bytes)¶ Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded string version of the same certificate.
-
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.
17.3.1.4. Constants¶
-
ssl.
CERT_NONE
¶ Possible value for
SSLContext.verify_mode
, or thecert_reqs
parameter towrap_socket()
. In this mode (the default), no certificates will be required from the other side of the socket connection. If a certificate is received from the other end, no attempt to validate it is made.See the discussion of Security considerations below.
-
ssl.
CERT_OPTIONAL
¶ Possible value for
SSLContext.verify_mode
, or thecert_reqs
parameter towrap_socket()
. In this mode no certificates will be required from the other side of the socket connection; but if they are provided, validation will be attempted and anSSLError
will be raised on failure.Use of this setting requires a valid set of CA certificates to be passed, either to
SSLContext.load_verify_locations()
or as a value of theca_certs
parameter towrap_socket()
.
-
ssl.
CERT_REQUIRED
¶ Possible value for
SSLContext.verify_mode
, or thecert_reqs
parameter towrap_socket()
. In this mode, certificates are required from the other side of the socket connection; anSSLError
will be raised if no certificate is provided, or if its validation fails.Use of this setting requires a valid set of CA certificates to be passed, either to
SSLContext.load_verify_locations()
or as a value of theca_certs
parameter towrap_socket()
.
-
ssl.
PROTOCOL_SSLv2
¶ Selects SSL version 2 as the channel encryption protocol.
This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2 flag.
Warning
SSL version 2 is insecure. Its use is highly discouraged.
-
ssl.
PROTOCOL_SSLv23
¶ Selects SSL version 2 or 3 as the channel encryption protocol. This is a setting to use with servers for maximum compatibility with the other end of an SSL connection, but it may cause the specific ciphers chosen for the encryption to be of fairly low quality.
-
ssl.
PROTOCOL_SSLv3
¶ Selects SSL version 3 as the channel encryption protocol. For clients, this is the maximally compatible SSL variant.
-
ssl.
PROTOCOL_TLSv1
¶ Selects TLS version 1 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.
-
ssl.
OP_ALL
¶ Enables workarounds for various bugs present in other SSL implementations. This option is set by default.
New in version 3.2:
New in version 3.2.
-
ssl.
OP_NO_SSLv2
¶ Prevents an SSLv2 connection. This option is only applicable in conjunction with
PROTOCOL_SSLv23
. It prevents the peers from choosing SSLv2 as the protocol version.New in version 3.2:
New in version 3.2.
-
ssl.
OP_NO_SSLv3
¶ Prevents an SSLv3 connection. This option is only applicable in conjunction with
PROTOCOL_SSLv23
. It prevents the peers from choosing SSLv3 as the protocol version.New in version 3.2:
New in version 3.2.
-
ssl.
OP_NO_TLSv1
¶ Prevents a TLSv1 connection. This option is only applicable in conjunction with
PROTOCOL_SSLv23
. It prevents the peers from choosing TLSv1 as the protocol version.New in version 3.2:
New in version 3.2.
-
ssl.
HAS_SNI
¶ Whether the OpenSSL library has built-in support for the Server Name Indication extension to the SSLv3 and TLSv1 protocols (as defined in RFC 4366). When true, you can use the server_hostname argument to
SSLContext.wrap_socket()
.New in version 3.2:
New in version 3.2.
-
ssl.
OPENSSL_VERSION
¶ The version string of the OpenSSL library loaded by the interpreter:
>>> ssl.OPENSSL_VERSION 'OpenSSL 0.9.8k 25 Mar 2009'
New in version 3.2:
New in version 3.2.