API Reference

python-libtls provides its functionality through two classes, Context and TLSSocket. You won’t need to reference the latter class directly, unless you want to subclass it for some reason.

The Context class

class Context(**kwargs)

This class is a high-level wrapper over the low-level functionality provided by libtls. Although you can access this low-level functionality through python-libtls, for the most part you can do what you need using Context. One of the things that it gives you is the ability to wrap a socket with the TLS security layer, and you can then use this wrapped like a normal socket.

Arguments are currently all provided as keyword arguments. Don’t be put off by the long list – for most usage, you only need to specify a few of these.

Common keyword parameters (client-side or server-side):
 
  • server (bool) – If True, this will be a server-side context. If False (the default), this will be a client-side context.
  • cafile (str) – The path to a CA certificate in PEM format. This is used for verification and is not normally needed to be provided on the client side. This is the certificate which has been used to sign any certificate provided via keypair_paths (see below). This will typically be a certificate bundle containing any number of intermediate certificates, with the topmost being one which is recognised by a valid certificate authority.
  • capath (str) – The path to a directory containing CA certificates in PEM format. This is used for verification and is not normally needed to be provided on the client side. The directory should contain any intermediate certificates which will be needed for verification.
  • keypair_paths (tuple) – This is used for verification and is not normally needed to be provided on the client side. This should be either a 2-tuple or a 3-tuple. The first element of the tuple is the path to the certificate (in PEM format) which identifies the client or server. The second element is the path to a private key in PEM format, which corresponds to the certificate specified in the first element. The third element, if provided, is the path to an OCSP response in DER format, which gives the revocation status of the certificate as obtained from an OCSP responder.
  • verify_depth (int) – If specified, limits the number of intermediate certificates that will be followed during certificate validation. If unspecified, there is no limit.
  • ciphers (str) – If specified, specifies the list of ciphers which will be used during handshake. See this page for the list format.
  • dhe_params (str) – If specified, specifies the DHE (Diffie-Hellman Exchange) parameters which will be used during handshake.
  • ecdhe_curve (str) – If specified, specifies the ECDHE (Elliptic Curve Diffie-Hellman Exchange) curve which will be used during handshake.
  • alpn (str) – If specified, specifies the ALPN (Application-Layer Protocol Negotiation) parameters which will be used during handshake.

Note

If you don’t specify capath= or cafile= parameters, then a default location will be searched for a CA certificate bundle for use in verification. See Location of the default CA certificate bundle for more information.

Client-side keyword parameters:
 
  • verify_cert (bool) – If False, the server identity will not be verified. If True (the default), the server identity will be verified.
  • verify_name (bool) – If False, the server name will not be checked to be the same as the server connected to. If True (the default), the server name will be checked.
  • verify_time (bool) – If False, the validity period of the server certificate will not be checked. If True (the default), the server certificate validity time will be checked.
  • require_ocsp_stapling (bool) – If True, the server will be required to staple an OCSP response to the response it sends during negotiation. If False (the default), the server will not be expected to provide an OCSP response. OCSP is the Online Certificate Status Protocol and is used to verify that a server’s certificate has not been revoked after it was issued, even if it appears otherwise valid.
Server-side keyword parameters:
 
  • verify_client (bool) – If True, the client will be expected to supply a certificate to identify itself. If False (the default), the client is not expected to certify its identity.
  • prefer_client_ciphers (bool) – If True, the ciphers suggested by the client will be given preference during negotiation. If False (the default - considered more secure), the server will use its preferred ciphers.
  • extra_certificate_key_paths (sequence) – A sequence of tuples. Each tuple is either a 2-tuple - a pair of filenames (certpath, keypath) to additional certificate and key files in PEM format - or a 3-tuple to be interpreted as (certpath, keypath, ocsppath) where the last member is the path to a file containing an OCSP response in DER format applicable to the certificate.
  • session_id (bytes) – If specified, this sets the session identifier that will be used by the server when sessions are enabled. By default, a random value is used.
  • session_lifetime (int) – If specified, sets the lifetime (in seconds) to be used for TLS sessions. Session support is disabled if a value of zero is specified, which is the default.

Note

Sessions are intended to improve performance during handshake, but come at a cost of not maintaining forward secrecy. They should be disabled (the default) if possible.

Methods (commonly used)

These are the most commonly used methods:

connect(host, port, sock=None, hostname=None)

This method of a client-side context is used to connect to a specified host and port.

Parameters:
 
  • host (str) – The host to connect to.
  • port (int) – The port to connect to.
Keyword parameters:
 
  • sock (socket) – A socket to use, which has either not been connected or has been connected to the specified host and port. The Context takes ownership of the socket and will close it when the context itself is closed. You should not close the socket yourself.

    If not specified, a socket is created internally and connected to the host and port specified.

  • hostname (str) – A specific hostname to check. If not specified, defaults to the host parameter.

Returns:
 

An instance of TLSSocket - a socket-like object which can be used for secure communication.

accept(sock):

This method of a server-side context is used to accept a socket which is connected to a client.

Parameters:
 
  • sock (socket) – A socket to use. The Context takes ownership of the socket and will close it when the context itself is closed. You should not close the socket yourself.
Returns:
 

An instance of TLSSocket - a socket-like object which can be used for secure communication.

close()

This closes the context. It will not be usable after this call. If a socket was provided in the connect() call, it will be closed. Any libtls resources used will be freed.

peer_cert_contains_name(name)

Whether the peer certificate contains the specified name.

Parameters:
 name (str) – The name to check.
Returns:
 True if the name appears in the certificate, else False.

Methods (less commonly used)

process_ocsp_response(response)

This processes an OCSP response.

Parameters:
 response (bytes) – The response in DER format.
Returns:
 An integer response code.
wrap_socket(sock, **kwargs)

This method wraps the provided socket with a TLS wrapper. This method is normally called by the connect() and accept() methods, so you shouldn’t need to call it directly.

Parameters:
 
  • sock (socket) – A socket to wrap.
Server-side keyword parameters:
 
  • server_side (bool) – This must be specified as True for server-side sockets. The default is False.
Client-side keyword parameters:
 
  • server_hostname (str) – A hostname to check for as part of verification. If not provided, the hostname which was used to connect to is used in its place.
Returns:
 

A TLSSocket instance.

Context instance attributes

About the connection

conn_version

(str) - the TLS version which has been negotiated for the connection.

conn_servername

(str) - the server name for the connection.

conn_cipher

(str) - the cipher used for the connection.

conn_alpn_selected

(str) - the selected ALPN parameters for the connection.

About the peer

peer_cert_provided

(bool) - whether the peer has provided a certificate.

peer_cert_issuer

(str) - the issuing CA for the peer’s certificate.

peer_cert_notbefore

(datetime) - the time before which the peer’s certificate is not valid.

peer_cert_notafter

(datetime) - the time after which the peer’s certificate is not valid.

peer_cert_subject

(str) - the subject of the peer’s certificate.

peer_cert_hash

(str) - the hash of the peer’s certificate. This is prefixed with the hash algorithm used (e.g. SHA256:) followed by the actual hash value as a hex string.

peer_ocsp_response_status

(int) - the status of the peer’s OCSP response, which will be as per RFC 6960 section 2.3:

  • TLS_OCSP_RESPONSE_SUCCESSFUL
  • TLS_OCSP_RESPONSE_MALFORMED
  • TLS_OCSP_RESPONSE_INTERNALERROR
  • TLS_OCSP_RESPONSE_TRYLATER
  • TLS_OCSP_RESPONSE_SIGREQUIRED
  • TLS_OCSP_RESPONSE_UNAUTHORIZED

(These values are defined in the tls package.)

peer_ocsp_cert_status

(int) - the OCSP status of the peer’s certificate, which will be as per RFC 6960 section 2.2:

  • TLS_OCSP_CERT_GOOD
  • TLS_OCSP_CERT_REVOKED
  • TLS_OCSP_CERT_UNKNOWN

(These values are defined in the tls package.)

peer_ocsp_result

(str) - the summary of the OCSP status of the peer’s certificate. If there was a problem with the OCSP response, this will indicate what the problem was. If the certificate wasn’t revoked, then information about the certificate status will be provided. If the certificate was revoked, then the reason for revocation will be provided.

peer_ocsp_crl_reason

(int) - the reason the peer certificate was revoked, which will be as per RFC 5280 section 5.3.1:

  • TLS_CRL_REASON_UNSPECIFIED
  • TLS_CRL_REASON_KEY_COMPROMISE
  • TLS_CRL_REASON_CA_COMPROMISE
  • TLS_CRL_REASON_AFFILIATION_CHANGED
  • TLS_CRL_REASON_SUPERSEDED
  • TLS_CRL_REASON_CESSATION_OF_OPERATION
  • TLS_CRL_REASON_CERTIFICATE_HOLD
  • TLS_CRL_REASON_REMOVE_FROM_CRL
  • TLS_CRL_REASON_PRIVILEGE_WITHDRAWN
  • TLS_CRL_REASON_AA_COMPROMISE

(These values are defined in the tls package.)

peer_ocsp_url

(str) - the URL of the OCSP provider for the peer.

peer_ocsp_this_update

(datetime) - the time of this OCSP update.

peer_ocsp_next_update

(datetime) - the time of the next OCSP update.

peer_ocsp_revocation_time

(datetime) - the time the peer certificate was revoked.

Context class attributes

wrapper_class

(class) - the class used as a wrapper class for sockets. By default it is set to TLSSocket, but this allows subclasses to be used if needed.

The TLSSocket class

This class behaves like an ordinary streaming socket, except that it has an additional do_handshake() method which allows you to do the TLS handshake explicitly. If you read from or write to the socket, a handshake will be done automatically when needed, but it’s useful to do it explicitly when you need to verify the connection and peer before doing any I/O for your application. You don’t instantiate TLSSocket instances directly: they’re created internally by Context instances and handed to you as the return value from certain Context methods.

Methods

do_handshake()

This initiates a handshake with the other end of the connection (if that has not already been done). A handshake is automatically done before doing any I/O with the peer; this method is for when you want to control handshaking explicitly, perhaps to perform verification of the peer at a time of your choosing.

Exception classes

python-libtls raises library-specific exceptions. The following is the exception class hierarchy.

Exception
└── TLSError
    ├── ConfigurationError
    └── ConnectionError
        └── VerificationError

The Exception class is from the Python standard library. The TLSError is the base class for exceptions raised by python-libtls. A ConfigurationError is raised when a configuration value is not acceptable to libtls. A ConnectionError is raised when an error related to connecting to a peer, or during I/O to or from a peer, occurs. A VerificationError is raised when an explicit handshake fails.

In addition to the TLSError-based exceptions, python-libtls may also raise ValueError, TypeError and other standard library exceptions.