# `SSL` — An interface to the SSL-specific parts of OpenSSL

This module handles things specific to SSL. There are two objects defined: Context, Connection.

OpenSSL.SSL.TLS_METHOD
OpenSSL.SSL.TLS_SERVER_METHOD
OpenSSL.SSL.TLS_CLIENT_METHOD
OpenSSL.SSL.SSLv2_METHOD
OpenSSL.SSL.SSLv3_METHOD
OpenSSL.SSL.SSLv23_METHOD
OpenSSL.SSL.TLSv1_METHOD
OpenSSL.SSL.TLSv1_1_METHOD
OpenSSL.SSL.TLSv1_2_METHOD

  These constants represent the different SSL methods to use when creating a context object. New code should only use `TLS_METHOD`, `TLS_SERVER_METHOD`, or `TLS_CLIENT_METHOD`. If the underlying OpenSSL build is missing support for any of these protocols, constructing a `Context` using the corresponding `*_METHOD` will raise an exception.

OpenSSL.SSL.SSL3_VERSION
OpenSSL.SSL.TLS1_VERSION
OpenSSL.SSL.TLS1_1_VERSION
OpenSSL.SSL.TLS1_2_VERSION
OpenSSL.SSL.TLS1_3_VERSION

  These constants represent the different TLS versions to use when setting the minimum or maximum TLS version.

OpenSSL.SSL.VERIFY_NONE
OpenSSL.SSL.VERIFY_PEER
OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT

  These constants represent the verification mode used by the Context object’s `set_verify()` method.

OpenSSL.SSL.FILETYPE_PEM
OpenSSL.SSL.FILETYPE_ASN1

  File type constants used with the `use_certificate_file()` and `use_privatekey_file()` methods of Context objects.

OpenSSL.SSL.OP_SINGLE_DH_USE
OpenSSL.SSL.OP_SINGLE_ECDH_USE

  Constants used with `set_options()` of Context objects.

  When these options are used, a new key will always be created when using ephemeral (Elliptic curve) Diffie-Hellman.

OpenSSL.SSL.OP_EPHEMERAL_RSA

  Constant used with `set_options()` of Context objects.

  When this option is used, ephemeral RSA keys will always be used when doing RSA operations.

OpenSSL.SSL.OP_NO_TICKET

  Constant used with `set_options()` of Context objects.

  When this option is used, the session ticket extension will not be used.

OpenSSL.SSL.OP_NO_COMPRESSION

  Constant used with `set_options()` of Context objects.

  When this option is used, compression will not be used.

OpenSSL.SSL.OP_NO_SSLv2
OpenSSL.SSL.OP_NO_SSLv3
OpenSSL.SSL.OP_NO_TLSv1
OpenSSL.SSL.OP_NO_TLSv1_1
OpenSSL.SSL.OP_NO_TLSv1_2
OpenSSL.SSL.OP_NO_TLSv1_3

  Constants used with `set_options()` of Context objects.

  Each of these options disables one version of the SSL/TLS protocol. This is interesting if you’re using e.g. `SSLv23_METHOD` to get an SSLv2-compatible handshake, but don’t want to use SSLv2. If the underlying OpenSSL build is missing support for any of these protocols, the `OP_NO_*` constant may be undefined.

OpenSSL.SSL.OPENSSL_VERSION
OpenSSL.SSL.OPENSSL_CFLAGS
OpenSSL.SSL.OPENSSL_BUILT_ON
OpenSSL.SSL.OPENSSL_PLATFORM
OpenSSL.SSL.OPENSSL_DIR

  Changed in version 22.1.0: Previously these were all named `SSLEAY_*`. Those names are still available for backwards compatibility, but the `OPENSSL_*` names are preferred.

  Constants used with `OpenSSL_version()` to specify what OpenSSL version information to retrieve. See the man page for the `OpenSSL_version()` C API for details.

OpenSSL.SSL.SESS_CACHE_OFF
OpenSSL.SSL.SESS_CACHE_CLIENT
OpenSSL.SSL.SESS_CACHE_SERVER
OpenSSL.SSL.SESS_CACHE_BOTH
OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR
OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP
OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE
OpenSSL.SSL.SESS_CACHE_NO_INTERNAL

  Constants used with `Context.set_session_cache_mode()` to specify the behavior of the session cache and potential session reuse. See the man page for the `SSL_CTX_set_session_cache_mode()` C API for details.

  Added in version 0.14.

OpenSSL.SSL.OPENSSL_VERSION_NUMBER

  An integer giving the version number of the OpenSSL library used to build this version of pyOpenSSL. See the man page for the `SSLeay_version()` C API for details.

OpenSSL.SSL.NO_OVERLAPPING_PROTOCOLS

  A sentinel value that can be returned by the callback passed to `Context.set_alpn_select_callback()` to indicate that the handshake can continue without a specific application protocol.

  Added in version 19.1.

OpenSSL.SSL.OpenSSL_version(type: int) → bytes

  Return a string describing the version of OpenSSL in use.

  Parameters:

    type – One of the `OPENSSL_` constants defined in this module.

class OpenSSL.SSL.Context(method: int)

  `OpenSSL.SSL.Context` instances define the parameters for setting up new SSL connections.

  Parameters:

    method – One of TLS_METHOD, TLS_CLIENT_METHOD, TLS_SERVER_METHOD, DTLS_METHOD, DTLS_CLIENT_METHOD, or DTLS_SERVER_METHOD. SSLv23_METHOD, TLSv1_METHOD, etc. are deprecated and should not be used.

class OpenSSL.SSL.Session

  A class representing an SSL session. A session defines certain connection parameters which may be re-used to speed up the setup of subsequent connections.

  Added in version 0.14.

class OpenSSL.SSL.Connection(context, socket)

  > A class representing SSL connections.

  > context should be an instance of `Context` and socket should be a socket [1] object. socket may be None; in this case, the Connection is created with a memory BIO: see the `bio_read()`, `bio_write()`, and `bio_shutdown()` methods.

exception OpenSSL.SSL.Error

  This exception is used as a base class for the other SSL-related exceptions, but may also be raised directly.

  Whenever this exception is raised directly, it has a list of error messages from the OpenSSL error queue, where each item is a tuple (lib, function, reason). Here lib, function and reason are all strings, describing where and what the problem is. See err(3) for more information.

exception OpenSSL.SSL.ZeroReturnError

  This exception matches the error return code `SSL_ERROR_ZERO_RETURN`, and is raised when the SSL Connection has been closed. In SSL 3.0 and TLS 1.0, this only occurs if a closure alert has occurred in the protocol, i.e. the connection has been closed cleanly. Note that this does not necessarily mean that the transport layer (e.g. a socket) has been closed.

  It may seem a little strange that this is an exception, but it does match an `SSL_ERROR` code, and is very convenient.

exception OpenSSL.SSL.WantReadError

  The operation did not complete; the same I/O method should be called again later, with the same arguments. Any I/O method can lead to this since new handshakes can occur at any time.

  The wanted read is for dirty data sent over the network, not the clean data inside the tunnel. For a socket based SSL connection, read means data coming at us over the network. Until that read succeeds, the attempted `OpenSSL.SSL.Connection.recv()`, `OpenSSL.SSL.Connection.send()`, or `OpenSSL.SSL.Connection.do_handshake()` is prevented or incomplete. You probably want to `select()` on the socket before trying again.

exception OpenSSL.SSL.WantWriteError

  See `WantReadError`. The socket send buffer may be too full to write more data.

exception OpenSSL.SSL.WantX509LookupError

  The operation did not complete because an application callback has asked to be called again. The I/O method should be called again later, with the same arguments.

  Note

  This won’t occur in this version, as there are no such callbacks in this version.

exception OpenSSL.SSL.SysCallError

  The `SysCallError` occurs when there’s an I/O error and OpenSSL’s error queue does not contain any information. This can mean two things: An error in the transport protocol, or an end of file that violates the protocol. The parameter to the exception is always a pair (errnum, errstr).

## Context objects

Context objects have the following methods:

class OpenSSL.SSL.Context(method: int)

  `OpenSSL.SSL.Context` instances define the parameters for setting up new SSL connections.

  Parameters:

    method – One of TLS_METHOD, TLS_CLIENT_METHOD, TLS_SERVER_METHOD, DTLS_METHOD, DTLS_CLIENT_METHOD, or DTLS_SERVER_METHOD. SSLv23_METHOD, TLSv1_METHOD, etc. are deprecated and should not be used.

  add_client_ca(certificate_authority: X509 | Certificate) → None

    Add the CA certificate to the list of preferred signers for this context.

    The list of certificate authorities will be sent to the client when the server requests a client certificate.

    Parameters:

      certificate_authority – certificate authority’s X509 certificate.

    Returns:

      None

    Added in version 0.10.

  add_extra_chain_cert(certobj: X509 | Certificate) → None

    Add certificate to chain

    Parameters:

      certobj – The X509 certificate object to add to the chain

    Returns:

      None

  check_privatekey() → None

    Check if the private key (loaded with `use_privatekey()`) matches the certificate (loaded with `use_certificate()`)

    Returns:

      `None` (raises `Error` if something’s wrong)

  clear_mode(mode_to_clear: int) → int

    Modes previously set cannot be overwritten without being cleared first. This method should be used to clear existing modes.

  get_app_data() → Any

    Get the application data (supplied via `set_app_data()`)

    Returns:

      The application data

  get_cert_store() → X509Store | None

    Get the certificate store for the context. This can be used to add “trusted” certificates without using the `load_verify_locations()` method.

    Returns:

      A X509Store object or None if it does not have one.

  get_session_cache_mode() → int

    Get the current session cache mode.

    Returns:

      The currently used cache mode.

    Added in version 0.14.

  get_timeout() → int

    Retrieve session timeout, as set by `set_timeout()`. The default is 300 seconds.

    Returns:

      The session timeout

  get_verify_depth() → int

    Retrieve the Context object’s verify depth, as set by `set_verify_depth()`.

    Returns:

      The verify depth

  get_verify_mode() → int

    Retrieve the Context object’s verify mode, as set by `set_verify()`.

    Returns:

      The verify mode

  load_client_ca(cafile: bytes) → None

    Load the trusted certificates that will be sent to the client. Does not actually imply any of the certificates are trusted; that must be configured separately.

    Parameters:

      cafile (bytes) – The path to a certificates file in PEM format.

    Returns:

      None

  load_tmp_dh(dhfile: str | bytes | PathLike[str] | PathLike[bytes]) → None

    Load parameters for Ephemeral Diffie-Hellman

    Parameters:

      dhfile – The file to load EDH parameters from (`bytes` or `str`).

    Returns:

      None

  load_verify_locations(cafile: str | bytes | PathLike[str] | PathLike[bytes] | None, capath: str | bytes | PathLike[str] | PathLike[bytes] | None = None) → None

    Let SSL know where we can find trusted certificates for the certificate chain. Note that the certificates have to be in PEM format.

    If capath is passed, it must be a directory prepared using the `c_rehash` tool included with OpenSSL. Either, but not both, of pemfile or capath may be `None`.

    Parameters:

      - cafile – In which file we can find the certificates (`bytes` or `str`).

      - capath – In which directory we can find the certificates (`bytes` or `str`).

    Returns:

      None

  set_alpn_protos(protos: list[bytes]) → None

    Specify the protocols that the client is prepared to speak after the TLS connection has been negotiated using Application Layer Protocol Negotiation.

    Parameters:

      protos – A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. `[b'http/1.1', b'spdy/2']`.

  set_alpn_select_callback(callback: Callable[[Connection, List[bytes]], bytes | _NoOverlappingProtocols]) → None

    Specify a callback function that will be called on the server when a client offers protocols using ALPN.

    Parameters:

      callback – The callback function. It will be invoked with two arguments: the Connection, and a list of offered protocols as bytestrings, e.g `[b'http/1.1', b'spdy/2']`. It can return one of those bytestrings to indicate the chosen protocol, the empty bytestring to terminate the TLS connection, or the `NO_OVERLAPPING_PROTOCOLS` to indicate that no offered protocol was selected, but that the connection should not be aborted.

  set_app_data(data: Any) → None

    Set the application data (will be returned from get_app_data())

    Parameters:

      data – Any Python object

    Returns:

      None

  set_cipher_list(cipher_list: bytes) → None

    Set the list of ciphers to be used in this context.

    See the OpenSSL manual for more information (e.g. ciphers(1)).

    Note this API does not change the cipher suites used in TLS 1.3 Use set_tls13_ciphersuites for that.

    Parameters:

      cipher_list (bytes) – An OpenSSL cipher string.

    Returns:

      None

  set_client_ca_list(certificate_authorities: Sequence[X509Name]) → None

    Set the list of preferred client certificate signers for this server context.

    This list of certificate authorities will be sent to the client when the server requests a client certificate.

    Parameters:

      certificate_authorities – a sequence of X509Names.

    Returns:

      None

    Added in version 0.10.

  set_default_verify_paths() → None

    Specify that the platform provided CA certificates are to be used for verification purposes. This method has some caveats related to the binary wheels that cryptography (pyOpenSSL’s primary dependency) ships:

    - macOS will only load certificates using this method if the user has the `openssl@3` Homebrew formula installed in the default location.

    - Windows will not work.

    - manylinux cryptography wheels will work on most common Linux distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the manylinux wheel and attempts to load roots via a fallback path.

    Returns:

      None

  set_info_callback(callback: Callable[[Connection, int, int], None]) → None

    Set the information callback to callback. This function will be called from time to time during SSL handshakes.

    Parameters:

      callback – The Python callback to use. This should take three arguments: a Connection object and two integers. The first integer specifies where in the SSL handshake the function was called, and the other the return code from a (possibly failed) internal function call.

    Returns:

      None

  set_keylog_callback(callback: Callable[[Connection, bytes], None]) → None

    Set the TLS key logging callback to callback. This function will be called whenever TLS key material is generated or received, in order to allow applications to store this keying material for debugging purposes.

    Parameters:

      callback – The Python callback to use. This should take two arguments: a Connection object and a bytestring that contains the key material in the format used by NSS for its SSLKEYLOGFILE debugging output.

    Returns:

      None

  set_max_proto_version(version: int) → None

    Set the maximum supported protocol version. Setting the maximum version to 0 will enable protocol versions up to the highest version supported by the library.

    If the underlying OpenSSL build is missing support for the selected version, this method will raise an exception.

  set_min_proto_version(version: int) → None

    Set the minimum supported protocol version. Setting the minimum version to 0 will enable protocol versions down to the lowest version supported by the library.

    If the underlying OpenSSL build is missing support for the selected version, this method will raise an exception.

  set_mode(mode: int) → int

    Add modes via bitmask. Modes set before are not cleared! This method should be used with the `MODE_*` constants.

    Parameters:

      mode – The mode to add.

    Returns:

      The new mode bitmask.

  set_ocsp_client_callback(callback: Callable[[Connection, bytes, _T | None], bool], data: _T | None = None) → None

    Set a callback to validate OCSP data stapled to the TLS handshake on the client side.

    Parameters:

      - callback – The callback function. It will be invoked with three arguments: the Connection, a bytestring containing the stapled OCSP assertion, and the optional arbitrary data you have provided. The callback must return a boolean that indicates the result of validating the OCSP data: `True` if the OCSP data is valid and the certificate can be trusted, or `False` if either the OCSP data is invalid or the certificate has been revoked.

      - data – Some opaque data that will be passed into the callback function when called. This can be used to avoid needing to do complex data lookups or to keep track of what context is being used. This parameter is optional.

  set_ocsp_server_callback(callback: Callable[[Connection, _T | None], bytes], data: _T | None = None) → None

    Set a callback to provide OCSP data to be stapled to the TLS handshake on the server side.

    Parameters:

      - callback – The callback function. It will be invoked with two arguments: the Connection, and the optional arbitrary data you have provided. The callback must return a bytestring that contains the OCSP data to staple to the handshake. If no OCSP data is available for this connection, return the empty bytestring.

      - data – Some opaque data that will be passed into the callback function when called. This can be used to avoid needing to do complex data lookups or to keep track of what context is being used. This parameter is optional.

  set_options(options: int) → int

    Add options. Options set before are not cleared! This method should be used with the `OP_*` constants.

    Parameters:

      options – The options to add.

    Returns:

      The new option bitmask.

  set_passwd_cb(callback: Callable[[int, bool, _T | None], bytes], userdata: _T | None = None) → None

    Set the passphrase callback. This function will be called when a private key with a passphrase is loaded.

    Parameters:

      - callback – The Python callback to use. This must accept three positional arguments. First, an integer giving the maximum length of the passphrase it may return. If the returned passphrase is longer than this, it will be truncated. Second, a boolean value which will be true if the user should be prompted for the passphrase twice and the callback should verify that the two values supplied are equal. Third, the value given as the userdata parameter to `set_passwd_cb()`. The callback must return a byte string. If an error occurs, callback should return a false value (e.g. an empty string).

      - userdata – (optional) A Python object which will be given as argument to the callback

    Returns:

      None

  set_session_cache_mode(mode: int) → int

    Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See `SESS_CACHE_*` for details about particular modes.

    Parameters:

      mode – One or more of the SESS_CACHE_* flags (combine using bitwise or)

    Returns:

      The previously set caching mode.

    Added in version 0.14.

  set_session_id(buf: bytes) → None

    Set the session id to buf within which a session can be reused for this Context object. This is needed when doing session resumption, because there is no way for a stored session to know which Context object it is associated with.

    Parameters:

      buf (bytes) – The session id.

    Returns:

      None

  set_timeout(timeout: int) → None

    Set the timeout for newly created sessions for this Context object to timeout. The default value is 300 seconds. See the OpenSSL manual for more information (e.g. SSL_CTX_set_timeout(3)).

    Parameters:

      timeout – The timeout in (whole) seconds

    Returns:

      The previous session timeout

  set_tls13_ciphersuites(ciphersuites: bytes) → None

    Set the list of TLS 1.3 ciphers to be used in this context. OpenSSL maintains a separate list of TLS 1.3+ ciphers to ciphers for TLS 1.2 and lowers.

    See the OpenSSL manual for more information (e.g. ciphers(1)).

    Parameters:

      ciphersuites (bytes) – An OpenSSL cipher string containing TLS 1.3+ ciphersuites.

    Returns:

      None

    Added in version 25.2.0.

  set_tlsext_servername_callback(callback: Callable[[Connection], None]) → None

    Specify a callback function to be called when clients specify a server name.

    Parameters:

      callback – The callback function. It will be invoked with one argument, the Connection instance.

    Added in version 0.13.

  set_tlsext_use_srtp(profiles: bytes) → None

    Enable support for negotiating SRTP keying material.

    Parameters:

      profiles (bytes) – A colon delimited list of protection profile names, like `b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'`.

    Returns:

      None

  set_tmp_ecdh(curve: _EllipticCurve | EllipticCurve) → None

    Select a curve to use for ECDHE key exchange.

    Parameters:

      curve – A curve instance from cryptography (`EllipticCurve`). Alternatively (deprecated) a curve object from either `OpenSSL.crypto.get_elliptic_curve()` or `OpenSSL.crypto.get_elliptic_curves()`.

    Returns:

      None

  set_verify(mode: int, callback: Callable[[Connection, X509, int, int, int], bool] | None = None) → None

    Set the verification flags for this Context object to mode and specify that callback should be used for verification callbacks.

    Parameters:

      - mode – The verify mode, this should be one of `VERIFY_NONE` and `VERIFY_PEER`. If `VERIFY_PEER` is used, mode can be OR:ed with `VERIFY_FAIL_IF_NO_PEER_CERT` and `VERIFY_CLIENT_ONCE` to further control the behaviour.

      - callback – The optional Python verification callback to use. This should take five arguments: A Connection object, an X509 object, and three integer variables, which are in turn potential error number, error depth and return code. callback should return True if verification passes and False otherwise. If omitted, OpenSSL’s default verification is used.

    Returns:

      None

    See SSL_CTX_set_verify(3SSL) for further details.

  set_verify_depth(depth: int) → None

    Set the maximum depth for the certificate chain verification that shall be allowed for this Context object.

    Parameters:

      depth – An integer specifying the verify depth

    Returns:

      None

  use_certificate(cert: X509 | Certificate) → None

    Load a certificate from a X509 object

    Parameters:

      cert – The X509 object

    Returns:

      None

  use_certificate_chain_file(certfile: str | bytes | PathLike[str] | PathLike[bytes]) → None

    Load a certificate chain from a file.

    Parameters:

      certfile – The name of the certificate chain file (`bytes` or `str`). Must be PEM encoded.

    Returns:

      None

  use_certificate_file(certfile: str | bytes | PathLike[str] | PathLike[bytes], filetype: int = 1) → None

    Load a certificate from a file

    Parameters:

      - certfile – The name of the certificate file (`bytes` or `str`).

      - filetype – (optional) The encoding of the file, which is either `FILETYPE_PEM` or `FILETYPE_ASN1`. The default is `FILETYPE_PEM`.

    Returns:

      None

  use_privatekey(pkey: DSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey | Ed448PrivateKey | RSAPrivateKey | PKey) → None

    Load a private key from a PKey object

    Parameters:

      pkey – The PKey object

    Returns:

      None

  use_privatekey_file(keyfile: str | bytes | PathLike[str] | PathLike[bytes], filetype: int = 1) → None

    Load a private key from a file

    Parameters:

      - keyfile – The name of the key file (`bytes` or `str`)

      - filetype – (optional) The encoding of the file, which is either `FILETYPE_PEM` or `FILETYPE_ASN1`. The default is `FILETYPE_PEM`.

    Returns:

      None

## Session objects

Session objects have no methods.

## Connection objects

Connection objects have the following methods:

class OpenSSL.SSL.Connection(context: Context, socket: socket | None = None)
  DTLSv1_get_timeout() → int | None

    Determine when the DTLS SSL object next needs to perform internal processing due to the passage of time.

    When the returned number of seconds have passed, the `DTLSv1_handle_timeout()` method needs to be called.

    Returns:

      The time left in seconds before the next timeout or None if no timeout is currently active.

  DTLSv1_handle_timeout() → bool

    Handles any timeout events which have become pending on a DTLS SSL object.

    Returns:

      True if there was a pending timeout, False otherwise.

  DTLSv1_listen() → None

    Call the OpenSSL function DTLSv1_listen on this connection. See the OpenSSL manual for more details.

    Returns:

      None

  accept() → tuple[Connection, Any]

    Call the `accept()` method of the underlying socket and set up SSL on the returned socket, using the Context object supplied to this `Connection` object at creation.

    Returns:

      A (conn, addr) pair where conn is the new `Connection` object created, and address is as returned by the socket’s `accept()`.

  bio_read(bufsiz: int) → bytes

    If the Connection was created with a memory BIO, this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions.

    Parameters:

      bufsiz – The maximum number of bytes to read

    Returns:

      The string read.

  bio_shutdown() → None

    If the Connection was created with a memory BIO, this method can be used to indicate that end of file has been reached on the read end of that memory BIO.

    Returns:

      None

  bio_write(buf: bytes | bytearray | memoryview) → int

    If the Connection was created with a memory BIO, this method can be used to add bytes to the read end of that memory BIO. The Connection can then read the bytes (for example, in response to a call to `recv()`).

    Parameters:

      buf – The string to put into the memory BIO.

    Returns:

      The number of bytes written

  client_random() → bytes | None

    Retrieve the random value used with the client hello message.

    Returns:

      A string representing the state

  connect(addr: Any) → None

    Call the `connect()` method of the underlying socket and set up SSL on the socket, using the `Context` object supplied to this `Connection` object at creation.

    Parameters:

      addr – A remote address

    Returns:

      What the socket’s connect method returns

  connect_ex(addr: Any) → int

    Call the `connect_ex()` method of the underlying socket and set up SSL on the socket, using the Context object supplied to this Connection object at creation. Note that if the `connect_ex()` method of the socket doesn’t return 0, SSL won’t be initialized.

    Parameters:

      addr – A remove address

    Returns:

      What the socket’s connect_ex method returns

  do_handshake() → None

    Perform an SSL handshake (usually called after `renegotiate()` or one of `set_accept_state()` or `set_connect_state()`). This can raise the same exceptions as `send()` and `recv()`.

    Returns:

      None.

  export_keying_material(label: bytes, olen: int, context: bytes | None = None) → bytes

    Obtain keying material for application use.

    Param:

      label - a disambiguating label string as described in RFC 5705

    Param:

      olen - the length of the exported key material in bytes

    Param:

      context - a per-association context value

    Returns:

      the exported key material bytes or None

  get_alpn_proto_negotiated() → bytes

    Get the protocol that was negotiated by ALPN.

    Returns:

      A bytestring of the protocol name. If no protocol has been negotiated yet, returns an empty bytestring.

  get_app_data() → Any

    Retrieve application data as set by `set_app_data()`.

    Returns:

      The application data

  get_certificate(*, as_cryptography: Literal[True]) → Certificate | None
  get_certificate(*, as_cryptography: Literal[False] = False) → X509 | None

    Retrieve the local certificate (if any)

    Parameters:

      as_cryptography (bool) – Controls whether a `cryptography.x509.Certificate` or an `OpenSSL.crypto.X509` object should be returned.

    Returns:

      The local certificate

  get_cipher_bits() → int | None

    Obtain the number of secret bits of the currently used cipher.

    Returns:

      The number of secret bits of the currently used cipher or `None` if no connection has been established.

    Added in version 0.15.

  get_cipher_list() → list[str]

    Retrieve the list of ciphers used by the Connection object.

    Returns:

      A list of native cipher strings.

  get_cipher_name() → str | None

    Obtain the name of the currently used cipher.

    Returns:

      The name of the currently used cipher or `None` if no connection has been established.

    Added in version 0.15.

  get_cipher_version() → str | None

    Obtain the protocol version of the currently used cipher.

    Returns:

      The protocol name of the currently used cipher or `None` if no connection has been established.

    Added in version 0.15.

  get_cleartext_mtu() → int

    For DTLS, get the maximum size of unencrypted data you can pass to `write()` without exceeding the MTU (as passed to `set_ciphertext_mtu()`).

    Returns:

      The effective MTU as an integer.

    Added in version 21.1.

  get_client_ca_list(*, as_cryptography: Literal[True]) → list[Name]
  get_client_ca_list(*, as_cryptography: Literal[False] = False) → list[X509Name]

    Get CAs whose certificates are suggested for client authentication.

    Parameters:

      as_cryptography (bool) – Controls whether a list of `cryptography.x509.Name` or `OpenSSL.crypto.X509Name` objects should be returned.

    Returns:

      If this is a server connection, the list of certificate authorities that will be sent or has been sent to the client, as controlled by this `Connection`’s `Context`.

      If this is a client connection, the list will be empty until the connection with the server is established.

    Added in version 0.10.

  get_context() → Context

    Retrieve the `Context` object associated with this `Connection`.

  get_finished() → bytes | None

    Obtain the latest TLS Finished message that we sent.

    Returns:

      The contents of the message or `None` if the TLS handshake has not yet completed.

    Added in version 0.15.

  get_group_name() → str | None

    Get the name of the negotiated group for the key exchange.

    Returns:

      A string giving the group name or `None`.

  get_peer_cert_chain(*, as_cryptography: Literal[True]) → list[Certificate] | None
  get_peer_cert_chain(*, as_cryptography: Literal[False] = False) → list[X509] | None

    Retrieve the other side’s certificate (if any)

    Parameters:

      as_cryptography (bool) – Controls whether a list of `cryptography.x509.Certificate` or `OpenSSL.crypto.X509` object should be returned.

    Returns:

      A list of X509 instances giving the peer’s certificate chain, or None if it does not have one.

  get_peer_certificate(*, as_cryptography: Literal[True]) → Certificate | None
  get_peer_certificate(*, as_cryptography: Literal[False] = False) → X509 | None

    Retrieve the other side’s certificate (if any)

    Parameters:

      as_cryptography (bool) – Controls whether a `cryptography.x509.Certificate` or an `OpenSSL.crypto.X509` object should be returned.

    Returns:

      The peer’s certificate

  get_peer_finished() → bytes | None

    Obtain the latest TLS Finished message that we received from the peer.

    Returns:

      The contents of the message or `None` if the TLS handshake has not yet completed.

    Added in version 0.15.

  get_protocol_version() → int

    Retrieve the SSL or TLS protocol version of the current connection.

    Returns:

      The TLS version of the current connection. For example, it will return `0x769` for connections made over TLS version 1.

  get_protocol_version_name() → str

    Retrieve the protocol version of the current connection.

    Returns:

      The TLS version of the current connection, for example the value for TLS 1.2 would be `TLSv1.2``or ``Unknown` for connections that were not successfully established.

  get_selected_srtp_profile() → bytes

    Get the SRTP protocol which was negotiated.

    Returns:

      A bytestring of the SRTP profile name. If no profile has been negotiated yet, returns an empty bytestring.

  get_servername() → bytes | None

    Retrieve the servername extension value if provided in the client hello message, or None if there wasn’t one.

    Returns:

      A byte string giving the server name or `None`.

    Added in version 0.13.

  get_session() → Session | None

    Returns the Session currently used.

    Returns:

      An instance of `OpenSSL.SSL.Session` or `None` if no session exists.

    Added in version 0.14.

  get_shutdown() → int

    Get the shutdown state of the Connection.

    Returns:

      The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.

  get_state_string() → bytes

    Retrieve a verbose string detailing the state of the Connection.

    Returns:

      A string representing the state

  get_verified_chain(*, as_cryptography: Literal[True]) → list[Certificate] | None
  get_verified_chain(*, as_cryptography: Literal[False] = False) → list[X509] | None

    Retrieve the verified certificate chain of the peer including the peer’s end entity certificate. It must be called after a session has been successfully established. If peer verification was not successful the chain may be incomplete, invalid, or None.

    Parameters:

      as_cryptography (bool) – Controls whether a list of `cryptography.x509.Certificate` or `OpenSSL.crypto.X509` object should be returned.

    Returns:

      A list of X509 instances giving the peer’s verified certificate chain, or None if it does not have one.

    Added in version 20.0.

  get_verify_mode() → int

    Retrieve the Connection object’s verify mode, as set by `set_verify()`.

    Returns:

      The verify mode

  makefile(*args: Any, **kwargs: Any) → NoReturn

    The makefile() method is not implemented, since there is no dup semantics for SSL connections

    Raise:

      NotImplementedError

  master_key() → bytes | None

    Retrieve the value of the master key for this session.

    Returns:

      A string representing the state

  pending() → int

    Get the number of bytes that can be safely read from the SSL buffer (not the underlying transport buffer).

    Returns:

      The number of bytes available in the receive buffer.

  read(bufsiz: int, flags: int | None = None) → bytes

    Receive data on the connection.

    Parameters:

      - bufsiz – The maximum number of bytes to read

      - flags – (optional) The only supported flag is `MSG_PEEK`, all other flags are ignored.

    Returns:

      The string read from the Connection

  recv(bufsiz: int, flags: int | None = None) → bytes

    Receive data on the connection.

    Parameters:

      - bufsiz – The maximum number of bytes to read

      - flags – (optional) The only supported flag is `MSG_PEEK`, all other flags are ignored.

    Returns:

      The string read from the Connection

  recv_into(buffer: Any, nbytes: int | None = None, flags: int | None = None) → int

    Receive data on the connection and copy it directly into the provided buffer, rather than creating a new string.

    Parameters:

      - buffer – The buffer to copy into.

      - nbytes – (optional) The maximum number of bytes to read into the buffer. If not present, defaults to the size of the buffer. If larger than the size of the buffer, is reduced to the size of the buffer.

      - flags – (optional) The only supported flag is `MSG_PEEK`, all other flags are ignored.

    Returns:

      The number of bytes read into the buffer.

  renegotiate() → bool

    Renegotiate the session.

    Returns:

      True if the renegotiation can be started, False otherwise

  renegotiate_pending() → bool

    Check if there’s a renegotiation in progress, it will return False once a renegotiation is finished.

    Returns:

      Whether there’s a renegotiation in progress

  request_ocsp() → None

    Called to request that the server sends stapled OCSP data, if available. If this is not called on the client side then the server will not send OCSP data. Should be used in conjunction with `Context.set_ocsp_client_callback()`.

  send(buf: bytes | bytearray | memoryview, flags: int = 0) → int

    Send data on the connection. NOTE: If you get one of the WantRead, WantWrite or WantX509Lookup exceptions on this, you have to call the method again with the SAME buffer.

    Parameters:

      - buf – The string, buffer or memoryview to send

      - flags – (optional) Included for compatibility with the socket API, the value is ignored

    Returns:

      The number of bytes written

  sendall(buf: bytes | bytearray | memoryview, flags: int = 0) → int

    Send “all” data on the connection. This calls send() repeatedly until all data is sent. If an error occurs, it’s impossible to tell how much data has been sent.

    Parameters:

      - buf – The string, buffer or memoryview to send

      - flags – (optional) Included for compatibility with the socket API, the value is ignored

    Returns:

      The number of bytes written

  server_random() → bytes | None

    Retrieve the random value used with the server hello message.

    Returns:

      A string representing the state

  set_accept_state() → None

    Set the connection to work in server mode. The handshake will be handled automatically by read/write.

    Returns:

      None

  set_alpn_protos(protos: list[bytes]) → None

    Specify the client’s ALPN protocol list.

    These protocols are offered to the server during protocol negotiation.

    Parameters:

      protos – A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. `[b'http/1.1', b'spdy/2']`.

  set_app_data(data: Any) → None

    Set application data

    Parameters:

      data – The application data

    Returns:

      None

  set_ciphertext_mtu(mtu: int) → None

    For DTLS, set the maximum UDP payload size (not including IP/UDP overhead).

    Note that you might have to set `OP_NO_QUERY_MTU` to prevent OpenSSL from spontaneously clearing this.

    Parameters:

      mtu – An integer giving the maximum transmission unit.

    Added in version 21.1.

  set_connect_state() → None

    Set the connection to work in client mode. The handshake will be handled automatically by read/write.

    Returns:

      None

  set_context(context: Context) → None

    Switch this connection to a new session context.

    Parameters:

      context – A `Context` instance giving the new session context to use.

  set_info_callback(callback: Callable[[Connection, int, int], None]) → None

    Set the information callback to callback. This function will be called from time to time during SSL handshakes.

    Parameters:

      callback – The Python callback to use. This should take three arguments: a Connection object and two integers. The first integer specifies where in the SSL handshake the function was called, and the other the return code from a (possibly failed) internal function call.

    Returns:

      None

  set_options(options: int) → int

    Add options. Options set before are not cleared! This method should be used with the `OP_*` constants.

    Parameters:

      options – The options to add.

    Returns:

      The new option bitmask.

  set_session(session: Session) → None

    Set the session to be used when the TLS/SSL connection is established.

    The session must have been obtained, via `get_session()`, from a `Connection` that was using the same `Context` as this one. OpenSSL requires (but does not verify) that sessions only be re-used with a compatible `SSL_CTX`, so this is enforced here.

    Parameters:

      session – A Session instance representing the session to use.

    Returns:

      None

    Added in version 0.14.

  set_shutdown(state: int) → None

    Set the shutdown state of the Connection.

    Parameters:

      state – bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.

    Returns:

      None

  set_tlsext_host_name(name: bytes) → None

    Set the value of the servername extension to send in the client hello.

    Parameters:

      name – A byte string giving the name.

    Added in version 0.13.

  set_verify(mode: int, callback: Callable[[Connection, X509, int, int, int], bool] | None = None) → None

    Override the Context object’s verification flags for this specific connection. See `Context.set_verify()` for details.

  shutdown() → bool

    Send the shutdown message to the Connection.

    Returns:

      True if the shutdown completed successfully (i.e. both sides have sent closure alerts), False otherwise (in which case you call `recv()` or `send()` when the connection becomes readable/writeable).

  sock_shutdown(*args: Any, **kwargs: Any) → None

    Call the `shutdown()` method of the underlying socket. See shutdown(2).

    Returns:

      What the socket’s shutdown() method returns

  total_renegotiations() → int

    Find out the total number of renegotiations.

    Returns:

      The number of renegotiations.

  use_certificate(cert: X509 | Certificate) → None

    Load a certificate from a X509 object

    Parameters:

      cert – The X509 object

    Returns:

      None

  use_privatekey(pkey: DSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey | Ed448PrivateKey | RSAPrivateKey | PKey) → None

    Load a private key from a PKey object

    Parameters:

      pkey – The PKey object

    Returns:

      None

  want_read() → bool

    Checks if more data has to be read from the transport layer to complete an operation.

    Returns:

      True iff more data has to be read

  want_write() → bool

    Checks if there is data to write to the transport layer to complete an operation.

    Returns:

      True iff there is data to write

  write(buf: bytes | bytearray | memoryview, flags: int = 0) → int

    Send data on the connection. NOTE: If you get one of the WantRead, WantWrite or WantX509Lookup exceptions on this, you have to call the method again with the SAME buffer.

    Parameters:

      - buf – The string, buffer or memoryview to send

      - flags – (optional) Included for compatibility with the socket API, the value is ignored

    Returns:

      The number of bytes written

Footnotes

[1]

Actually, all that is required is an object that behaves like a socket, you could even use files, even though it’d be tricky to get the handshakes right!