tls-1.4.0: TLS/SSL protocol native implementation (Server and Client)

MaintainerVincent Hanquez <>
Safe HaskellNone






Context configuration

data ClientParams Source #




type Bytes = ByteString Source #

Deprecated: Use Data.ByteString.Bytestring instead of Bytes.

data ServerParams Source #




data DebugParams Source #

All settings should not be used in production




  • debugSeed :: Maybe Seed

    Disable the true randomness in favor of deterministic seed that will produce a deterministic random from. This is useful for tests and debugging purpose. Do not use in production

  • debugPrintSeed :: Seed -> IO ()

    Add a way to print the seed that was randomly generated. re-using the same seed will reproduce the same randomness with debugSeed

data ClientHooks Source #

A set of callbacks run by the clients for various corners of TLS establishment




  • onCertificateRequest :: ([CertificateType], Maybe [HashAndSignatureAlgorithm], [DistinguishedName]) -> IO (Maybe (CertificateChain, PrivKey))

    This action is called when the server sends a certificate request. The parameter is the information from the request. The action should select a certificate chain of one of the given certificate types where the last certificate in the chain should be signed by one of the given distinguished names. Each certificate should be signed by the following one, except for the last. At least the first of the certificates in the chain must have a corresponding private key, because that is used for signing the certificate verify message.

    Note that is is the responsibility of this action to select a certificate matching one of the requested certificate types. Returning a non-matching one will lead to handshake failure later.

    Returning a certificate chain not matching the distinguished names may lead to problems or not, depending whether the server accepts it.

  • onServerCertificate :: CertificateStore -> ValidationCache -> ServiceID -> CertificateChain -> IO [FailedReason]

    Used by the client to validate the server certificate. The default implementation calls validateDefault which validates according to the default hooks and checks provided by Data.X509.Validation. This can be replaced with a custom validation function using different settings.

  • onSuggestALPN :: IO (Maybe [ByteString])

    This action is called when the client sends ClientHello to determine ALPN values such as '["h2", "http/1.1"]'.

data ServerHooks Source #

A set of callbacks run by the server for various corners of the TLS establishment




  • onClientCertificate :: CertificateChain -> IO CertificateUsage

    This action is called when a client certificate chain is received from the client. When it returns a CertificateUsageReject value, the handshake is aborted.

  • onUnverifiedClientCert :: IO Bool

    This action is called when the client certificate cannot be verified. Return True to accept the certificate anyway, or False to fail verification.

  • onCipherChoosing :: Version -> [Cipher] -> Cipher

    Allow the server to choose the cipher relative to the the client version and the client list of ciphers.

    This could be useful with old clients and as a workaround to the BEAST (where RC4 is sometimes prefered with TLS < 1.1)

    The client cipher list cannot be empty.

  • onServerNameIndication :: Maybe HostName -> IO Credentials

    Allow the server to indicate additional credentials to be used depending on the host name indicated by the client.

    This is most useful for transparent proxies where credentials must be generated on the fly according to the host the client is trying to connect to.

    Returned credentials may be ignored if a client does not support the signature algorithms used in the certificate chain.

  • onNewHandshake :: Measurement -> IO Bool

    at each new handshake, we call this hook to see if we allow handshake to happens.

  • onALPNClientSuggest :: Maybe ([ByteString] -> IO ByteString)

    Allow the server to choose an application layer protocol suggested from the client through the ALPN (Application Layer Protocol Negotiation) extensions.

data Supported Source #

List all the supported algorithms, versions, ciphers, etc supported.




  • supportedVersions :: [Version]

    Supported Versions by this context On the client side, the highest version will be used to establish the connection. On the server side, the highest version that is less or equal than the client version will be chosed.

  • supportedCiphers :: [Cipher]

    Supported cipher methods. The default is empty, specify a suitable cipher list. ciphersuite_default is often a good choice.

  • supportedCompressions :: [Compression]

    supported compressions methods

  • supportedHashSignatures :: [HashAndSignatureAlgorithm]

    All supported hash/signature algorithms pair for client certificate verification and server signature in (EC)DHE, ordered by decreasing priority.

    This list is sent to the peer as part of the signature_algorithms extension. It is also used to restrict the choice of server credential, signature and hash algorithm, but only when the TLS version is 1.2 or above. In order to disable SHA-1 one must then also disable earlier protocol versions in supportedVersions.

  • supportedSecureRenegotiation :: Bool

    Secure renegotiation defined in RFC5746. If True, clients send the renegotiation_info extension. If True, servers handle the extension or the renegotiation SCSV then send the renegotiation_info extension.

  • supportedClientInitiatedRenegotiation :: Bool

    If True, renegotiation is allowed from the client side. This is vulnerable to DOS attacks. If False, renegotiation is allowed only from the server side via HelloRequest.

  • supportedSession :: Bool

    Set if we support session.

  • supportedFallbackScsv :: Bool

    Support for fallback SCSV defined in RFC7507. If True, servers reject handshakes which suggest a lower protocol than the highest protocol supported.

  • supportedEmptyPacket :: Bool

    In ver <= TLS1.0, block ciphers using CBC are using CBC residue as IV, which can be guessed by an attacker. Hence, an empty packet is normally sent before a normal data packet, to prevent guessability. Some Microsoft TLS-based protocol implementations, however, consider these empty packets as a protocol violation and disconnect. If this parameter is False, empty packets will never be added, which is less secure, but might help in rare cases.

  • supportedGroups :: [Group]

    A list of supported elliptic curves in the preferred order. The default value is [P256,P384,P521]. P256 provides 128-bit security which is strong enough until 2030 and is fast because its backend is written in C.

data Hooks Source #

A collection of hooks actions.





data Logging Source #

Hooks for logging

This is called when sending and receiving packets and IO




data Measurement Source #

record some data about this connection.




data CertificateUsage Source #

Certificate Usage callback possible returns values.



usage of certificate accepted

CertificateUsageReject CertificateRejectReason

usage of certificate rejected

raw types


type SessionID = ByteString Source #

A session ID

data SessionManager Source #

A session manager




Backend abstraction

data Backend Source #

Connection IO backend




Context object

data Context Source #

A TLS Context keep tls specific state, parameters and backend information.

ctxConnection :: Context -> Backend Source #

return the backend object associated with this context

class TLSParams a Source #

Minimal complete definition

getTLSCommonParams, getTLSRole, doHandshake, doHandshakeWith

Creating a context

contextNew Source #


:: (MonadIO m, HasBackend backend, TLSParams params) 
=> backend

Backend abstraction with specific method to interact with the connection type.

-> params

Parameters of the context.

-> m Context 

create a new context using the backend and parameters specified.

contextNewOnHandle Source #


:: (MonadIO m, TLSParams params) 
=> Handle

Handle of the connection.

-> params

Parameters of the context.

-> m Context 

Deprecated: use contextNew

create a new context on an handle.

contextNewOnSocket Source #


:: (MonadIO m, TLSParams params) 
=> Socket

Socket of the connection.

-> params

Parameters of the context.

-> m Context 

Deprecated: use contextNew

create a new context on a socket.

Information gathering

contextGetInformation :: Context -> IO (Maybe Information) Source #

Information about the current context


credentialLoadX509 Source #


:: FilePath

public certificate (X.509 format)

-> FilePath

private key associated

-> IO (Either String Credential) 

try to create a new credential object from a public certificate and the associated private key that are stored on the filesystem in PEM format.

credentialLoadX509FromMemory :: ByteString -> ByteString -> Either String Credential Source #

similar to credentialLoadX509 but take the certificate and private key from memory instead of from the filesystem.

credentialLoadX509Chain Source #


:: FilePath

public certificate (X.509 format)

-> [FilePath]

chain certificates (X.509 format)

-> FilePath

private key associated

-> IO (Either String Credential) 

similar to credentialLoadX509 but also allow specifying chain certificates.

Initialisation and Termination of context

bye :: MonadIO m => Context -> m () Source #

notify the context that this side wants to close connection. this is important that it is called before closing the handle, otherwise the session might not be resumable (for version < TLS1.2).

this doesn't actually close the handle

handshake :: MonadIO m => Context -> m () Source #

Handshake for a new TLS connection This is to be called at the beginning of a connection, and during renegotiation

Application Layer Protocol Negotiation

getNegotiatedProtocol :: MonadIO m => Context -> m (Maybe ByteString) Source #

If the ALPN extensions have been used, this will return get the protocol agreed upon.

Server Name Indication

getClientSNI :: MonadIO m => Context -> m (Maybe HostName) Source #

If the Server Name Indication extension has been used, return the hostname specified by the client.

High level API

sendData :: MonadIO m => Context -> ByteString -> m () Source #

sendData sends a bunch of data. It will automatically chunk data to acceptable packet size

recvData :: MonadIO m => Context -> m ByteString Source #

recvData get data out of Data packet, and automatically renegotiate if a Handshake ClientHello is received

recvData' :: MonadIO m => Context -> m ByteString Source #

Deprecated: use recvData that returns strict bytestring

same as recvData but returns a lazy bytestring.

Crypto Key

data PubKey :: * #

Public key types known and used in X.509


PubKeyRSA PublicKey

RSA public key

PubKeyDSA PublicKey

DSA public key

PubKeyDH (Integer, Integer, Integer, Maybe Integer, ([Word8], Integer))

DH format with (p,g,q,j,(seed,pgenCounter))

PubKeyEC PubKeyEC

EC public key

PubKeyUnknown OID ByteString

unrecognized format


data PrivKey :: * #

Private key types known and used in X.509


PrivKeyRSA PrivateKey

RSA private key

PrivKeyDSA PrivateKey

DSA private key


Compressions & Predefined compressions

class CompressionC a where Source #

supported compression algorithms need to be part of this class

data Compression Source #

every compression need to be wrapped in this, to fit in structure


CompressionC a => Compression a 

type CompressionID = Word8 Source #

Compression identification

nullCompression :: Compression Source #

default null compression

data NullCompression Source #

This is the default compression which is a NOOP.

member redefined for the class abstraction

compressionID :: Compression -> CompressionID Source #

return the associated ID for this algorithm

compressionDeflate :: ByteString -> Compression -> (Compression, ByteString) Source #

deflate (compress) a bytestring using a compression context and return the result along with the new compression context.

compressionInflate :: ByteString -> Compression -> (Compression, ByteString) Source #

inflate (decompress) a bytestring using a compression context and return the result along the new compression context.


compressionIntersectID :: [Compression] -> [Word8] -> [Compression] Source #

intersect a list of ids commonly given by the other side with a list of compression the function keeps the list of compression in order, to be able to find quickly the prefered compression.

Ciphers & Predefined ciphers

data Bulk Source #


Eq Bulk Source # 


(==) :: Bulk -> Bulk -> Bool #

(/=) :: Bulk -> Bulk -> Bool #

Show Bulk Source # 


showsPrec :: Int -> Bulk -> ShowS #

show :: Bulk -> String #

showList :: [Bulk] -> ShowS #

data Hash Source #




Eq Hash Source # 


(==) :: Hash -> Hash -> Bool #

(/=) :: Hash -> Hash -> Bool #

Show Hash Source # 


showsPrec :: Int -> Hash -> ShowS #

show :: Hash -> String #

showList :: [Hash] -> ShowS #

type CipherID = Word16 Source #

Cipher identification

cipherAllowedForVersion :: Version -> Cipher -> Bool Source #

Check if a specific Cipher is allowed to be used with the version specified


data Version Source #

Versions known to TLS

SSL2 is just defined, but this version is and will not be supported.





data TLSException Source #

TLS Exceptions related to bad user usage or asynchronous errors


Terminated Bool String TLSError

Early termination exception with the reason and the error associated

HandshakeFailed TLSError

Handshake failed for the reason attached


Usage error when the connection has not been established and the user is trying to send or receive data

X509 Validation

data ValidationChecks :: * #

A set of checks to activate or parametrize to perform on certificates.

It's recommended to use defaultChecks to create the structure, to better cope with future changes or expansion of the structure.




  • checkTimeValidity :: Bool

    check time validity of every certificate in the chain. the make sure that current time is between each validity bounds in the certificate

  • checkAtTime :: Maybe DateTime

    The time when the validity check happens. When set to Nothing, the current time will be used

  • checkStrictOrdering :: Bool

    Check that no certificate is included that shouldn't be included. unfortunately despite the specification violation, a lots of real world server serves useless and usually old certificates that are not relevant to the certificate sent, in their chain.

  • checkCAConstraints :: Bool

    Check that signing certificate got the CA basic constraint. this is absolutely not recommended to turn it off.

  • checkExhaustive :: Bool

    Check the whole certificate chain without stopping at the first failure. Allow gathering a exhaustive list of failure reasons. if this is turn off, it's absolutely not safe to ignore a failed reason even it doesn't look serious (e.g. Expired) as other more serious checks would not have been performed.

  • checkLeafV3 :: Bool

    Check that the leaf certificate is version 3. If disable, version 2 certificate is authorized in leaf position and key usage cannot be checked.

  • checkLeafKeyUsage :: [ExtKeyUsageFlag]

    Check that the leaf certificate is authorized to be used for certain usage. If set to empty list no check are performed, otherwise all the flags is the list need to exists in the key usage extension. If the extension is not present, the check will pass and behave as if the certificate key is not restricted to any specific usage.

  • checkLeafKeyPurpose :: [ExtKeyUsagePurpose]

    Check that the leaf certificate is authorized to be used for certain purpose. If set to empty list no check are performed, otherwise all the flags is the list need to exists in the extended key usage extension if present. If the extension is not present, then the check will pass and behave as if the certificate is not restricted to any specific purpose.

  • checkFQHN :: Bool

    Check the top certificate names matching the fully qualified hostname (FQHN). it's not recommended to turn this check off, if no other name checks are performed.

data ValidationHooks :: * #

A set of hooks to manipulate the way the verification works.

BEWARE, it's easy to change behavior leading to compromised security.




X509 Validation Cache

data ValidationCache :: * #

All the callbacks needed for querying and adding to the cache.




data ValidationCacheResult :: * #

The result of a cache query



cache allow this fingerprint to go through

ValidationCacheDenied String

cache denied this fingerprint for further validation


unknown fingerprint in cache

exceptionValidationCache :: [(ServiceID, Fingerprint)] -> ValidationCache #

create a simple constant cache that list exceptions to the certification validation. Typically this is use to allow self-signed certificates for specific use, with out-of-bounds user checks.

No fingerprints will be added after the instance is created.

The underlying structure for the check is kept as a list, as usually the exception list will be short, but when the list go above a dozen exceptions it's recommended to use another cache mechanism with a faster lookup mechanism (hashtable, map, etc).

Note that only one fingerprint is allowed per ServiceID, for other use, another cache mechanism need to be use.

Key exchange group