HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Moduletls-2.1.6Haskell2010

Network.TLS

Native Haskell TLS protocol implementation for servers and clients.

This provides a high-level implementation of a sensitive security protocol, eliminating a common set of security issues through the use of the advanced type system, high level constructions and common Haskell features.

Currently implement the TLS1.2 and TLS 1.3 protocol, and support RSA and Ephemeral (Elliptic curve and regular) Diffie Hellman key exchanges, and many extensions.

The tipical usage is:

socket <- ...
ctx <- contextNew socket <params>
handshake ctx
... (using recvData and sendData)
bye
  • 61 types
  • 3 classes
  • 135 values
  • Packagetls-2.1.6
  • Exports277
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceTLS.hs

Basic APIs

6 declarations
datadata Context
#

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

valuecontextNew
  1. :: (MonadIO m, HasBackend backend, TLSParams params)
  2. => backend

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

  3. -> params

    Parameters of the context.

  4. -> m Context
#

create a new context using the backend and parameters specified.

valuehandshake :: MonadIO m => Context -> m ()
#

Handshake for a new TLS connection This is to be called at the beginning of a connection, and during renegotiation. Don't use this function as the acquire resource of bracket.

valuerecvData :: MonadIO m => Context -> m ByteString
#

Get data out of Data packet, and automatically renegotiate if a Handshake ClientHello is received. An empty result means EOF.

valuebye :: MonadIO m => Context -> m ()
#

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.

Proper usage is as follows:

ctx <- contextNew <backend> <params>
handshake ctx
...
bye

The following code ensures nothing but is no harm.

bracket (contextNew <backend> <params>) bye $ \ctx -> do
  handshake ctx
  ...

Exceptions

0 declarations

Since 1.8.0, this library only throws exceptions of type TLSException. In the common case where the chosen backend is socket, IOException may be thrown as well. This happens because the backend for sockets, opaque to most modules in the tls library, throws those exceptions.

Backend abstraction

2 declarations

Parameters

1 declaration

Client parameters

Define the name of the server, along with an extra service identification blob. this is important that the hostname part is properly filled for security reason, as it allow to properly associate the remote side with the given certificate during a handshake.

The extra blob is useful to differentiate services running on the same host, but that might have different certificates given. It's only used as part of the X509 validation infrastructure.

This value is typically set by defaultParamsClient.

Allow the use of the Server Name Indication TLS extension during handshake, which allow the client to specify which host name, it's trying to access. This is useful to distinguish CNAME aliasing (e.g. web virtual host).

Default: True

Client tries to send early data in TLS 1.3 via sendData if possible. If not accepted by the server, the early data is automatically re-sent.

Default: False

Server parameters

Server accepts this size of early data in TLS 1.3. 0 (or lower) means that the server does not accept early data.

Default: 0

Lifetime in seconds for session tickets generated by the server. Acceptable value range is 0 to 604800 (7 days).

Default: 7200 (2 hours)

Shared

datadata Shared
#

Parameters that are common to clients and servers.

Instances2Show, Default
  • Show SharedDefined in tls-2.1.6 · Network.TLS.Parameters
  • Default SharedDefined in tls-2.1.6 · Network.TLS.Parameters

The list of certificates and private keys that a server will use as part of authentication to clients. Actual credentials that are used are selected dynamically from this list based on client capabilities. Additional credentials returned by onServerNameIndication are also considered.

When credential list is left empty (the default value), no key exchange can take place.

Default: mempty

Callbacks that may be used by a client to cache certificate validation results (positive or negative) and avoid expensive signature check. The default implementation does not have any caching.

See the default value of ValidationCache.

Additional extensions to be sent during the Hello sequence.

For a client this is always included in message ClientHello. For a server, this is sent in messages ServerHello or EncryptedExtensions based on the TLS version.

Default: []

Client hooks

datadata ClientHooks
#

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

Instances2Show, Default

This action is called when the a certificate request is received from the server. The callback argument is the information from the request. The server, at its discretion, may be willing to continue the handshake without a client certificate. Therefore, the callback is free to return Nothing to indicate that no client certificate should be sent, despite the server's request. In some cases it may be appropriate to get user consent before sending the certificate; the content of the user's certificate may be sensitive and intended only for specific servers.

The action should select a certificate chain of one of the given certificate types and one of the certificates in the chain should (if possible) be signed by one of the given distinguished names. Some servers, that don't have a narrow set of preferred issuer CAs, will send an empty DistinguishedName list, rather than send all the names from their trusted CA bundle. If the client does not have a certificate chaining to a matching CA, it may choose a default certificate instead.

Each certificate except the last should be signed by the following one. The returned private key must be for the first certificates in the chain. This key will be used to signing the certificate verify message.

The public key in the first certificate, and the matching returned private key must be compatible with one of the list of HashAndSignatureAlgorithm value when provided. TLS 1.3 changes the meaning of the list elements, adding explicit code points for each supported pair of hash and signature (public key) algorithms, rather than combining separate codes for the hash and key. For details see RFC 8446 section 4.2.3. When no compatible certificate chain is available, return Nothing if it is OK to continue without a client certificate. Returning a non-matching certificate should result in a handshake failure.

While the TLS version is not provided to the callback, the content of the signature_algorithms list provides a strong hint, since TLS 1.3 servers will generally list RSA pairs with a hash component of Intrinsic (0x08).

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

Default: returns Nothing anyway.

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.

The function is not expected to verify the key-usage extension of the end-entity certificate, as this depends on the dynamically-selected cipher and this part should not be cached. Key-usage verification is performed by the library internally.

Default: validateDefault

This action is called to validate DHE parameters when the server selected a finite-field group not part of the "Supported Groups Registry" or not part of supportedGroups list.

With TLS 1.3 custom groups have been removed from the protocol, so this callback is only used when the version negotiated is 1.2 or below.

The default behavior with (dh_p, dh_g, dh_size) and pub as follows:

  1. rejecting if dh_p is even

  2. rejecting unless 1 < dh_g && dh_g < dh_p - 1

  3. rejecting unless 1 < dh_p && pub < dh_p - 1

  4. rejecting if dh_size < 1024 (to prevent Logjam attack)

See RFC 7919 section 3.1 for recommandations.

Server hooks

datadata ServerHooks
#

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

Instances2Show, Default

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

The function is not expected to verify the key-usage extension of the certificate. This verification is performed by the library internally.

Default: returns the followings:

CertificateUsageReject (CertificateRejectOther "no client certificates expected")
valueonCipherChoosing :: ServerHooks -> 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.

Default: taking the head of ciphers.

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.

Default: returns mempty

datadata Measurement
#

record some data about this connection.

Instances2Eq, Show

Supported

datadata Supported
#

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

Instances3Eq, Show, Default

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

Versions should be listed in preference order, i.e. higher versions first.

Default: [TLS13,TLS12]

Supported compressions methods. By default only the "null" compression is supported, which means no compression will be performed. Allowing other compression method is not advised as it causes a connection failure when TLS 1.3 is negotiated.

Default: [nullCompression]

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 used to restrict accepted signatures received from the peer at TLS level (not in X.509 certificates), 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.

The list also impacts the selection of possible algorithms when generating signatures.

Note: with TLS 1.3 some algorithms have been deprecated and will not be used even when listed in the parameter: MD5, SHA-1, SHA-224, RSA PKCS#1, DSA.

Default:

  [ (HashIntrinsic,     SignatureEd448)
  , (HashIntrinsic,     SignatureEd25519)
  , (Struct.HashSHA256, SignatureECDSA)
  , (Struct.HashSHA384, SignatureECDSA)
  , (Struct.HashSHA512, SignatureECDSA)
  , (HashIntrinsic,     SignatureRSApssRSAeSHA512)
  , (HashIntrinsic,     SignatureRSApssRSAeSHA384)
  , (HashIntrinsic,     SignatureRSApssRSAeSHA256)
  , (Struct.HashSHA512, SignatureRSA)
  , (Struct.HashSHA384, SignatureRSA)
  , (Struct.HashSHA256, SignatureRSA)
  , (Struct.HashSHA1,   SignatureRSA)
  , (Struct.HashSHA1,   SignatureDSA)
  ]

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.

Default: True

The mode regarding extended main secret. Enabling this extension provides better security for TLS versions 1.2. TLS 1.3 provides the security properties natively and does not need the extension.

By default the extension is RequireEMS. So, the handshake will fail when the peer does not support the extension.

Default: RequireEMS

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.

Default: True

valuesupportedGroups :: Supported -> [Group]
#

A list of supported elliptic curves and finite-field groups in the preferred order.

The list is sent to the server as part of the "supported_groups" extension. It is used in both clients and servers to restrict accepted groups in DH key exchange. Up until TLS v1.2, it is also used by a client to restrict accepted elliptic curves in ECDSA signatures.

The default value includes all groups with security strength of 128 bits or more.

Default: [X25519,X448,P256,FFDHE2048,FFDHE3072,FFDHE4096,P384,FFDHE6144,FFDHE8192,P521]

Debug parameters

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

Default: Nothing

valuedebugPrintSeed :: DebugParams -> 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

Default: no printing

Shared parameters

0 declarations

Credentials

Session manager

Session data

datadata SessionData
#

Session data to resume

Instances5Eq, Show, Generic, Serialise, Rep
datadata SessionFlag
#

Some session flags

Constructors

  • SessionEMS

    Session created with Extended Main Secret

Instances6Enum, Eq, Show, Generic, Serialise, Rep
datadata TLS13TicketInfo
#
Instances5Eq, Show, Generic, Serialise, Rep

Validation Cache

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.

Types

0 declarations

For Supported

newtypenewtype Version
#

Versions known to TLS

Constructors

Instances6Eq, Ord, Show, Generic, Serialise, Rep
newtypenewtype Group
#

Constructors

Instances5Eq, Show, Generic, Serialise, Rep
datadata EMSMode
#

Client or server policy regarding Extended Main Secret

Constructors

  • NoEMS

    Extended Main Secret is not used

  • AllowEMS

    Extended Main Secret is allowed

  • RequireEMS

    Extended Main Secret is required

Instances2Eq, Show
  • Eq EMSModeDefined in tls-2.1.6 · Network.TLS.Parameters
  • Show EMSModeDefined in tls-2.1.6 · Network.TLS.Parameters

For parameters and hooks

newtypenewtype CertificateType
#

Some of the IANA registered code points for CertificateType are not currently supported by the library. Nor should they be, they're are either unwise, obsolete or both. There's no point in conveying these to the user in the client certificate request callback. The request callback will be filtered to exclude unsupported values. If the user cannot find a certificate for a supported code point, we'll go ahead without a client certificate and hope for the best, unless the user's callback decides to throw an exception.

Instances3Eq, Ord, Show
typetype HostName = String
#

Either a host name e.g., "haskell.org" or a numeric host address string consisting of a dotted decimal IPv4 address or an IPv6 address e.g., "192.168.0.1".

Advanced APIs

0 declarations

Backend

Information gathering

datadata Information
#

Information related to a running context, e.g. current cipher

Instances2Eq, Show

Getting certificates from a client, if any. Note that the certificates are not sent by a client on resumption even if client authentication is required. So, this API would be replaced by the one which can treat both cases of full-negotiation and resumption.

Negotiated

Post-handshake actions

Post-handshake certificate request with TLS 1.3. Returns True if the request was possible, i.e. if TLS 1.3 is used and the remote client supports post-handshake authentication.

Getting the "tls-server-end-point" channel binding for TLS 1.2 (RFC5929). For 1.3, there is no specifications for how to create it. In this implementation, a certificate chain without extensions is hashed like TLS 1.2.

Modifying hooks in context

datadata Hooks
#

A collection of hooks actions.

Instances1Default
datadata Logging
#

Hooks for logging

This is called when sending and receiving packets and IO

Instances1Default

Errors and exceptions

0 declarations

Errors

datadata TLSError
#

TLSError that might be returned through the TLS stack.

Prior to version 1.8.0, this type had an Exception instance. In version 1.8.0, this instance was removed, and functions in this library now only throw TLSException.

Constructors

Instances4Eq, Show, MonadError

Exceptions

datadata TLSException
#

TLS Exceptions. Some of the data constructors indicate incorrect use of the library, and the documentation for those data constructors calls this out. The others wrap TLSError with some kind of context to explain when the exception occurred.

Constructors

Instances3Eq, Show, Exception

Raw types

0 declarations

Compressions class

Crypto Key

datadata PubKey
#

Public key types known and used in X.509

Constructors

Instances3Eq, Show, ASN1Object
  • Eq PubKeyDefined in crypton-x509-1.7.7 · Data.X509.PublicKey
  • Show PubKeyDefined in crypton-x509-1.7.7 · Data.X509.PublicKey
  • ASN1Object PubKeyDefined in crypton-x509-1.7.7 · Data.X509.PublicKey
datadata PrivKey
#

Private key types known and used in X.509

Constructors

Instances3Eq, Show, ASN1Object
  • Eq PrivKeyDefined in crypton-x509-1.7.7 · Data.X509.PrivateKey
  • Show PrivKeyDefined in crypton-x509-1.7.7 · Data.X509.PrivateKey
  • ASN1Object PrivKeyDefined in crypton-x509-1.7.7 · Data.X509.PrivateKey

Ciphers & Predefined ciphers

Deprecated

4 declarations
typetype Bytes = ByteString
#

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

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

Constructors

  • ValidationChecks
    • 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.

Instances3Eq, Show, Default
datadata ValidationHooks
#

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

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

Constructors

Instances1Default