gevent.ssl – Secure Sockets Layer (SSL/TLS) module#

This module provides SSL/TLS operations and some related functions. The API of the functions and classes matches the API of the corresponding items in the standard ssl module exactly, but the synchronous functions in this module only block the current greenlet and let the others run.

The exact API exposed by this module varies depending on what version of Python you are using. The documents below describe the API for Python 3.

Tip

As an implementation note, gevent’s exact behaviour will differ somewhat depending on the underlying TLS version in use. For example, the number of data exchanges involved in the handshake process, and exactly when that process occurs, will vary. This can be indirectly observed by the number and timing of greenlet switches or trips around the event loop gevent makes.

Most applications should not notice this, but some applications (and especially tests, where it is common for a process to be both a server and its own client), may find that they have coded in assumptions about the order in which multiple greenlets run. As TLS 1.3 gets deployed, those assumptions are likely to break.

Warning

All the described APIs should be imported from gevent.ssl, and not from their implementation modules. Their organization is an implementation detail that may change at any time.

SSL wrapper for socket objects on Python 3.

For the documentation, refer to ssl module manual.

This module implements cooperative SSL socket wrappers.

CertificateError#

alias of SSLCertVerificationError

exception SSLCertVerificationError#

Bases: SSLError, ValueError

A certificate could not be verified.

exception SSLEOFError#

Bases: SSLError

SSL/TLS connection terminated abruptly.

exception SSLError#

Bases: OSError

An error occurred in the SSL implementation.

exception SSLSyscallError#

Bases: SSLError

System error when attempting SSL operation.

exception SSLWantReadError#

Bases: SSLError

Non-blocking SSL socket needs to read more data before the requested operation can be completed.

exception SSLWantWriteError#

Bases: SSLError

Non-blocking SSL socket needs to write more data before the requested operation can be completed.

exception SSLZeroReturnError#

Bases: SSLError

SSL/TLS session closed cleanly.

socket_error#

alias of OSError

class AlertDescription(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: IntEnum

An enumeration.

class DefaultVerifyPaths(cafile, capath, openssl_cafile_env, openssl_cafile, openssl_capath_env, openssl_capath)#

Bases: tuple

Create new instance of DefaultVerifyPaths(cafile, capath, openssl_cafile_env, openssl_cafile, openssl_capath_env, openssl_capath)

cafile#

Alias for field number 0

capath#

Alias for field number 1

openssl_cafile#

Alias for field number 3

openssl_cafile_env#

Alias for field number 2

openssl_capath#

Alias for field number 5

openssl_capath_env#

Alias for field number 4

class Options(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: IntFlag

An enumeration.

class Purpose(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: _ASN1Object, Enum

SSLContext purpose flags with X509v3 Extended Key Usage objects

Create new instance of _ASN1Object(nid, shortname, longname, oid)

class SSLContext(protocol=None, *args, **kwargs)[source]#

Bases: SSLContext

sslsocket_class#

alias of SSLSocket

property sni_callback#

Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.

If the argument is None then the callback is disabled. The method is called with the SSLSocket, the server name as a string, and the SSLContext object. See RFC 6066 for details of the SNI extension.

class SSLErrorNumber(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: IntEnum

An enumeration.

class SSLObject(*args, **kwargs)[source]#

Bases: object

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 does not have a public constructor. Instances are returned by SSLContext.wrap_bio. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers.

When compared to SSLSocket, this object lacks the following features:

  • Any form of network IO, including methods such as recv and send.

  • The do_handshake_on_connect and suppress_ragged_eofs machinery.

cipher()[source]#

Return the currently selected cipher as a 3-tuple (name, ssl_version, secret_bits).

compression()[source]#

Return the current compression algorithm in use, or None if compression was not negotiated or not supported by one of the peers.

do_handshake()[source]#

Start the SSL/TLS handshake.

get_channel_binding(cb_type='tls-unique')[source]#

Get channel binding data for current connection. Raise ValueError if the requested cb_type is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).

getpeercert(binary_form=False)[source]#

Returns a formatted version of the data in the certificate provided by the other end of the SSL channel.

Return None if no certificate was provided, {} if a certificate was provided, but not validated.

pending()[source]#

Return the number of bytes that can be read immediately.

read(len=1024, buffer=None)[source]#

Read up to ‘len’ bytes from the SSL object and return them.

If ‘buffer’ is provided, read into this buffer and return the number of bytes read.

selected_alpn_protocol()[source]#

Return the currently selected ALPN protocol as a string, or None if a next protocol was not negotiated or if ALPN is not supported by one of the peers.

selected_npn_protocol()[source]#

Return the currently selected NPN protocol as a string, or None if a next protocol was not negotiated or if NPN is not supported by one of the peers.

shared_ciphers()[source]#

Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection.

unwrap()[source]#

Start the SSL shutdown handshake.

version()[source]#

Return a string identifying the protocol version used by the current SSL channel.

write(data)[source]#

Write ‘data’ to the SSL object and return the number of bytes written.

The ‘data’ argument must support the buffer interface.

property context#

The SSLContext that is currently in use.

property server_hostname#

The currently set server hostname (for SNI), or None if no server hostname is set.

property server_side#

Whether this is a server-side socket.

property session#

The SSLSession for client socket.

property session_reused#

Was the client session reused during handshake

class SSLSocket(sock=None, keyfile=None, certfile=None, server_side=False, cert_reqs=VerifyMode.CERT_NONE, ssl_version=_SSLMethod.PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, fileno=None, suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, server_hostname=None, _session=None, _context=None)[source]#

Bases: socket

gevent ssl.SSLSocket for Python 3.

accept()[source]#

Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.

connect(addr)[source]#

Connects to remote ADDR, and then wraps the connection in an SSL channel.

connect_ex(addr)[source]#

Connects to remote ADDR, and then wraps the connection in an SSL channel.

do_handshake()[source]#

Perform a TLS/SSL handshake.

dup() socket object[source]#

Return a new socket object connected to the same system resource.

get_channel_binding(cb_type='tls-unique')[source]#

Get channel binding data for current connection. Raise ValueError if the requested cb_type is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).

getpeercert(binary_form=False)[source]#

Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.

read(nbytes=2014, buffer=None)[source]#

Read up to LEN bytes and return them. Return zero-length string on EOF.

Changed in version 24.2.1: No longer requires a non-None buffer to implement len(). This is a backport from 3.11.8.

recv(buffersize[, flags]) data[source]#

Receive up to buffersize bytes from the socket. For the optional flags argument, see the Unix manual. When no data is available, block until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, return the empty string.

recv_into(buffer, nbytes=None, flags=0)[source]#

Changed in version 24.2.1: No longer requires a non-None buffer to implement len(). This is a backport from 3.11.8.

recvfrom(buffersize[, flags]) -> (data, address info)[source]#

Like recv(buffersize, flags) but also return the sender’s address info.

recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)[source]#

Like recv_into(buffer[, nbytes[, flags]]) but also return the sender’s address info.

send(data[, flags]) count[source]#

Send a data string to the socket. For the optional flags argument, see the Unix manual. Return the number of bytes sent; this may be less than len(data) if the network is busy.

sendall(data[, flags])[source]#

Send a data string to the socket. For the optional flags argument, see the Unix manual. This calls send() repeatedly until all data is sent. If an error occurs, it’s impossible to tell how much data has been sent.

sendto(data, [flags, ]address) count[source]#

Like send(data, flags) but allows specifying the destination address. For IP sockets, the address is a pair (hostaddr, port).

shared_ciphers()[source]#

Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection.

shutdown(flag)[source]#

Shut down the reading side of the socket (flag == SHUT_RD), the writing side of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).

version()[source]#

Return a string identifying the protocol version used by the current SSL channel.

write(data)[source]#

Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.

property session#

The SSLSession for client socket.

property session_reused#

Was the client session reused during handshake

class TLSVersion(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: IntEnum

An enumeration.

class VerifyFlags(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: IntFlag

An enumeration.

class VerifyMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: IntEnum

An enumeration.

DER_cert_to_PEM_cert(der_cert_bytes)[source]#

Takes a certificate in binary DER format and returns the PEM version of it as a string.

PEM_cert_to_DER_cert(pem_cert_string)[source]#

Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence

RAND_add(string, entropy, /)#

Mix string into the OpenSSL PRNG state.

entropy (a float) is a lower bound on the entropy contained in string. See RFC 4086.

RAND_bytes(n, /)#

Generate n cryptographically strong pseudo-random bytes.

RAND_pseudo_bytes(n, /)#

Generate n pseudo-random bytes.

Return a pair (bytes, is_cryptographic). is_cryptographic is True if the bytes generated are cryptographically strong.

RAND_status()#

Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.

It is necessary to seed the PRNG with RAND_add() on some platforms before using the ssl() function.

cert_time_to_seconds(cert_time)[source]#

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).

“notBefore” or “notAfter” dates must use UTC (RFC 5280).

Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec UTC should be specified as GMT (see ASN1_TIME_print())

create_connection(address, timeout=<object object>, source_address=None, *, all_errors=False)[source]#

Connect to address and return the socket object.

Convenience function. Connect to address (a 2-tuple (host, port)) and return the socket object. Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned by getdefaulttimeout() is used. If source_address is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. A host of ‘’ or port 0 tells the OS to use the default. When a connection cannot be created, raises the last error if all_errors is False, and an ExceptionGroup of all errors if all_errors is True.

create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None)[source]#

Create a SSLContext object with default settings.

NOTE: The protocol and settings may change anytime without prior

deprecation. The values represent a fair balance between maximum compatibility and security.

get_default_verify_paths()[source]#

Return paths to default cafile and capath.

get_server_certificate(addr, ssl_version=_SSLMethod.PROTOCOL_TLS, ca_certs=None)[source]#

Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If ‘ca_certs’ is specified, validate the server cert against it. If ‘ssl_version’ is specified, use it in the connection attempt.

match_hostname(cert, hostname)[source]#

Verify that cert (in decoded format as returned by SSLSocket.getpeercert()) matches the hostname. RFC 2818 and RFC 6125 rules are followed.

The function matches IP addresses rather than dNSNames if hostname is a valid ipaddress string. IPv4 addresses are supported on all platforms. IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 and inet_pton).

CertificateError is raised on failure. On success, the function returns nothing.