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.SSLv2_METHOD
OpenSSL.SSL.SSLv3_METHOD
OpenSSL.SSL.SSLv23_METHOD
OpenSSL.SSL.TLSv1_METHOD

These constants represent the different SSL methods to use when creating a context object.

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_EPHEMERAL_RSA
OpenSSL.SSL.OP_NO_SSLv2
OpenSSL.SSL.OP_NO_SSLv3
OpenSSL.SSL.OP_NO_TLSv1

Constants used with set_options() of Context objects.

OP_SINGLE_DH_USE means to always create a new key when using ephemeral Diffie-Hellman. OP_EPHEMERAL_RSA means to always use ephemeral RSA keys when doing RSA operations. OP_NO_SSLv2, OP_NO_SSLv3 and OP_NO_TLSv1 means to disable those specific protocols. This is interesting if you’re using e.g. SSLv23_METHOD to get an SSLv2-compatible handshake, but don’t want to use SSLv2.

OpenSSL.SSL.SSLEAY_VERSION
OpenSSL.SSL.SSLEAY_CFLAGS
OpenSSL.SSL.SSLEAY_BUILT_ON
OpenSSL.SSL.SSLEAY_PLATFORM
OpenSSL.SSL.SSLEAY_DIR

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

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.SSLeay_version(type)

Retrieve a string describing some aspect of the underlying OpenSSL version. The type passed in should be one of the SSLEAY_* constants defined in this module.

OpenSSL.SSL.ContextType

See Context.

class OpenSSL.SSL.Context(method)

A class representing SSL contexts. Contexts define the parameters of one or more SSL connections.

method should be SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD or TLSv1_METHOD.

OpenSSL.SSL.ConnectionType

See Connection.

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:

Context.check_privatekey()

Check if the private key (loaded with use_privatekey()) matches the certificate (loaded with use_certificate()). Returns None if they match, raises Error otherwise.

Context.get_app_data()

Retrieve application data as set by set_app_data().

Context.get_cert_store()

Retrieve the certificate store (a X509Store object) that the context uses. This can be used to add “trusted” certificates without using the. load_verify_locations() method.

Context.get_timeout()

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

Context.get_verify_depth()

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

Context.get_verify_mode()

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

Context.load_client_ca(pemfile)

Read a file with PEM-formatted certificates that will be sent to the client when requesting a client certificate.

Context.set_client_ca_list(certificate_authorities)

Replace the current list of preferred certificate signers that would be sent to the client when requesting a client certificate with the certificate_authorities sequence of OpenSSL.crypto.X509Name‘s.

New in version 0.10.

Context.add_client_ca(certificate_authority)

Extract a OpenSSL.crypto.X509Name from the certificate_authority OpenSSL.crypto.X509 certificate and add it to the list of preferred certificate signers sent to the client when requesting a client certificate.

New in version 0.10.

Context.load_verify_locations(pemfile, capath)

Specify where CA certificates for verification purposes are located. These are trusted certificates. 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.

Context.set_default_verify_paths()

Specify that the platform provided CA certificates are to be used for verification purposes. This method may not work properly on OS X.

Context.load_tmp_dh(dhfile)

Load parameters for Ephemeral Diffie-Hellman from dhfile.

Context.set_app_data(data)

Associate data with this Context object. data can be retrieved later using the get_app_data() method.

Context.set_cipher_list(ciphers)

Set the list of ciphers to be used in this context. See the OpenSSL manual for more information (e.g. ciphers(1))

Context.set_info_callback(callback)

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

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

Context.set_options(options)

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

Context.set_passwd_cb(callback[, userdata])

Set the passphrase callback to callback. This function will be called when a private key with a passphrase is loaded. callback 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(). If an error occurs, callback should return a false value (e.g. an empty string).

Context.set_session_id(name)

Set the context name 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. name may be any binary data.

Context.set_timeout(timeout)

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

Context.set_verify(mode, callback)

Set the verification flags for this Context object to mode and specify that callback should be used for verification callbacks. mode 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 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.

Context.set_verify_depth(depth)

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

Context.use_certificate(cert)

Use the certificate cert which has to be a X509 object.

Context.add_extra_chain_cert(cert)

Adds the certificate cert, which has to be a X509 object, to the certificate chain presented together with the certificate.

Context.use_certificate_chain_file(file)

Load a certificate chain from file which must be PEM encoded.

Context.use_privatekey(pkey)

Use the private key pkey which has to be a PKey object.

Context.use_certificate_file(file[, format])

Load the first certificate found in file. The certificate must be in the format specified by format, which is either FILETYPE_PEM or FILETYPE_ASN1. The default is FILETYPE_PEM.

Context.use_privatekey_file(file[, format])

Load the first private key found in file. The private key must be in the format specified by format, which is either FILETYPE_PEM or FILETYPE_ASN1. The default is FILETYPE_PEM.

Context.set_tlsext_servername_callback(callback)

Specify a one-argument callable to use as the TLS extension server name callback. When a connection using the server name extension is made using this context, the callback will be invoked with the Connection instance.

New in version 0.13.

Connection objects

Connection objects have the following methods:

Connection.accept()

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 pair (conn, address). where conn is the new Connection object created, and address is as returned by the socket’s accept().

Connection.bind(address)

Call the bind() method of the underlying socket.

Connection.close()

Call the close() method of the underlying socket. Note: If you want correct SSL closure, you need to call the shutdown() method first.

Connection.connect(address)

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.

Connection.connect_ex(address)

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.

Connection.do_handshake()

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

Connection.fileno()

Retrieve the file descriptor number for the underlying socket.

Connection.listen(backlog)

Call the listen() method of the underlying socket.

Connection.get_app_data()

Retrieve application data as set by set_app_data().

Connection.get_cipher_list()

Retrieve the list of ciphers used by the Connection object. WARNING: This API has changed. It used to take an optional parameter and just return a string, but not it returns the entire list in one go.

Connection.get_client_ca_list()

Retrieve the list of preferred client certificate issuers sent by the server as OpenSSL.crypto.X509Name objects.

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

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

New in version 0.10.

Connection.get_context()

Retrieve the Context object associated with this Connection.

Connection.set_context(context)

Specify a replacement Context object for this Connection.

Connection.get_peer_certificate()

Retrieve the other side’s certificate (if any)

Connection.get_peer_cert_chain()

Retrieve the tuple of the other side’s certificate chain (if any)

Connection.getpeername()

Call the getpeername() method of the underlying socket.

Connection.getsockname()

Call the getsockname() method of the underlying socket.

Connection.getsockopt(level, optname[, buflen])

Call the getsockopt() method of the underlying socket.

Connection.pending()

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

Connection.recv(bufsize)

Receive data from the Connection. The return value is a string representing the data received. The maximum amount of data to be received at once, is specified by bufsize.

Connection.bio_write(bytes)

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

Connection.renegotiate()

Renegotiate the SSL session. Call this if you wish to change cipher suites or anything like that.

Connection.send(string)

Send the string data to the Connection.

Connection.bio_read(bufsize)

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.

Connection.sendall(string)

Send all of the string data to 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.

Connection.set_accept_state()

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

Connection.set_app_data(data)

Associate data with this Connection object. data can be retrieved later using the get_app_data() method.

Connection.set_connect_state()

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

Connection.setblocking(flag)

Call the setblocking() method of the underlying socket.

Connection.setsockopt(level, optname, value)

Call the setsockopt() method of the underlying socket.

Connection.shutdown()

Send the shutdown message to the Connection. Returns true if the shutdown message exchange is completed and false otherwise (in which case you call recv() or send() when the connection becomes readable/writeable.

Connection.get_shutdown()

Get the shutdown state of the Connection. Returns a bitvector of either or both of SENT_SHUTDOWN and RECEIVED_SHUTDOWN.

Connection.set_shutdown(state)

Set the shutdown state of the Connection. state is a bitvector of either or both of SENT_SHUTDOWN and RECEIVED_SHUTDOWN.

Connection.sock_shutdown(how)

Call the shutdown() method of the underlying socket.

Connection.bio_shutdown()

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.

Connection.state_string()

Retrieve a verbose string detailing the state of the Connection.

Connection.client_random()

Retrieve the random value used with the client hello message.

Connection.server_random()

Retrieve the random value used with the server hello message.

Connection.master_key()

Retrieve the value of the master key for this session.

Connection.want_read()

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

Connection.want_write()

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

Connection.set_tlsext_host_name(name)

Specify the byte string to send as the server name in the client hello message.

New in version 0.13.

Connection.get_servername()

Get the value of the server name received in the client hello message.

New in version 0.13.

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!

Table Of Contents

Previous topic

rand — An interface to the OpenSSL pseudo random number generator

Next topic

Internals

This Page