TLS

class kaa.net.tls.TLSSocket(ctx=None, reuse_sessions=False)

TLSSocket extends Socket by adding SSL/TLS support.

Until starttls_client() or starttls_server() is called, a TLSSocket operates like a standard Socket. After TLS handshaking is initiated, data passed to/from the socket is transparently encrypted.

TLSSockets that listen() will emit new-client with a TLSSocket object as the client. This TLSSocket will share the same TLSContext as the listening TLSSocket.

Synopsis

Class Hierarchy

kaa.Object
└─ kaa.IOChannel
     └─ kaa.Socket
          └─ kaa.net.tls.TLSSocket

Methods
starttls_client()Send a ClientHello to initiate SSL session negotiation.
starttls_server()Wait for a ClientHello before continuing communication.
verify()Verify one certificate in the peer’s certificate chain.
write()Write data to the socket, encrypting if necessary.
Properties
cipherread-onlyThe cipher negotiated with the peer.
ctxread/writeThe TLSContext object associated with this TLSSocket.
handshakedread-onlyTrue when the SSL handshake has completed.
peer_cert_chainread-onlyA list of Certificate objects representing the certificate chain for the connected peer.
reuse_sessionsread/writeTrue if session state will be preserved between connections.
secure_renegotiation_supportread-onlyIndicates if the peer supports RFC5746 Secure Renegotiation.
sessionread/writeA TLSSession object representing the session state for the current connection.
session_reusedread-onlyTrue if the SSL session was able to be reused for this connection.
verifiedread-onlyThe status of the peer’s certificate chain verification.
verify_cbread/writeUser-installable callback for peer certificate verification.
Signals
tlsEmitted when a TLS handshake has been successfully completed.

Methods

starttls_client(cert=None, key=None, password=None, verify=True, cn=None, fingerprint=None)

Send a ClientHello to initiate SSL session negotiation.

Parameters:
  • key, password (cert,) – corresponds to TLSContext.load_cert_chain()
  • verify (bool) – if True, the server must present a certificate and must verify successfully until further communication is allowed; if False, no server certificate verification is done.
  • cn (str) – the default verification function will verify that the server presents a certificate with a commonName or subjectAltName matching this value; if None, the hostname passed to connect() is used instead.
  • fingerprint (str) – require the server’s certificate to match the given SHA1 hex digest
Returns:

InProgress that finishes when TLS handshaking succeeds or fails. If the handshake fails, an exception is thrown to the InProgress

Before this method (or starttls_server()) is invoked, a TLSSocket behaves like a standard Socket.

starttls_server(cert=None, key=None, password=None, verify=False, dh=None, ticket_key=None)

Wait for a ClientHello before continuing communication.

Parameters:
  • key, password (cert,) – corresponds to TLSContext.load_cert_chain()
  • verify (bool) – if True, the client must present a certificate and must verify successfully until further communication is allowed; if False, no client certificate verification is done.
  • dh (str) – filename for Diffie-Hellman parameters in PEM format, needed for EDH ciphers. If None, temporary DH params will be used.
  • ticket_key (str) – corresponds to TLSContext.ticket_key
Returns:

InProgress that finishes when TLS handshaking succeeds or fails. If the handshake fails, an exception is thrown to the InProgress

Before this method (or starttls_client()) is invoked, a TLSSocket behaves like a standard Socket.

verify(cert, depth, err, errmsg)

Verify one certificate in the peer’s certificate chain.

Parameters:
  • cert (Certificate) – the certificate in the chain currently being verified
  • depth (int) – the depth within the peer’s certificate chain for the certificate; the values are inverted such that 0 is the peer’s certificate, and increasing values walk up the issuer chain.
  • err (int or None) – an error code indicating any pre-validation failures detected by OpenSSL, or None if no errors were found.
  • errmsg (str or None) – a human-readable string of err, or None if no errors were found.
Returns:

anything if the certificate should be accepted, otherwise it will raise an exception to reject it

Raises :

TLSVerificationError

If verify=True was passed to either starttls_client() or starttls_server(), this method is invoked for each certificate in the peer’s chain to give it an opportunity to accept or reject it by raising TLSVerificationError.

Raising an exception will cause the exception to be thrown to the InProgress of a pending starttls_client() or starttls_server(). The verified property will be False, and the socket will be immediately closed.

The default behaviour requires the certificate is issued by a recognized CA (see TLSContext.load_verify_locations()), the current time is within the certificate’s validity period, and Certificate.match_subject_name() succeeds given the hostname given to connect() (or cn kwarg passed to starttls_client())

Note

Subclasses may override this method to implement custom verification behaviour, but it may be more convenient to set the verify_cb property with a callback.

write(data)

Write data to the socket, encrypting if necessary.

Parameters:data (str) – the plaintext data to be sent to the peer
Returns:an InProgress as described in kaa.IOChannel.write()

Until starttls_client() or starttls_server() is called, the data passed is sent plaintext, just as it is with a standard Socket. After either is called, TLS handshaking must be completed and verification passed (if enabled) before writing is allowed, after which the supplied data is encrypted before being sent to the peer.

Properties

cipher

The cipher negotiated with the peer.

If no TLS handshake has been performed, this value is None.

ctx

The TLSContext object associated with this TLSSocket.

By default, a new context is created for each TLSSocket. You can set this property or pass a TLSContext object when creating the TLSSocket to share contexts between connections.

Note

For active connections that have completed handshaking, setting this property will have no effect until the next time starttls_client() or starttls_server() is called.

handshaked

True when the SSL handshake has completed.

peer_cert_chain

A list of Certificate objects representing the certificate chain for the connected peer.

The list is ordered such that the first element is the peer’s certificate, and the last element is the top-level certificate authority.

reuse_sessions

True if session state will be preserved between connections.

SSL session resumption performs an abbreviated handshake if the server side recognizes the session id, or if the client presents a valid session ticket the server can decrypt. This is allows substantially more efficient reconnections.

This value is False by default. If True, for clients, the session state will be perserved between subsequent connect() and starttls_client() calls.

Note

Currently, servers will always maintain a session cache and allow clients to attempt session resumption.

It is possible to explicitly reuse sessions by saving and restoring the session property between connections (which also works across different TLSSocket instances, and across TLSContexts).

secure_renegotiation_support

Indicates if the peer supports RFC5746 Secure Renegotiation.

session

A TLSSession object representing the session state for the current connection.

This value can be set with an existing TLSSession and later calls to starttls_client() will attempt to reuse the session.

session_reused

True if the SSL session was able to be reused for this connection.

verified

The status of the peer’s certificate chain verification.

Possible values:
  • None: verification was not yet performed (e.g. TLS handshake has not yet occurred)
  • False: verification was performed and failed
  • True: peer certificate chain passed verfication.
verify_cb

User-installable callback for peer certificate verification.

def callback(cert, depth, err, errmsg)

See verify() for argument details.

If a callback is set, it will be invoked for each certificate in the peer’s chain instead of the verify() method.

Signals

tls

Emitted when a TLS handshake has been successfully completed.

def callback(...)

class kaa.net.tls.TLSContext(protocol=None)

Encapsulates one or more TLSSocket objects with common configuration (like certificates) and shared data (like sessions).

By default, TLSSockets will each create their own TLSContext. Sharing the same context allows things like SSL session resumption between multiple sockets.

Synopsis

Class Hierarchy

kaa.net.tls.TLSContext

Methods
load_cert_chain()Load a certificate chain and keys into the context.
load_dh_params()Load parameters for Ephemeral Diffie-Hellman.
load_verify_locations()Set the location of trusted certificates for certificate verification.
set_ciphers()Set the available ciphers for sockets created with this context.
Properties
dh_sizeread-onlyThe size of the currently loaded DH parameters in bits.
local_certread-onlyA Certificate object of the local certificate loaded by load_cert_chain().
ticket_keyread/writeA 48 byte string used to encrypt session tickets.
verify_locationread-onlyThe location set (or discovered) by load_verify_locations()

Methods

load_cert_chain(cert, key=None, password=None)

Load a certificate chain and keys into the context.

Parameters:
  • cert (str) – filename for side certificate in PEM format
  • key (str) – filename for the private key for the given cert in PEM format; if None and cert is not None, then it assumes the key is contained in the cert file.
  • password – password to unlock the private key; if None and cert is not None, then it assumes the key is not protected by a password. If arg is a callable, it is passed no arguments and must return a string.

For clients, a loaded certificate will be presented to the server when TLSSocket.starttls_client() is called. For servers, it is mandatory that a certificate is loaded.

In either case, the certificate chain can be loaded by explicitly calling this method, or passing the cert, key, and password kwargs in TLSSocket.starttls_client() and TLSSocket.starttls_server().

load_dh_params(file=None)

Load parameters for Ephemeral Diffie-Hellman.

Parameters:file (str) – filename containing DH parameters in PEM format; if None, hardcoded defaults are used

DH parameters are required to be loaded in order for EDH ciphers to be available.

The size of the loaded DH parameters can be gotten from the dh_size property.

load_verify_locations(location=None)

Set the location of trusted certificates for certificate verification.

Parameters:location (str) – path to a file containing concatenated certificates in PEM format, or directory containing individual certificates as files; if None, a location is auto-discovered based on OpenSSL system configuration.
set_ciphers(ciphers)

Set the available ciphers for sockets created with this context.

Parameters:ciphers (str) – a string in the OpenSSL cipher list format.
Raises :TLSError if no ciphers could be selected

Once a TLSSocket is connected, the cipher property can be checked to see which cipher was selected.

Properties

dh_size

The size of the currently loaded DH parameters in bits.

local_cert

A Certificate object of the local certificate loaded by load_cert_chain().

If None, load_cert_chain() was never called (or had failed).

ticket_key

A 48 byte string used to encrypt session tickets.

Setting this value enables the session ticket extension, and clients will receive session tickets during handshake. Clients that present tickets encrypted using this key can resume SSL sessions without the need for server-side session cache.

Clients don’t need to do anything special to use the tickets except to set reuse_sessions.

Note

The actual key used to encrypt the tickets is derived from an HMAC of the local certificate using the given key. This means it is necessary to first call load_cert_chain().

verify_location

The location set (or discovered) by load_verify_locations()

If None, load_verify_locations() was either never called or no location was auto-discovered.

class kaa.net.tls.Certificate(x509, copy=False)

An X.509 certificate.

You will not instantiate these objects directly, but they will be returned from various TLSSocket methods and properties.

Note

Certificate objects are presently read-only.

Synopsis

Class Hierarchy

kaa.net.tls.Certificate

Methods
digest()Generate a binary digest for the certificate.
hexdigest()Generate a hex string digest for the certificate.
match_subject_name()Match the given name with either the subject’s commonName or one of the subjectAltNames.
Properties
expiredread-onlyTrue if the current time is outside the certificate’s validity period.
extensionsread-onlyA dictionary of X509 v3 extensions present in the certificate.
issuerread-onlyAn X509Name for the entity that signed and issued the certificate.
not_afterread-onlyA datetime object representing the expiry date of the certificate.
not_beforeread-onlyA datetime object representing the date the certificate becomes valid.
serial_numberread-onlyThe serial number assigned to the certificate by the issuer (which must be unique per CA).
subjectread-onlyAn X509Name for the entity the certificate belongs to.
versionread-onlyThe version of the certificate (usually 2).

Methods

digest(name='sha1')

Generate a binary digest for the certificate.

Parameters:name (str) – the name of the digest algorithm to use (e.g. md5, sha1, sha256, sha512)
Returns:a byte string containing the binary digest
hexdigest(name='sha1')

Generate a hex string digest for the certificate.

Parameters:name (str) – see digest()
Returns:a hex string of the digest
match_subject_name(name, wildcards=True)

Match the given name with either the subject’s commonName or one of the subjectAltNames.

Parameters:
  • name – the hostname to match
  • wildcards – allow wildcards in the subject names
Returns:

the name that matched the supplied name, or None if no matches were found.

Properties

expired

True if the current time is outside the certificate’s validity period.

For convenience, if a certificate is not yet valid (because the current time is before not_before), this property will be True.

extensions

A dictionary of X509 v3 extensions present in the certificate.

The keys are the extension name (e.g. subjectAltName), and each value is a dict mapping data type names (e.g. dns) to a list of data values.

Note

Currently the only supported extension is subjectAltName. Other extensions will be present in the extensions dict, but their values will be None.

issuer

An X509Name for the entity that signed and issued the certificate.

not_after

A datetime object representing the expiry date of the certificate.

The datetime object is timezone-aware in UTC.

not_before

A datetime object representing the date the certificate becomes valid.

The datetime object is timezone-aware in UTC.

serial_number

The serial number assigned to the certificate by the issuer (which must be unique per CA).

subject

An X509Name for the entity the certificate belongs to.

version

The version of the certificate (usually 2).

class kaa.net.tls.X509Name(x509name, cert)

Represents an X509 name element as a dictionary.

Typical keys are:
  • C: country
  • ST: state
  • L: city
  • O: organization
  • OU: organizational unit
  • CN: common name (hostname)

str(x509name) will return a single line representing all elements of the X509Name in an OpenSSL-specific format.

Note

X509Name objects are presently read-only.

Synopsis

Class Hierarchy

__builtin__.dict
└─ kaa.net.tls.X509Name

Previous topic

Input Plugins

Next topic

Multicast DNS

This Page