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

LicenseBSD-style
MaintainerVincent Hanquez <vincent@snarc.org>
Stabilityexperimental
Portabilityunknown
Safe HaskellNone
LanguageHaskell98

Network.TLS

Contents

Description

 
Synopsis

Context configuration

data ClientParams #

Constructors

ClientParams 

Fields

type Bytes = ByteString #

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

data ServerParams #

Constructors

ServerParams 

Fields

Instances
Show ServerParams # 
Instance details

Defined in Network.TLS.Parameters

Default ServerParams # 
Instance details

Defined in Network.TLS.Parameters

Methods

def :: ServerParams #

TLSParams ServerParams # 
Instance details

Defined in Network.TLS.Context

data DebugParams #

All settings should not be used in production

Constructors

DebugParams 

Fields

  • 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

Instances
Show DebugParams # 
Instance details

Defined in Network.TLS.Parameters

Default DebugParams # 
Instance details

Defined in Network.TLS.Parameters

Methods

def :: DebugParams #

data ClientHooks #

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

Constructors

ClientHooks 

Fields

  • 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"]'.

  • onCustomFFDHEGroup :: DHParams -> DHPublic -> IO GroupUsage

    This action is called to validate DHE parameters when the server selected a finite-field group not part of the "Supported Groups Registry". See RFC 7919 section 3.1 for recommandations.

Instances
Show ClientHooks # 
Instance details

Defined in Network.TLS.Parameters

Default ClientHooks # 
Instance details

Defined in Network.TLS.Parameters

Methods

def :: ClientHooks #

data ServerHooks #

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

Constructors

ServerHooks 

Fields

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

Instances
Show ServerHooks # 
Instance details

Defined in Network.TLS.Parameters

Default ServerHooks # 
Instance details

Defined in Network.TLS.Parameters

Methods

def :: ServerHooks #

data Supported #

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

Constructors

Supported 

Fields

  • 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 and finite-field groups in the preferred order. The default value is [X25519,P256,P384,P521]. X25519 and P256 provide 128-bit security which is strong enough until 2030. Both curves are fast because their backends are written in C.

Instances
Eq Supported # 
Instance details

Defined in Network.TLS.Parameters

Show Supported # 
Instance details

Defined in Network.TLS.Parameters

Default Supported # 
Instance details

Defined in Network.TLS.Parameters

Methods

def :: Supported #

data Hooks #

A collection of hooks actions.

Constructors

Hooks 

Fields

Instances
Default Hooks # 
Instance details

Defined in Network.TLS.Hooks

Methods

def :: Hooks #

data Handshake #

Instances
Eq Handshake # 
Instance details

Defined in Network.TLS.Struct

Show Handshake # 
Instance details

Defined in Network.TLS.Struct

data Logging #

Hooks for logging

This is called when sending and receiving packets and IO

Constructors

Logging 
Instances
Default Logging # 
Instance details

Defined in Network.TLS.Hooks

Methods

def :: Logging #

data Measurement #

record some data about this connection.

Constructors

Measurement 

Fields

Instances
Eq Measurement # 
Instance details

Defined in Network.TLS.Measurement

Show Measurement # 
Instance details

Defined in Network.TLS.Measurement

data GroupUsage #

Group usage callback possible return values.

Constructors

GroupUsageValid

usage of group accepted

GroupUsageInsecure

usage of group provides insufficient security

GroupUsageUnsupported String

usage of group rejected for other reason (specified as string)

GroupUsageInvalidPublic

usage of group with an invalid public value

Instances
Eq GroupUsage # 
Instance details

Defined in Network.TLS.Parameters

Show GroupUsage # 
Instance details

Defined in Network.TLS.Parameters

data CertificateUsage #

Certificate Usage callback possible returns values.

Constructors

CertificateUsageAccept

usage of certificate accepted

CertificateUsageReject CertificateRejectReason

usage of certificate rejected

raw types

data Header #

Instances
Eq Header # 
Instance details

Defined in Network.TLS.Struct

Methods

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

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

Show Header # 
Instance details

Defined in Network.TLS.Struct

Session

type SessionID = ByteString #

A session ID

data SessionData #

Session data to resume

Instances
Eq SessionData # 
Instance details

Defined in Network.TLS.Types

Show SessionData # 
Instance details

Defined in Network.TLS.Types

data SessionManager #

A session manager

Constructors

SessionManager 

Fields

Backend abstraction

data Backend #

Connection IO backend

Constructors

Backend 

Fields

Instances
HasBackend Backend # 
Instance details

Defined in Network.TLS.Backend

Context object

data Context #

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

ctxConnection :: Context -> Backend #

return the backend object associated with this context

class TLSParams a #

Minimal complete definition

getTLSCommonParams, getTLSRole, doHandshake, doHandshakeWith

class HasBackend a where #

Methods

initializeBackend :: a -> IO () #

getBackend :: a -> Backend #

Instances
HasBackend Handle # 
Instance details

Defined in Network.TLS.Backend

HasBackend Socket # 
Instance details

Defined in Network.TLS.Backend

HasBackend Backend # 
Instance details

Defined in Network.TLS.Backend

Creating a context

contextNew #

Arguments

:: (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 #

Arguments

:: (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 #

Arguments

:: (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

data Information #

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

data ClientRandom #

Instances
Eq ClientRandom # 
Instance details

Defined in Network.TLS.Struct

Show ClientRandom # 
Instance details

Defined in Network.TLS.Struct

data ServerRandom #

Instances
Eq ServerRandom # 
Instance details

Defined in Network.TLS.Struct

Show ServerRandom # 
Instance details

Defined in Network.TLS.Struct

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

Information about the current context

Credentials

credentialLoadX509 #

Arguments

:: 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 #

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

credentialLoadX509Chain #

Arguments

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

credentialLoadX509ChainFromMemory :: ByteString -> [ByteString] -> ByteString -> Either String Credential #

similar to credentialLoadX509FromMemory but also allow specifying chain certificates.

Initialisation and Termination of context

bye :: 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

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

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) #

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) #

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

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

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

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

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

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

Constructors

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

PubKeyX25519 PublicKey

X25519 public key

PubKeyX448 PublicKey

X448 public key

PubKeyEd25519 PublicKey

Ed25519 public key

PubKeyEd448 PublicKey

Ed448 public key

PubKeyUnknown OID ByteString

unrecognized format

Instances
Eq PubKey 
Instance details

Defined in Data.X509.PublicKey

Methods

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

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

Show PubKey 
Instance details

Defined in Data.X509.PublicKey

ASN1Object PubKey 
Instance details

Defined in Data.X509.PublicKey

data PrivKey #

Private key types known and used in X.509

Constructors

PrivKeyRSA PrivateKey

RSA private key

PrivKeyDSA PrivateKey

DSA private key

PrivKeyEC PrivKeyEC

EC private key

PrivKeyX25519 SecretKey

X25519 private key

PrivKeyX448 SecretKey

X448 private key

PrivKeyEd25519 SecretKey

Ed25519 private key

PrivKeyEd448 SecretKey

Ed448 private key

Instances
Eq PrivKey 
Instance details

Defined in Data.X509.PrivateKey

Methods

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

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

Show PrivKey 
Instance details

Defined in Data.X509.PrivateKey

ASN1Object PrivKey 
Instance details

Defined in Data.X509.PrivateKey

Compressions & Predefined compressions

data Compression #

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

Constructors

CompressionC a => Compression a 
Instances
Eq Compression # 
Instance details

Defined in Network.TLS.Compression

Show Compression # 
Instance details

Defined in Network.TLS.Compression

class CompressionC a where #

supported compression algorithms need to be part of this class

Methods

compressionCID :: a -> CompressionID #

compressionCDeflate :: a -> ByteString -> (a, ByteString) #

compressionCInflate :: a -> ByteString -> (a, ByteString) #

nullCompression :: Compression #

default null compression

Ciphers & Predefined ciphers

data Bulk #

Instances
Eq Bulk # 
Instance details

Defined in Network.TLS.Cipher

Methods

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

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

Show Bulk # 
Instance details

Defined in Network.TLS.Cipher

Methods

showsPrec :: Int -> Bulk -> ShowS #

show :: Bulk -> String #

showList :: [Bulk] -> ShowS #

newtype BulkStream #

data Hash #

Constructors

MD5 
SHA1 
SHA224 
SHA256 
SHA384 
SHA512 
SHA1_MD5 
Instances
Eq Hash # 
Instance details

Defined in Network.TLS.Crypto

Methods

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

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

Show Hash # 
Instance details

Defined in Network.TLS.Crypto

Methods

showsPrec :: Int -> Hash -> ShowS #

show :: Hash -> String #

showList :: [Hash] -> ShowS #

data Cipher #

Cipher algorithm

Instances
Eq Cipher # 
Instance details

Defined in Network.TLS.Cipher

Methods

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

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

Show Cipher # 
Instance details

Defined in Network.TLS.Cipher

type CipherID = Word16 #

Cipher identification

cipherAllowedForVersion :: Version -> Cipher -> Bool #

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

Versions

data Version #

Versions known to TLS

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

Constructors

SSL2 
SSL3 
TLS10 
TLS11 
TLS12 
Instances
Bounded Version # 
Instance details

Defined in Network.TLS.Types

Eq Version # 
Instance details

Defined in Network.TLS.Types

Methods

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

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

Ord Version # 
Instance details

Defined in Network.TLS.Types

Show Version # 
Instance details

Defined in Network.TLS.Types

Errors

data TLSError #

TLSError that might be returned through the TLS stack

Instances
Eq TLSError # 
Instance details

Defined in Network.TLS.Struct

Show TLSError # 
Instance details

Defined in Network.TLS.Struct

Exception TLSError # 
Instance details

Defined in Network.TLS.Struct

data KxError #

Instances
Show KxError # 
Instance details

Defined in Network.TLS.Crypto

Exceptions

data TLSException #

TLS Exceptions related to bad user usage or asynchronous errors

Constructors

Terminated Bool String TLSError

Early termination exception with the reason and the error associated

HandshakeFailed TLSError

Handshake failed for the reason attached

ConnectionNotEstablished

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.

Constructors

ValidationChecks 

Fields

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

Constructors

ValidationHooks 

Fields

Instances
Default ValidationHooks 
Instance details

Defined in Data.X509.Validation

X509 Validation Cache

data ValidationCache #

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

Constructors

ValidationCache 

Fields

Instances
Default ValidationCache 
Instance details

Defined in Data.X509.Validation.Cache

data ValidationCacheResult #

The result of a cache query

Constructors

ValidationCachePass

cache allow this fingerprint to go through

ValidationCacheDenied String

cache denied this fingerprint for further validation

ValidationCacheUnknown

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

data Group #

Instances
Eq Group # 
Instance details

Defined in Network.TLS.Crypto.Types

Methods

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

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

Show Group # 
Instance details

Defined in Network.TLS.Crypto.Types

Methods

showsPrec :: Int -> Group -> ShowS #

show :: Group -> String #

showList :: [Group] -> ShowS #