SSL Package — M2Crypto documentation

# SSL Package

## `SSL` Package

exception `M2Crypto.SSL.` `SSLError`

  Bases: `exceptions.Exception`

exception `M2Crypto.SSL.` `SSLTimeoutError`

  Bases: `M2Crypto.SSL.SSLError`, `socket.timeout`

## `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.

exception `M2Crypto.SSL.Checker.` `SSLVerificationError`

  Bases: `exceptions.Exception`

exception `M2Crypto.SSL.Checker.` `NoCertificate`

  Bases: `M2Crypto.SSL.Checker.SSLVerificationError`

exception `M2Crypto.SSL.Checker.` `WrongCertificate`

  Bases: `M2Crypto.SSL.Checker.SSLVerificationError`

exception `M2Crypto.SSL.Checker.` `WrongHost`(expectedHost, actualHost, fieldName='commonName')

  Bases: `M2Crypto.SSL.Checker.SSLVerificationError`

class `M2Crypto.SSL.Checker.` `Checker`(host=None, peerCertHash=None, peerCertDigest='sha1')
  `numericIpMatch` = <_sre.SRE_Pattern object>

## `Cipher` Module

SSL Ciphers

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

class `M2Crypto.SSL.Cipher.` `Cipher`(cipher)
  `name`()
  `version`()

class `M2Crypto.SSL.Cipher.` `Cipher_Stack`(stack)

## `Connection` Module

class `M2Crypto.SSL.Connection.` `Connection`(ctx, sock=None, family=2)

  An SSL connection.

  `accept`()

    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`()

    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)
  `clear`()

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

  `clientPostConnectionCheck` = <M2Crypto.SSL.Checker.Checker instance>
  `close`()
  `connect`(addr)

    Overloading socket.connect()

    Parameters: | addr – addresses have various depending on their type

    :return:status of ssl_connect()

  `connect_ssl`()
  `fileno`()
  `get_cipher`()

    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=0)

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

  `get_ciphers`()

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

  `get_context`()

    Return the Context object associated with this connection.

  `get_default_session_timeout`()
  `get_peer_cert`()

    Return the peer certificate.

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

  `get_peer_cert_chain`()

    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`()
  `get_shutdown`()

    Get the current shutdown mode of the Connection.

  `get_socket_read_timeout`()
  `get_socket_write_timeout`()
  `get_state`()

    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`()

    Return the peer certificate verification depth.

  `get_verify_mode`()

    Return the peer certificate verification mode.

  `get_verify_result`()

    Return the peer certificate verification result.

  `get_version`()

    Return the TLS/SSL protocol version for this connection.

  `getpeername`()

    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`()

    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, optname, buflen=None)

    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=5)
  `m2_bio_free`()
  `m2_ssl_free`()
  `makefile`(mode='rb', bufsize=-1)
  `pending`()

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

  `read`(size=1024)
  `recv`(size=1024)
  `recv_into`(buff, nbytes=0)

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

    @param buffer: a buffer for the received bytes @param nbytes: maximum number of bytes to read @return: number of bytes added

    See recv() for documentation about the flags.

  `renegotiate`()

    Renegotiate this connection’s SSL parameters.

  `send`(data)
  `sendall`(data)
  `serverPostConnectionCheck`(*args, **kw)
  `set_accept_state`()

    Sets Connection to work in the server mode.

  `set_bio`(readbio, writebio)

    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)

    Set the cipher suites for this connection.

  `set_client_CA_list_from_context`()

    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)

    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`()

    Sets Connection to work in the client mode.

  `set_post_connection_check_callback`(postConnectionCheck)
  `set_session`(session)
  `set_session_id_ctx`(id)
  `set_shutdown`(mode)

    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)
  `set_socket_write_timeout`(timeo)
  `set_ssl_close_flag`(flag)

    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)

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

  `setblocking`(mode)

    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, optname, value=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)

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

  `setup_addr`(addr)
  `setup_ssl`()
  `shutdown`(how)
  `ssl_get_error`(ret)
  `verify_ok`()
  `write`(data)

## `Context` Module

`M2Crypto.SSL.Context.` `ctxmap`()

class `M2Crypto.SSL.Context.` `Context`(protocol='tls', weak_crypto=None, post_connection_check=None)

  ‘Context’ for SSL connections.

  `add_session`(session)

    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`()
  `get_allow_unknown_ca`()

    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`()

    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`()

    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`()

    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`()

    Returns the verification mode currently set in the SSL Context.

  `get_verify_mode`()
  `load_cert`(certfile, keyfile=None, callback=<function passphrase_callback>)

    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, keyfile=None, callback=<function passphrase_callback>)

    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)

    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)

    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=None, capath=None)

    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=None, capath=None)

    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.

  `m2_ssl_ctx_free`()
  `remove_session`(session)

    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)

    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)

    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)

    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`()

    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=<function ssl_info_callback>)

    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)

    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)

    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)

    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)

    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)

    Load ephemeral DH parameters into the context.

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

  `set_tmp_dh_callback`(callback=None)

    Sets the callback function for SSL.Context.

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

  `set_tmp_rsa`(rsa)

    Load ephemeral RSA key into the context.

    Parameters: | rsa – RSA.RSA instance.

  `set_tmp_rsa_callback`(callback=None)

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

  `set_verify`(mode, depth, callback=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.` `map`()

## `SSLServer` Module

class `M2Crypto.SSL.SSLServer.` `SSLServer`(server_address, RequestHandlerClass, ssl_context, bind_and_activate=True)

  Bases: `SocketServer.TCPServer`

  `handle_error`(request, client_address)
  `handle_request`()

class `M2Crypto.SSL.SSLServer.` `ForkingSSLServer`(server_address, RequestHandlerClass, ssl_context, bind_and_activate=True)

  Bases: `SocketServer.ForkingMixIn`, `M2Crypto.SSL.SSLServer.SSLServer`

class `M2Crypto.SSL.SSLServer.` `ThreadingSSLServer`(server_address, RequestHandlerClass, ssl_context, bind_and_activate=True)

  Bases: `SocketServer.ThreadingMixIn`, `M2Crypto.SSL.SSLServer.SSLServer`

## `Session` Module

SSL Session

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

class `M2Crypto.SSL.Session.` `Session`(session, _pyfree=0)
  `as_der`()
  `as_text`()
  `get_time`()
  `get_timeout`()
  `m2_ssl_session_free`()
  `set_time`(t)
  `set_timeout`(t)
  `write_bio`(bio)

`M2Crypto.SSL.Session.` `load_session`(pemfile)

## `TwistedProtocolWrapper` Module

Make Twisted use M2Crypto for SSL

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

FIXME THIS HAS NOT BEEN FINISHED. NEITHER PEP484 NOR PORT PYTHON3 HAS BEEN FINISHED. THE FURTHER WORK WILL BE DONE WHEN THE STATUS OF TWISTED IN THE PYTHON 3 (AND ASYNCIO) WORLD WILL BE CLEAR.

`M2Crypto.SSL.TwistedProtocolWrapper.` `connectSSL`(host, port, factory, contextFactory, timeout=30, bindAddress=None, reactor=<twisted.internet.epollreactor.EPollReactor object>, postConnectionCheck=<M2Crypto.SSL.Checker.Checker instance>)

  A convenience function to start an SSL/TLS connection using Twisted.

  See IReactorSSL interface in Twisted.

`M2Crypto.SSL.TwistedProtocolWrapper.` `connectTCP`(host, port, factory, timeout=30, bindAddress=None, reactor=<twisted.internet.epollreactor.EPollReactor object>, postConnectionCheck=<M2Crypto.SSL.Checker.Checker instance>)

  A convenience function to start a TCP connection using Twisted.

  NOTE: You must call startTLS(ctx) to go into SSL/TLS mode.

  See IReactorTCP interface in Twisted.

`M2Crypto.SSL.TwistedProtocolWrapper.` `listenSSL`(port, factory, contextFactory, backlog=5, interface='', reactor=<twisted.internet.epollreactor.EPollReactor object>, postConnectionCheck=<function _alwaysSucceedsPostConnectionCheck>)

  A convenience function to listen for SSL/TLS connections using Twisted.

  See IReactorSSL interface in Twisted.

`M2Crypto.SSL.TwistedProtocolWrapper.` `listenTCP`(port, factory, backlog=5, interface='', reactor=<twisted.internet.epollreactor.EPollReactor object>, postConnectionCheck=None)

  A convenience function to listen for TCP connections using Twisted.

  NOTE: You must call startTLS(ctx) to go into SSL/TLS mode.

  See IReactorTCP interface in Twisted.

class `M2Crypto.SSL.TwistedProtocolWrapper.` `TLSProtocolWrapper`(factory, wrappedProtocol, startPassThrough, client, contextFactory, postConnectionCheck)

  Bases: `twisted.protocols.policies.ProtocolWrapper`

  A SSL/TLS protocol wrapper to be used with Twisted. Typically you would not use this class directly. Use connectTCP, connectSSL, listenTCP, listenSSL functions defined above, which will hook in this class.

  `clear`()

    Clear this instance, after which it is ready for reuse.

  `connectionLost`(reason)
  `connectionMade`()
  `dataReceived`(data)
  `loseConnection`()
  `startTLS`(ctx)

    Start SSL/TLS. If this is not called, this instance just passes data through untouched.

  `write`(data)
  `writeSequence`(data)

## `cb` Module

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

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

`M2Crypto.SSL.cb.` `ssl_verify_callback_allow_unknown_ca`(ok, store)

`M2Crypto.SSL.cb.` `ssl_info_callback`(where, ret, ssl_ptr)

## `ssl_dispatcher` Module

class `M2Crypto.SSL.ssl_dispatcher.` `ssl_dispatcher`(sock=None, map=None)

  Bases: `asyncore.dispatcher`

  `connect`(addr)
  `create_socket`(ssl_context)
  `recv`(buffer_size=4096)

    Receive data over SSL.

  `send`(buffer)

    Send data over SSL.

## `timeout` Module

Support for SSL socket timeouts.

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

Copyright 2008 Heikki Toivonen. All rights reserved.

class `M2Crypto.SSL.timeout.` `timeout`(sec=600, microsec=0)
  `pack`()

`M2Crypto.SSL.timeout.` `struct_to_timeout`(binstr)

`M2Crypto.SSL.timeout.` `struct_size`()