# SSL Package

## `SSL` Package

M2Crypto SSL services.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

## `Checker` Module

SSL peer certificate checking routines

Copyright (c) 2004-2007 Open Source Applications Foundation. All rights reserved.

Copyright 2008 Heikki Toivonen. All rights reserved.

class M2Crypto.SSL.Checker.Checker(host: str | None = None, peerCertHash: bytes | None = None, peerCertDigest: str = 'sha256')

  Bases: `object`

  numericIpMatch: Pattern[str] = re.compile('^[0-9]+(\\.[0-9]+)*$')

exception M2Crypto.SSL.Checker.NoCertificate

  Bases: `SSLVerificationError`

exception M2Crypto.SSL.Checker.SSLVerificationError

  Bases: `Exception`

exception M2Crypto.SSL.Checker.WrongCertificate

  Bases: `SSLVerificationError`

exception M2Crypto.SSL.Checker.WrongHost(expectedHost: str, actualHost: str | bytes, fieldName: str = 'commonName')

  Bases: `SSLVerificationError`

## `Cipher` Module

SSL Ciphers

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.SSL.Cipher.Cipher(cipher: SSL_CIPHER, _pyfree: int = 0)

  Bases: `object`

  cipher: SSL_CIPHER
  name() → str
  version() → str

class M2Crypto.SSL.Cipher.Cipher_Stack(stack: List[SSL_CIPHER], _pyfree: int = 0)

  Bases: `object`

  stack: List[SSL_CIPHER]

## `Connection` Module

SSL Connection aka socket

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2004-2007 OSAF. All Rights Reserved.

Copyright 2008 Heikki Toivonen. All rights reserved.

class M2Crypto.SSL.Connection.Connection(ctx: Context, sock: socket | None = None, family: int = AddressFamily.AF_INET)

  Bases: `object`

  An SSL connection.

  accept() → Tuple[Connection, Tuple[str, int] | str]

    Accept an SSL connection.

    The return value is a pair (ssl, addr) where ssl is a new SSL connection object and addr is the address bound to the other end of the SSL connection.

    Returns:

      tuple of Connection and addr. Address can take very various forms (see socket documentation), for IPv4 it is tuple(str, int), for IPv6 a tuple of four (host, port, flowinfo, scopeid), where the last two are optional ints.

  accept_ssl() → int | None

    Waits for a TLS/SSL client to initiate the TLS/SSL handshake.

    The communication channel must already have been set and assigned to the ssl by setting an underlying BIO.

    Returns:

      0 The TLS/SSL handshake was not successful but was shut

        down controlled and by the specifications of the TLS/SSL protocol. Call get_error() with the return value ret to find out the reason.

      1 The TLS/SSL handshake was successfully completed,

        a TLS/SSL connection has been established.

      <0 The TLS/SSL handshake was not successful because

        a fatal error occurred either at the protocol level or a connection failure occurred. The shutdown was not clean. It can also occur of action is need to continue the operation for non-blocking BIOs. Call get_error() with the return value ret to find out the reason.

  bind(addr: Tuple[str, int] | str) → None
  clear() → int

    If there were errors in this connection, call clear() rather than close() to end it, so that bad sessions will be cleared from cache.

  close(freeBio: bool | None = True) → None

    if freeBio is true, call _free_bio

  property closed: bool
  connect(addr: Tuple[str, int] | str) → int | None

    Overloading socket.connect()

    Parameters:

      addr – addresses have various depending on their type

    :return:status of ssl_connect()

  connect_ssl() → int | None
  fileno() → int
  flush() → None
  get_cipher() → Cipher | None

    Return an M2Crypto.SSL.Cipher object for this connection; if the connection has not been initialised with a cipher suite, return None.

  get_cipher_list(idx: int = 0) → str

    Return the cipher suites for this connection as a string object.

  get_ciphers() → Cipher_Stack | None

    Return an M2Crypto.SSL.Cipher_Stack object for this connection; if the connection has not been initialised with cipher suites, return None.

  get_context() → Context

    Return the Context object associated with this connection.

  get_default_session_timeout() → int
  get_peer_cert() → X509 | None

    Return the peer certificate.

    If the peer did not provide a certificate, return None.

  get_peer_cert_chain() → X509_Stack | None

    Return the peer certificate chain; if the peer did not provide a certificate chain, return None.

    Warning:

      The returned chain will be valid only for as long as the connection object is alive. Once the connection object gets freed, the chain will be freed as well.

  get_session() → Session | None
  get_shutdown() → int

    Get the current shutdown mode of the Connection.

  get_socket_read_timeout() → timeout
  get_socket_write_timeout() → timeout
  get_state() → str

    Return the SSL state of this connection.

    During its use, an SSL objects passes several states. The state is internally maintained. Querying the state information is not very informative before or when a connection has been established. It however can be of significant interest during the handshake.

    Returns:

      6 letter string indicating the current state of the SSL object ssl.

  get_verify_depth() → int

    Return the peer certificate verification depth.

  get_verify_mode() → int

    Return the peer certificate verification mode.

  get_verify_result() → int

    Return the peer certificate verification result.

  get_version() → str

    Return the TLS/SSL protocol version for this connection.

  getpeername() → Tuple[str, int] | str

    Return the remote address to which the socket is connected.

    This is useful to find out the port number of a remote IPv4/v6 socket, for instance. On some systems this function is not supported.

    Returns:

  getsockname() → Tuple[str, int] | str

    Return the socket’s own address.

    This is useful to find out the port number of an IPv4/v6 socket, for instance. The format of the address returned depends on the address family – see above.)

    :return:socket’s address as addr type

  getsockopt(level: int, optname: int, buflen: int | None = None) → int | bytes

    Get the value of the given socket option.

    Parameters:

      - level – level at which the option resides. To manipulate options at the sockets API level, level is specified as socket.SOL_SOCKET. To manipulate options at any other level the protocol number of the appropriate protocol controlling the option is supplied. For example, to indicate that an option is to be interpreted by the TCP protocol, level should be set to the protocol number of socket.SOL_TCP; see getprotoent(3).

      - optname – The value of the given socket option is described in the Unix man page getsockopt(2)). The needed symbolic constants (SO_* etc.) are defined in the socket module.

      - buflen – If it is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a bytes object.

    Returns:

      Either integer or bytes value of the option. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as byte strings).

  listen(qlen: int = 5) → None
  static m2_bio_free(bio: BIO) → int
  m2_bio_noclose = 0
  static m2_ssl_free(ssl: SSL) → None
  makefile(mode: str = 'rb', bufsize: int = -1) → BufferedRWPair | BufferedReader | BufferedWriter
  pending() → int

    Return the numbers of octets that can be read from the connection.

  read(size: int = 1024) → bytes
  readable() → bool
  readinto(b: bytearray) → int
  recv(size: int = 1024) → bytes
  recv_into(buff: bytearray | memoryview, nbytes: int = 0) → int

    A version of recv() that stores its data into a buffer rather than creating a new string. Receive up to nbytes bytes from the socket. If nbytes is not specified (or 0), receive up to the size available in the given buffer.

    If buff is bytearray, it will have after return length of the actually returned number of bytes. If buff is memoryview, then the size of buff won’t change (it cannot), but all bytes after the number of returned bytes will be NULL.

    Parameters:

      - buffer – a buffer for the received bytes

      - nbytes – maximum number of bytes to read

    Returns:

      number of bytes read

    See recv() for documentation about the flags.

  renegotiate() → int

    Renegotiate this connection’s SSL parameters.

  send(data: bytes) → int
  sendall(data: bytes) → int
  set1_host(name: bytes) → None

    Set the requested hostname to check in the server certificate.

  set_accept_state() → None

    Sets Connection to work in the server mode.

  set_bio(readbio: BIO, writebio: BIO) → None

    Explicitly set read and write bios

    Connects the BIOs for the read and write operations of the TLS/SSL (encrypted) side of ssl.

    The SSL engine inherits the behaviour of both BIO objects, respectively. If a BIO is non-blocking, the Connection will also have non-blocking behaviour.

    If there was already a BIO connected to Connection, BIO_free() will be called (for both the reading and writing side, if different).

    Parameters:

      - readbio – BIO for reading

      - writebio – BIO for writing.

  set_cipher_list(cipher_list: str) → int

    Set the cipher suites for this connection.

  set_client_CA_list_from_context() → None

    Set the acceptable client CA list. If the client returns a certificate, it must have been issued by one of the CAs listed in context.

    Makes sense only for servers.

  set_client_CA_list_from_file(cafile: str) → None

    Set the acceptable client CA list.

    If the client returns a certificate, it must have been issued by one of the CAs listed in cafile.

    Makes sense only for servers.

    Parameters:

      cafile – Filename from which to load the CA list.

    Returns:

      0 A failure while manipulating the STACK_OF(X509_NAME)

        object occurred or the X509_NAME could not be extracted from cacert. Check the error stack to find out the reason.

      1 The operation succeeded.

  set_connect_state() → None

    Sets Connection to work in the client mode.

  set_post_connection_check_callback(postConnectionCheck: Callable) → None
  set_session(session: Session) → None
  set_session_id_ctx(id: bytes) → int
  set_shutdown(mode: int) → None

    Sets the shutdown state of the Connection to mode.

    The shutdown state of an ssl connection is a bitmask of (use m2.SSL_* constants):

    0 No shutdown setting, yet.

    SSL_SENT_SHUTDOWN

      A “close notify” shutdown alert was sent to the peer, the connection is being considered closed and the session is closed and correct.

    SSL_RECEIVED_SHUTDOWN

      A shutdown alert was received form the peer, either a normal “close notify” or a fatal error.

    SSL_SENT_SHUTDOWN and SSL_RECEIVED_SHUTDOWN can be set at the same time.

    Parameters:

      mode – set the mode bitmask.

  set_socket_read_timeout(timeo: timeout) → None
  set_socket_write_timeout(timeo: timeout) → None
  set_ssl_close_flag(flag: int) → None

    By default, SSL struct will be freed in __del__. Call with m2.bio_close to override this default.

    Parameters:

      flag – either m2.bio_close or m2.bio_noclose

  set_tlsext_host_name(name: str) → None

    Set the requested hostname for the SNI (Server Name Indication) extension.

  setblocking(mode: int) → None

    Set this connection’s underlying socket to _mode_.

    Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0.0); s.setblocking(1) is equivalent to s.settimeout(None).

    Parameters:

      mode – new mode to be set

  setsockopt(level: int, optname: int, value: int | bytes | None = None) → bytes | None

    Set the value of the given socket option.

    Parameters:

      - level – same as with getsockopt() above

      - optname – same as with getsockopt() above

      - value – an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module struct for a way to encode C structures as strings).

    Returns:

      None for success or the error handler for failure.

  settimeout(timeout: float) → None

    Set this connection’s underlying socket’s timeout to _timeout_.

  setup_addr(addr: Tuple[str, int] | str) → None
  setup_ssl() → None
  shutdown(how: int) → None
  ssl_get_error(ret: int) → int
  verify_ok() → bool
  writable() → bool
  write(data: bytes) → int

## `Context` Module

SSL Context

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

class M2Crypto.SSL.Context.Context(protocol: str = 'tls', weak_crypto: int | None = None, post_connection_check: Callable | None = None)

  Bases: `object`

  ‘Context’ for SSL connections.

  add_session(session: Session) → int

    Add the session to the context.

    Parameters:

      session – the session to be added.

    Returns:

      0 The operation failed. It was tried to add the same

        (identical) session twice.

      1 The operation succeeded.

  close() → None
  get_allow_unknown_ca() → int | bool

    Get the context’s setting that accepts/rejects a peer certificate if the certificate’s CA is unknown.

    FIXME 2Bconverted to bool

  get_cert_store() → X509_Store

    Get the certificate store associated with this context.

    Warning:

      The store is NOT refcounted, and as such can not be relied to be valid once the context goes away or is changed.

  get_session_cache_mode() → int

    Gets the current session caching.

    The mode is set to m2.SSL_SESS_CACHE_* constants.

    Returns:

      the previously set cache mode value.

  get_session_timeout() → int

    Get current session timeout.

    Whenever a new session is created, it is assigned a maximum lifetime. This lifetime is specified by storing the creation time of the session and the timeout value valid at this time. If the actual time is later than creation time plus timeout, the session is not reused.

    Due to this realization, all sessions behave according to the timeout value valid at the time of the session negotiation. Changes of the timeout value do not affect already established sessions.

    Expired sessions are removed from the internal session cache, whenever SSL_CTX_flush_sessions(3) is called, either directly by the application or automatically (see SSL_CTX_set_session_cache_mode(3))

    The default value for session timeout is decided on a per protocol basis, see SSL_get_default_timeout(3). All currently supported protocols have the same default timeout value of 300 seconds.

    SSL_CTX_set_timeout() returns the previously set timeout value.

    Returns:

      the currently set timeout value.

  get_verify_depth() → int

    Returns the verification mode currently set in the SSL Context.

  get_verify_mode() → int
  load_cert(certfile: str | bytes, keyfile: str | bytes | None = None, callback: ~typing.Callable = <function passphrase_callback>) → None

    Load certificate and private key into the context.

    Parameters:

      - certfile – File that contains the PEM-encoded certificate.

      - keyfile – File that contains the PEM-encoded private key. Default value of None indicates that the private key is to be found in ‘certfile’.

      - callback – Callable object to be invoked if the private key is passphrase-protected. Default callback provides a simple terminal-style input for the passphrase.

  load_cert_chain(certchainfile: str | bytes, keyfile: str | bytes | None = None, callback: ~typing.Callable = <function passphrase_callback>) → None

    Load certificate chain and private key into the context.

    Parameters:

      - certchainfile – File object containing the PEM-encoded certificate chain.

      - keyfile – File object containing the PEM-encoded private key. Default value of None indicates that the private key is to be found in ‘certchainfile’.

      - callback – Callable object to be invoked if the private key is passphrase-protected. Default callback provides a simple terminal-style input for the passphrase.

  load_client_CA(cafile: str | bytes) → None

    Load CA certs into the context. These CA certs are sent to the peer during SSLv3 certificate request.

    Parameters:

      cafile – File object containing one or more PEM-encoded CA certificates concatenated together.

  load_client_ca(cafile: str | bytes) → None

    Load CA certs into the context. These CA certs are sent to the peer during SSLv3 certificate request.

    Parameters:

      cafile – File object containing one or more PEM-encoded CA certificates concatenated together.

  load_verify_info(cafile: str | bytes | None = None, capath: str | bytes | None = None) → int

    Load CA certs into the context.

    These CA certs are used during verification of the peer’s certificate.

    Parameters:

      - cafile – File containing one or more PEM-encoded CA certificates concatenated together.

      - capath – Directory containing PEM-encoded CA certificates (one certificate per file).

    Returns:

      0 if the operation failed because CAfile and CApath are NULL

        or the processing at one of the locations specified failed. Check the error stack to find out the reason.

      1 The operation succeeded.

  load_verify_locations(cafile: str | bytes | None = None, capath: str | bytes | None = None) → int

    Load CA certs into the context.

    These CA certs are used during verification of the peer’s certificate.

    Parameters:

      - cafile – File containing one or more PEM-encoded CA certificates concatenated together.

      - capath – Directory containing PEM-encoded CA certificates (one certificate per file).

    Returns:

      0 if the operation failed because CAfile and CApath are NULL

        or the processing at one of the locations specified failed. Check the error stack to find out the reason.

      1 The operation succeeded.

  static m2_ssl_ctx_free(ctx: SSL_CTX) → None
  remove_session(session: Session) → int

    Remove the session from the context.

    Parameters:

      session – the session to be removed.

    Returns:

      0 The operation failed. The session was not found in

        the cache.

      1 The operation succeeded.

  set_allow_unknown_ca(ok: int | bool) → None

    Set the context to accept/reject a peer certificate if the certificate’s CA is unknown.

    Parameters:

      ok – True to accept, False to reject.

  set_cipher_list(cipher_list: str) → int

    Sets the list of available ciphers.

    Parameters:

      cipher_list – The format of the string is described in ciphers(1).

    Returns:

      1 if any cipher could be selected and 0 on complete failure.

  set_client_CA_list_from_file(cafile: str | bytes) → None

    Load CA certs into the context. These CA certs are sent to the peer during SSLv3 certificate request.

    Parameters:

      cafile – File object containing one or more PEM-encoded CA certificates concatenated together.

  set_default_verify_paths() → int

    Specifies that the default locations from which CA certs are loaded should be used.

    There is one default directory and one default file. The default CA certificates directory is called “certs” in the default OpenSSL directory. Alternatively the SSL_CERT_DIR environment variable can be defined to override this location. The default CA certificates file is called “cert.pem” in the default OpenSSL directory. Alternatively the SSL_CERT_FILE environment variable can be defined to override this location.

    @return 0 if the operation failed. A missing default location is

      > still treated as a success. No error code is set.

      1 The operation succeeded.

  set_info_callback(callback: ~typing.Callable = <function ssl_info_callback>) → None

    Set a callback function to get state information.

    It can be used to get state information about the SSL connections that are created from this context.

    Parameters:

      callback – Callback function. The default prints information to stderr.

  set_options(op: int) → int

    Adds the options set via bitmask in options to the Context.

    !!! Options already set before are not cleared!

    The behaviour of the SSL library can be changed by setting several options. The options are coded as bitmasks and can be combined by a logical or operation (|).

    SSL.Context.set_options() and SSL.set_options() affect the (external) protocol behaviour of the SSL library. The (internal) behaviour of the API can be changed by using the similar SSL.Context.set_mode() and SSL.set_mode() functions.

    During a handshake, the option settings of the SSL object are used. When a new SSL object is created from a context using SSL(), the current option setting is copied. Changes to ctx do not affect already created SSL objects. SSL.clear() does not affect the settings.

    Parameters:

      op – bitmask of additional options specified in SSL_CTX_set_options(3) manpage.

    Returns:

      the new options bitmask after adding options.

  set_session_cache_mode(mode: int) → int

    Enables/disables session caching.

    The mode is set by using m2.SSL_SESS_CACHE_* constants.

    Parameters:

      mode – new mode value.

    Returns:

      the previously set cache mode value.

  set_session_id_ctx(id: bytes) → None

    Sets the session id for the SSL.Context w/in a session can be reused.

    Parameters:

      id – Sessions are generated within a certain context. When exporting/importing sessions with i2d_SSL_SESSION/d2i_SSL_SESSION it would be possible, to re-import a session generated from another context (e.g. another application), which might lead to malfunctions. Therefore each application must set its own session id context sid_ctx which is used to distinguish the contexts and is stored in exported sessions. The sid_ctx can be any kind of binary data with a given length, it is therefore possible to use e.g. the name of the application and/or the hostname and/or service name.

  set_session_timeout(timeout: int) → int

    Set new session timeout.

    See self.get_session_timeout() for explanation of the session timeouts.

    Parameters:

      timeout – new timeout value.

    Returns:

      the previously set timeout value.

  set_tmp_dh(dhpfile: str | bytes) → int

    Load ephemeral DH parameters into the context.

    Parameters:

      dhpfile – Filename of the file containing the PEM-encoded DH parameters.

  set_tmp_dh_callback(callback: Callable | None = None) → None

    Sets the callback function for SSL.Context.

    Parameters:

      callback – Callable to be used when a DH parameters are required.

  set_tmp_rsa(rsa: RSA) → int

    Load ephemeral RSA key into the context.

    Parameters:

      rsa – RSA.RSA instance.

  set_tmp_rsa_callback(callback: Callable | None = None) → None

    Sets the callback function to be used when a temporary/ephemeral RSA key is required.

  set_verify(mode: int, depth: int, callback: Callable[[int, X509_STORE_CTX], int] | None = None) → None

    Set verify options. Most applications will need to call this method with the right options to make a secure SSL connection.

    Parameters:

      - mode – The verification mode to use. Typically at least SSL.verify_peer is used. Clients would also typically add SSL.verify_fail_if_no_peer_cert.

      - depth – The maximum allowed depth of the certificate chain returned by the peer.

      - callback – Callable that can be used to specify custom verification checks.

M2Crypto.SSL.Context.ctxmap() → _ctxmap

M2Crypto.SSL.Context.map() → _ctxmap

## `SSLServer` Module

SSLServer

Copyright (c) 1999-2002 Ng Pheng Siong. All rights reserved.

class M2Crypto.SSL.SSLServer.ForkingSSLServer(server_address: Tuple[str, int] | str, RequestHandlerClass: BaseRequestHandler, ssl_context: Context, bind_and_activate: bool = True)

  Bases: `ForkingMixIn`, `SSLServer`

class M2Crypto.SSL.SSLServer.SSLServer(server_address: Tuple[str, int] | str, RequestHandlerClass: BaseRequestHandler, ssl_context: Context, bind_and_activate: bool = True)

  Bases: `TCPServer`

  handle_error(request: socket | Connection | None, client_address: Tuple[str, int] | str | None) → None

    Handle an error gracefully. May be overridden.

    The default is to print a traceback and continue.

  handle_request() → None

    Handle one request, possibly blocking.

    Respects self.timeout.

  socket: Connection

class M2Crypto.SSL.SSLServer.ThreadingSSLServer(server_address: Tuple[str, int] | str, RequestHandlerClass: BaseRequestHandler, ssl_context: Context, bind_and_activate: bool = True)

  Bases: `ThreadingMixIn`, `SSLServer`

## `Session` Module

SSL Session

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.SSL.Session.Session(session, _pyfree: int = 0)

  Bases: `object`

  as_der() → bytes
  as_text() → bytes
  get_time() → int
  get_timeout() → int
  static m2_ssl_session_free(sess: SSL_SESSION) → None
  set_time(t: int) → int
  set_timeout(t: int) → int
  write_bio(bio: BIO) → int

M2Crypto.SSL.Session.load_session(pemfile: str | bytes) → Session

## `TwistedProtocolWrapper` Module

## `cb` Module

SSL callbacks

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

M2Crypto.SSL.cb.ssl_info_callback(where: int, ret: int, ssl_ptr: SSL) → None

M2Crypto.SSL.cb.ssl_verify_callback(ssl_ctx_ptr: SSL_CTX, x509_ptr: X509, errnum: int, errdepth: int, ok: int) → int

M2Crypto.SSL.cb.ssl_verify_callback_allow_unknown_ca(ok: int, store: X509_Store_Context) → int

  Callback that allows unknown CA errors. This version relies on a corrected SWIG typemap to receive a valid ‘store’ object.

M2Crypto.SSL.cb.ssl_verify_callback_stub(ssl_ctx_ptr, x509_ptr, errnum, errdepth, ok)

## `timeout` Module

Support for SSL socket timeouts.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

Copyright 2008 Heikki Toivonen. All rights reserved.

M2Crypto.SSL.timeout.struct_size() → int

M2Crypto.SSL.timeout.struct_to_timeout(binstr: bytes) → timeout

class M2Crypto.SSL.timeout.timeout(sec: int = 600, microsec: int = 0)

  Bases: `object`

  microsec: int
  pack() → bytes
  sec: int