packages feed

tls 2.5.5 → 2.6.4

raw patch · 25 files changed

Files

CHANGELOG.md view
@@ -1,7 +1,16 @@ # Change log for "tls" -## Version 2.5.5+## Version 2.6.4 +* An interrupted receive breaks the receive side and wakes PHA waiters.+  [#668](https://github.com/haskell-tls/hs-tls/pull/668)+* bye gives up on close_notify with the backend's SendWith.+  [#670](https://github.com/haskell-tls/hs-tls/pull/670)+* handshakeWith, recvDataWith, sendDataWith and byeWith give up on an STM action.+  [#672](https://github.com/haskell-tls/hs-tls/pull/672)++## Version 2.6.3+ * Never wrap around the RTT of a ticket, and cap it at 10 seconds.   [#661](https://github.com/haskell-tls/hs-tls/pull/661) * Keep contexts closable after failures of the backend.@@ -10,20 +19,44 @@   [#664](https://github.com/haskell-tls/hs-tls/pull/664) * Throw the exception of a failed send again on later sends.   [#665](https://github.com/haskell-tls/hs-tls/pull/665)+* bye sends close_notify when the backend gives up by itself.+  [#666](https://github.com/haskell-tls/hs-tls/pull/666) -## Version 2.5.4+## Version 2.6.2 +* Make bye robust after a failed handshake or a vanished peer.+  [#657](https://github.com/haskell-tls/hs-tls/pull/657)+* Close the connection when post-handshake auth fails.+  [#659](https://github.com/haskell-tls/hs-tls/pull/659)++## Version 2.6.1+ * Use up a session for 0-RTT only after checking the ClientHello.   [#655](https://github.com/haskell-tls/hs-tls/pull/655) -## Version 2.5.3+## Version 2.6.0 +The early data sizes are `Word32`, and `HasBackend` has a new method with a default.+`bye` waits for the last handshake messages only with a backend which has it.+ * Count milliseconds from the base without overflowing a 32-bit time_t.   [#644](https://github.com/haskell-tls/hs-tls/pull/644)+* Use Word32 for the early data sizes.+  [#645](https://github.com/haskell-tls/hs-tls/pull/645) * Use a generator of no small order in the custom DH prime test.   [#646](https://github.com/haskell-tls/hs-tls/pull/646)+* Let bye give up on a receive without interrupting it.+  [#647](https://github.com/haskell-tls/hs-tls/pull/647) * Encode the test certificates as v3.   [#648](https://github.com/haskell-tls/hs-tls/pull/648)+* Take the STM action last in getBackendRecvWith, whatever its result.+  [#650](https://github.com/haskell-tls/hs-tls/pull/650)+* Give up in bye only through getBackendRecvWith, and give Socket one.+  [#651](https://github.com/haskell-tls/hs-tls/pull/651)+* Use the native I/O manager for the tests on Windows.+  [#652](https://github.com/haskell-tls/hs-tls/pull/652)+* Bound network-run and hpke for the utilities.+  [#653](https://github.com/haskell-tls/hs-tls/pull/653)  ## Version 2.5.2 
Network/TLS.hs view
@@ -8,9 +8,9 @@ -- 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.+-- It currently implements TLS 1.2 and TLS 1.3, supports RSA and+-- ephemeral (elliptic curve and finite field) Diffie-Hellman key+-- exchanges, and many extensions. -- -- The typical usage is: --@@ -18,7 +18,7 @@ -- > ctx <- contextNew socket <params> -- > handshake ctx -- > ... (using recvData and sendData)--- > bye+-- > bye ctx module Network.TLS (     -- * Basic APIs     Context,@@ -29,11 +29,19 @@     closeNotifyReceived,     bye, +    -- * Giving up on an event+    handshakeWith,+    sendDataWith,+    recvDataWith,+    byeWith,+     -- * Exceptions     -- $exceptions      -- * Backend abstraction     HasBackend (..),+    RecvWith (..),+    SendWith (..),     Backend (..),      -- * Parameters@@ -332,7 +340,12 @@ import Data.X509 (ExtKeyUsagePurpose (..), PrivKey (..), PubKey (..)) import Data.X509.Validation hiding (HostName, defaultHooks) -import Network.TLS.Backend (Backend (..), HasBackend (..))+import Network.TLS.Backend (+    Backend (..),+    HasBackend (..),+    RecvWith (..),+    SendWith (..),+ ) import Network.TLS.Cipher import Network.TLS.Compression (     Compression (..),@@ -375,7 +388,7 @@ import Network.TLS.Types import Network.TLS.X509 -{-# DEPRECATED Bytes "Use Data.ByteString.Bytestring instead of Bytes." #-}+{-# DEPRECATED Bytes "Use Data.ByteString.ByteString instead of Bytes." #-} type Bytes = ByteString  -- | Getting certificates from a client, if any.@@ -385,11 +398,13 @@ getClientCertificateChain :: Context -> IO (Maybe CertificateChain) getClientCertificateChain ctx = usingState_ ctx S.getClientCertificateChain +-- | Getting certificates from a server, if any.+--   A server sends no certificate on resumption; then this returns 'Nothing'. getServerCertificateChain :: Context -> IO (Maybe CertificateChain) getServerCertificateChain ctx = usingState_ ctx S.getServerCertificateChain  -- $exceptions --     Since 1.8.0, this library only throws exceptions of type 'TLSException'.---     In the common case where the chosen backend is socket, 'IOException'+--     In the common case where the chosen backend is socket, 'Control.Exception.IOException' --     may be thrown as well. This happens because the backend for sockets, --     opaque to most modules in the @tls@ library, throws those exceptions.
Network/TLS/Backend.hs view
@@ -1,8 +1,12 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE RankNTypes #-}+ -- | A Backend represents a unified way to do IO on different -- types without burdening our calling API with multiple -- ways to initialize a new context. -- -- Typically, a backend provides:+-- -- * a way to read data -- * a way to write data -- * a way to close the stream@@ -10,8 +14,11 @@ module Network.TLS.Backend (     HasBackend (..),     Backend (..),+    RecvWith (..),+    SendWith (..), ) where +import Control.Concurrent.STM (STM) import qualified Data.ByteString as B import qualified Network.Socket as Network import qualified Network.Socket.ByteString as Network@@ -28,13 +35,54 @@     , backendSend :: ByteString -> IO ()     -- ^ Send a bytestring through the connection.     , backendRecv :: Int -> IO ByteString-    -- ^ Receive specified number of bytes from the connection.+    -- ^ Receive the specified number of bytes from the connection.+    -- Fewer bytes are returned only at the end of the stream.+    --+    -- An 'Control.Exception.IOException' means a broken connection: the+    -- context is marked EOF and 'Network.TLS.bye' sends nothing.  Other+    -- exceptions, including asynchronous ones, pass through as they are,+    -- and 'Network.TLS.bye' can still send close_notify.  'Network.TLS.recvData'+    -- may be called again only if the exception was thrown before any byte+    -- of a record was taken.  Thrown inside the body of a record, it is+    -- thrown again by later receives (an asynchronous one as a TLS error).     } +-- | Types which a 'Network.TLS.Context' can be created on. class HasBackend a where+    -- | Prepare the connection before use.     initializeBackend :: a -> IO ()++    -- | The IO functions of the connection.     getBackend :: a -> Backend +    -- | A receive which can give up.  With it, 'Network.TLS.bye' waits for the+    --   peer's last handshake messages without interrupting a receive.+    --+    -- @since 2.6.0+    getBackendRecvWith :: a -> Maybe RecvWith+    getBackendRecvWith _ = Nothing++    -- | A send which can give up.  With it, 'Network.TLS.bye' gives up on+    --   close_notify when the peer does not read.+    --+    -- @since 2.6.4+    getBackendSendWith :: a -> Maybe SendWith+    getBackendSendWith _ = Nothing++-- | A receive of the specified number of bytes which gives up once the+--   'STM' action succeeds, answering what it gave as 'Left'.  Bytes+--   already received by then are answered instead.+--+-- @since 2.6.0+newtype RecvWith = RecvWith (forall g. Int -> STM g -> IO (Either g ByteString))++-- | A send of all the bytes which gives up once the 'STM' action+--   succeeds, answering what it gave as 'Left'.  Part of the bytes may+--   have been sent by then.+--+-- @since 2.6.4+newtype SendWith = SendWith (forall g. ByteString -> STM g -> IO (Either g ()))+ instance HasBackend Backend where     initializeBackend _ = return ()     getBackend = id@@ -60,6 +108,25 @@                 if B.null r                     then return []                     else (r :) <$> loop (left - B.length r)+#if MIN_VERSION_network(3,2,12)+    getBackendRecvWith sock = Just $ RecvWith recvAllWith+      where+        recvAllWith n giveUp = loop n []+          where+            done = return . Right . B.concat . reverse+            loop 0 acc = done acc+            loop left acc = do+                r <- Network.recvWith sock left giveUp+                case r of+                    -- Bytes already received are answered, not 'Left'.+                    Left g+                        | null acc -> return $ Left g+                        | otherwise -> done acc+                    Right bs+                        | B.null bs -> done acc+                        | otherwise -> loop (left - B.length bs) (bs : acc)+    getBackendSendWith sock = Just $ SendWith $ Network.sendAllWith sock+#endif  instance HasBackend Handle where     initializeBackend handle = hSetBuffering handle NoBuffering
Network/TLS/Context.hs view
@@ -74,6 +74,7 @@ ) where  import Control.Concurrent.MVar+import Control.Concurrent.STM import Control.Monad.State.Strict import Data.IORef import qualified Data.X509 as X509@@ -147,7 +148,7 @@     doRequestCertificateAsync = requestCertificateAsyncServer     doPostHandshakeAuthWith = \_ _ _ -> return () --- | create a new context using the backend and parameters specified.+-- | Create a new context using the backend and parameters specified. contextNew     :: (MonadIO m, HasBackend backend, TLSParams params)     => backend@@ -175,6 +176,9 @@     eof <- newIORef False     closeNotify <- newIORef False     txBroken <- newIORef Nothing+    rxBroken <- newIORef Nothing+    rxGiveUp <- newIORef Nothing+    txGiveUp <- newIORef Nothing     established <- newIORef NotEstablished     stats <- newIORef newMeasurement     needEmptyPacket <- newIORef False@@ -185,7 +189,7 @@     recvActionsRef <- newIORef []     appDataRef <- newIORef []     sendActionRef <- newIORef Nothing-    locks <- Locks <$> newMVar () <*> newMVar () <*> newMVar ()+    locks <- Locks <$> newTMVarIO () <*> newTMVarIO () <*> newTMVarIO ()     st13ref <- newIORef defaultTLS13State     mylimref <- newRecordLimitRef $ Just defaultRecordSizeLimit     peerlimref <- newRecordLimitRef $ Just defaultRecordSizeLimit@@ -202,6 +206,10 @@     let ctx =             Context                 { ctxBackend = getBackend backend+                , ctxBackendRecvWith = getBackendRecvWith backend+                , ctxBackendSendWith = getBackendSendWith backend+                , ctxRxGiveUp = rxGiveUp+                , ctxTxGiveUp = txGiveUp                 , ctxShared = shared                 , ctxSupported = supported                 , ctxDebug = debug@@ -216,6 +224,7 @@                 , ctxEOF_ = eof                 , ctxCloseNotify_ = closeNotify                 , ctxTxBroken_ = txBroken+                , ctxRxBroken_ = rxBroken                 , ctxEstablished_ = established                 , ctxNeedEmptyPacket = needEmptyPacket                 , ctxHooks = hooks@@ -274,7 +283,7 @@  -- | Getting the "tls-unique" channel binding for TLS 1.2 (RFC5929). --   For TLS 1.3, 'Nothing' is returned.---   'supportedExtendedMainSecret' must be 'RequireEMS'+--   'supportedExtendedMainSecret' must be 'RequireEMS'. --   But in general, it is highly recommended to upgrade to TLS 1.3 --   and use the "tls-exporter" channel binding via 'getTLSExporter'. getTLSUnique :: Context -> IO (Maybe ByteString)
Network/TLS/Context/Internal.hs view
@@ -21,11 +21,17 @@     PendingRecvAction (..),     RecordLayer (..),     Locks (..),+    GiveUp (..),+    GaveUp (..),+    gaveUpSending,+    withRxGiveUp,+    withTxGiveUp,     RoleParams (..),     ctxEOF,     ctxCloseNotify,     ctxTxBroken,     ctxTxBrokenBy,+    ctxRxBrokenBy,     ctxEstablished,     withLog,     ctxWithHooks,@@ -33,6 +39,9 @@     setEOF,     setCloseNotify,     setTxBroken,+    setRxBroken,+    wakePHA,+    throwBroken,     setEstablished,     skipEarlyData,     contextFlush,@@ -43,10 +52,13 @@     updateMeasure,     withMeasure,     withReadLock,+    withReadLockGivingUp,     tryWithReadLock,     withWriteLock,+    withWriteLockGivingUp,     withStateLock,     withRWLock,+    withRWLockGivingUp,      -- * information     Information (..),@@ -97,6 +109,7 @@ ) where  import Control.Concurrent.MVar+import Control.Concurrent.STM import qualified Control.Exception as E import Control.Monad.State.Strict import Data.ByteArray (convert)@@ -124,13 +137,23 @@ import Network.TLS.Util import Network.TLS.X509 (CertificateChain) --- | A TLS Context keep tls specific state, parameters and backend information.+-- | A TLS Context keeps TLS specific state, parameters and backend information. data Context     = forall a.       Monoid a =>     Context     { ctxBackend :: Backend     -- ^ return the backend object associated with this context+    , ctxBackendRecvWith :: Maybe RecvWith+    -- ^ 'getBackendRecvWith' of the backend+    , ctxBackendSendWith :: Maybe SendWith+    -- ^ 'getBackendSendWith' of the backend+    , ctxRxGiveUp :: IORef (Maybe GiveUp)+    -- ^ what a receive through 'ctxBackendRecvWith' gives up on, set+    -- with the read lock taken+    , ctxTxGiveUp :: IORef (Maybe (STM ()))+    -- ^ what a send through 'ctxBackendSendWith' gives up on, set with+    -- the write lock taken     , ctxSupported :: Supported     , ctxShared :: Shared     , ctxDebug :: DebugParams@@ -143,6 +166,8 @@     , ctxTxBroken_ :: IORef (Maybe E.SomeException)     -- ^ the exception of the first failed send, which left the TX record     -- state ahead of the peer.+    , ctxRxBroken_ :: IORef (Maybe E.SomeException)+    -- ^ the exception which interrupted a receive inside a record.     , ctxEstablished_ :: IORef Established     -- ^ has the handshake been done and been successful.     , ctxTxRecordState :: MVar RecordState@@ -193,12 +218,46 @@     , doPostHandshakeAuthWith_ :: Context -> Handshake13R -> IO ()     } +-- | What a receive gives up on: before the first byte of a record, and+-- inside a record, which leaves the stream there.+data GiveUp = GiveUp+    { giveUpBetween :: STM ()+    , giveUpInside :: STM ()+    }++-- | Thrown by a receive which has given up before the first byte of a+-- record, and caught by the caller which set 'ctxRxGiveUp'.+data GaveUp = GaveUp deriving (Show)++instance E.Exception GaveUp++-- | Thrown by a send which has given up, which may have sent part of a+-- record.+gaveUpSending :: TLSException+gaveUpSending = PostHandshake $ Error_Misc "gave up sending"++-- | Running with a give-up for the receives; the read lock is taken.+withRxGiveUp :: Context -> GiveUp -> IO a -> IO a+withRxGiveUp ctx = withGiveUpIn (ctxRxGiveUp ctx)++-- | Running with a give-up for the sends; the write lock is taken.+withTxGiveUp :: Context -> STM () -> IO a -> IO a+withTxGiveUp ctx = withGiveUpIn (ctxTxGiveUp ctx)++withGiveUpIn :: IORef (Maybe b) -> b -> IO a -> IO a+withGiveUpIn ref g f =+    E.bracket+        (atomicModifyIORef' ref (\old -> (Just g, old)))+        (writeIORef ref)+        (const f)++-- | 'TMVar's, so that a wait for them can be given up on. data Locks = Locks-    { lockWrite :: MVar ()+    { lockWrite :: TMVar ()     -- ^ lock to use for writing data (including updating the state)-    , lockRead :: MVar ()+    , lockRead :: TMVar ()     -- ^ lock to use for reading data (including updating the state)-    , lockState :: MVar ()+    , lockState :: TMVar ()     -- ^ lock used during read/write when receiving and sending packet.     -- it is usually nested in a write or read lock.     }@@ -325,8 +384,8 @@  data Established     = NotEstablished-    | EarlyDataAllowed Int -- server: remaining 0-RTT bytes allowed-    | EarlyDataNotAllowed Int -- server: remaining 0-RTT bytes allowed to skip+    | EarlyDataAllowed Word32 -- server: remaining 0-RTT bytes allowed+    | EarlyDataNotAllowed Word32 -- server: remaining 0-RTT bytes allowed to skip     | EarlyDataSending     | Established     deriving (Eq, Show)@@ -419,8 +478,13 @@         _ -> return Nothing  contextSend :: Context -> ByteString -> IO ()-contextSend c b =-    updateMeasure c (addBytesSent $ B.length b) >> (backendSend $ ctxBackend c) b+contextSend c b = do+    updateMeasure c (addBytesSent $ B.length b)+    mgiveUp <- readIORef $ ctxTxGiveUp c+    case (mgiveUp, ctxBackendSendWith c) of+        (Just giveUp, Just (SendWith sendWith)) ->+            sendWith b giveUp >>= either (\_ -> E.throwIO gaveUpSending) return+        _ -> backendSend (ctxBackend c) b  contextRecv :: Context -> Int -> IO ByteString contextRecv c sz = updateMeasure c (addBytesReceived sz) >> (backendRecv $ ctxBackend c) sz@@ -431,7 +495,11 @@ setEOF :: Context -> IO () setEOF ctx = do     writeIORef (ctxEOF_ ctx) True-    -- Wake up those waiting for a pending post-handshake authentication.+    wakePHA ctx++-- | Wake up those waiting for a pending post-handshake authentication.+wakePHA :: Context -> IO ()+wakePHA ctx = do     mpha <- tls13stPHA <$> readIORef (ctxTLS13State ctx)     forM_ mpha $ \(mv, err) -> void $ tryPutMVar mv $ PHAFailed err @@ -450,6 +518,22 @@ setTxBroken :: Context -> E.SomeException -> IO () setTxBroken ctx e = atomicModifyIORef' (ctxTxBroken_ ctx) $ \m -> (m <|> Just e, ()) +ctxRxBrokenBy :: Context -> IO (Maybe E.SomeException)+ctxRxBrokenBy ctx = readIORef $ ctxRxBroken_ ctx++-- | Throw again the exception which broke a direction.  An asynchronous+-- one was meant for the thread which got it, so it is replaced.+throwBroken :: String -> E.SomeException -> IO a+throwBroken msg e = E.throwIO $ case E.fromException e of+    Just (E.SomeAsyncException _) -> E.toException $ PostHandshake $ Error_Misc msg+    Nothing -> e++-- | The stream is left inside a record, so nothing more can be received.+setRxBroken :: Context -> E.SomeException -> IO ()+setRxBroken ctx e = do+    atomicModifyIORef' (ctxRxBroken_ ctx) $ \m -> (m <|> Just e, ())+    wakePHA ctx+ ctxEstablished :: Context -> IO Established ctxEstablished ctx = readIORef $ ctxEstablished_ ctx @@ -478,7 +562,7 @@         _ -> return False   where     -- The AEAD tag and the inner content type are not early data.-    cost = max 1 (len - 17)+    cost = fromIntegral $ max 1 (len - 17)  withLog :: Context -> (Logging -> IO ()) -> IO () withLog ctx f = ctxWithHooks ctx (f . hookLogging)@@ -564,9 +648,23 @@ getStateRNG :: Context -> Int -> IO ByteString getStateRNG ctx n = usingState_ ctx $ genRandom n +withLock :: TMVar () -> IO a -> IO a+withLock lock = E.bracket_ (atomically $ takeTMVar lock) (atomically $ putTMVar lock ())++-- | Taking the lock unless the 'STM' action succeeds first.+withLockGivingUp :: TMVar () -> STM g -> IO a -> IO (Either g a)+withLockGivingUp lock giveUp f = E.mask $ \restore -> do+    r <- atomically $ (Right <$> takeTMVar lock) `orElse` (Left <$> giveUp)+    case r of+        Left g -> return $ Left g+        Right () -> (Right <$> restore f) `E.finally` atomically (putTMVar lock ())+ withReadLock :: Context -> IO a -> IO a-withReadLock ctx f = withMVar (lockRead $ ctxLocks ctx) (const f)+withReadLock ctx = withLock (lockRead $ ctxLocks ctx) +withReadLockGivingUp :: Context -> STM g -> IO a -> IO (Either g a)+withReadLockGivingUp ctx = withLockGivingUp (lockRead $ ctxLocks ctx)+ -- | Like 'withReadLock', but returns 'Nothing' immediately instead of waiting -- when another thread already holds the read lock. --@@ -579,22 +677,23 @@ -- is better than waiting for the current reader, which may hold the lock for -- arbitrarily long.  'bye' is the only such caller; see the note there. tryWithReadLock :: Context -> IO a -> IO (Maybe a)-tryWithReadLock ctx f = E.bracket acquire release $ \mlock -> case mlock of-    Nothing -> return Nothing-    Just _ -> Just <$> f-  where-    lock = lockRead $ ctxLocks ctx-    acquire = tryTakeMVar lock-    release = mapM_ (putMVar lock)+tryWithReadLock ctx f = either (const Nothing) Just <$> withReadLockGivingUp ctx (return ()) f  withWriteLock :: Context -> IO a -> IO a-withWriteLock ctx f = withMVar (lockWrite $ ctxLocks ctx) (const f)+withWriteLock ctx = withLock (lockWrite $ ctxLocks ctx) +withWriteLockGivingUp :: Context -> STM g -> IO a -> IO (Either g a)+withWriteLockGivingUp ctx = withLockGivingUp (lockWrite $ ctxLocks ctx)+ withRWLock :: Context -> IO a -> IO a withRWLock ctx f = withReadLock ctx $ withWriteLock ctx f +withRWLockGivingUp :: Context -> STM g -> IO a -> IO (Either g a)+withRWLockGivingUp ctx giveUp f =+    join <$> withReadLockGivingUp ctx giveUp (withWriteLockGivingUp ctx giveUp f)+ withStateLock :: Context -> IO a -> IO a-withStateLock ctx f = withMVar (lockState $ ctxLocks ctx) (const f)+withStateLock ctx = withLock (lockState $ ctxLocks ctx)  tls13orLater :: MonadIO m => Context -> m Bool tls13orLater ctx = do
Network/TLS/Core.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-} {-# OPTIONS_HADDOCK hide #-}  module Network.TLS.Core (@@ -10,7 +11,9 @@      -- * Initialisation and Termination of context     bye,+    byeWith,     handshake,+    handshakeWith,      -- * Application Layer Protocol Negotiation     getNegotiatedProtocol,@@ -20,7 +23,9 @@      -- * High level API     sendData,+    sendDataWith,     recvData,+    recvDataWith,     recvData',     closeNotifyReceived,     updateKey,@@ -31,21 +36,30 @@ ) where  import Control.Concurrent (forkIO)-import Control.Concurrent.MVar+import Control.Concurrent.STM import qualified Control.Exception as E import Control.Monad.State.Strict import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C8 import qualified Data.ByteString.Lazy as L import Data.IORef-import System.Timeout+import GHC.IO.Exception (IOErrorType (..), IOException (..))  import Network.TLS.Context import Network.TLS.Context.Internal (+    GaveUp (..),+    GiveUp (..),     PHAResult (..),     ctxTxBroken,+    gaveUpSending,     incrementTLS13KeyUpdateCount,     resetTLS13KeyUpdateCount,+    wakePHA,+    withRWLockGivingUp,+    withReadLockGivingUp,+    withRxGiveUp,+    withTxGiveUp,+    withWriteLockGivingUp,  ) import Network.TLS.Extension import Network.TLS.Handshake@@ -73,53 +87,117 @@  ) import Network.TLS.Util (catchException, mapChunks_) --- | Handshake for a new TLS connection+-- | 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'.+-- Don't use this function as the acquire resource of 'Control.Exception.bracket'. handshake :: MonadIO m => Context -> m ()-handshake ctx = do+handshake ctx = liftIO $ do     handshake_ ctx     -- Trying to receive an alert of client authentication failure-    liftIO $ do-        role <- usingState_ ctx getRole-        tls13 <- tls13orLater ctx-        sentClientCert <- tls13stSentClientCert <$> getTLS13State ctx-        when (role == ClientRole && tls13 && sentClientCert) $ do-            rtt <- getRTT ctx-            -- We are only willing to wait 'rtt' for the alert, but a receive-            -- must not be abandoned once it has started.  Records are read-            -- length-prefixed and the record layer keeps no receive buffer, so-            -- an aborted receive loses the bytes it has already taken off the-            -- transport and leaves the stream positioned inside a record.-            -- Every later read is then misframed, and the connection is dead-            -- with a spurious protocol error.-            ---            -- So the receive runs in its own thread and we stop waiting for it-            -- rather than interrupting it.  It holds the read lock, which keeps-            -- it the only reader and makes the next receive wait for it to-            -- finish; its outcome is left in 'tls13stPendingRecv' for that-            -- receive to pick up.-            done <- newEmptyMVar-            void $ forkIO $ withReadLock ctx $ do-                r <- E.try $ recvData13 ctx-                modifyTLS13State ctx $ \st ->-                    st-                        { tls13stPendingRecv = case r of-                            Right dat -> PendingRecvData dat-                            Left err -> PendingRecvError err-                        }-                putMVar done ()-            arrived <- timeout rtt $ takeMVar done-            -- Still report the authentication failure from 'handshake' itself-            -- whenever it did arrive in time.-            when (isJust arrived) $ do-                pending <- tls13stPendingRecv <$> getTLS13State ctx-                case pending of-                    PendingRecvError err -> do-                        modifyTLS13State ctx $ \st -> st{tls13stPendingRecv = NoPendingRecv}-                        E.throwIO err-                    _ -> return ()+    authFailureExpected ctx >>= \expected -> when expected $ waitAuthFailure ctx +-- | 'handshake' which gives up once the 'STM' action succeeds, also while+-- waiting for the locks or in a send.  After 'Left', the context cannot be+-- used.  With a backend which can neither give up on a receive nor on a+-- send, only the wait for the locks is given up on.+--+-- @since 2.6.4+handshakeWith :: MonadIO m => Context -> STM a -> m (Either a ())+handshakeWith ctx giveUp = liftIO $ do+    (giveUp', given) <- recording giveUp+    r <-+        E.try $+            withRWLockGivingUp ctx giveUp $+                withTxGiveUp ctx giveUp' $+                    withRxGiveUp ctx (GiveUp giveUp' giveUp') $+                        handshakeLocked ctx+    case r of+        Left e -> given >>= maybe (E.throwIO (e :: E.SomeException)) (return . Left)+        Right (Left a) -> return $ Left a+        Right (Right ()) -> do+            expected <- authFailureExpected ctx+            if not expected+                then return $ Right ()+                else case ctxBackendRecvWith ctx of+                    Nothing -> Right <$> waitAuthFailure ctx+                    Just _ -> waitAuthFailureGivingUp ctx giveUp' given++-- | Recording what the 'STM' action gave, for one which has given up.+recording :: STM a -> IO (STM (), IO (Maybe a))+recording giveUp = do+    var <- newTVarIO Nothing+    return (giveUp >>= writeTVar var . Just, readTVarIO var)++authFailureExpected :: Context -> IO Bool+authFailureExpected ctx = do+    role <- usingState_ ctx getRole+    tls13 <- tls13orLater ctx+    sentClientCert <- tls13stSentClientCert <$> getTLS13State ctx+    return $ role == ClientRole && tls13 && sentClientCert++-- | Waiting 'rtt' for an alert of client authentication failure.+waitAuthFailure :: Context -> IO ()+waitAuthFailure ctx = do+    rtt <- getRTT ctx+    -- We are only willing to wait 'rtt' for the alert, but a receive+    -- must not be abandoned once it has started.  Records are read+    -- length-prefixed and the record layer keeps no receive buffer, so+    -- an aborted receive loses the bytes it has already taken off the+    -- transport and leaves the stream positioned inside a record.+    -- Every later read is then misframed, and the connection is dead+    -- with a spurious protocol error.+    --+    -- So the receive runs in its own thread and we stop waiting for it+    -- rather than interrupting it.  It holds the read lock, which keeps+    -- it the only reader and makes the next receive wait for it to+    -- finish; its outcome is left in 'tls13stPendingRecv' for that+    -- receive to pick up.+    done <- newEmptyTMVarIO+    void $ forkIO $ withReadLock ctx $ do+        r <- E.try $ recvData13 ctx+        modifyTLS13State ctx $ \st ->+            st+                { tls13stPendingRecv = case r of+                    Right dat -> PendingRecvData dat+                    Left err -> PendingRecvError err+                }+        atomically $ putTMVar done ()+    late <- registerDelay rtt+    arrived <-+        atomically $+            (Just <$> takeTMVar done) `orElse` (Nothing <$ (readTVar late >>= check))+    -- Still report the authentication failure from 'handshake' itself+    -- whenever it did arrive in time.+    when (isJust arrived) $ do+        pending <- tls13stPendingRecv <$> getTLS13State ctx+        case pending of+            PendingRecvError err -> do+                modifyTLS13State ctx $ \st -> st{tls13stPendingRecv = NoPendingRecv}+                E.throwIO err+            _ -> return ()++-- | 'waitAuthFailure' with a backend which can give up: no thread, since+-- the receive gives up only before a record begins.  Once begun, only the+-- caller's give-up ends it, and the context cannot be used then.+waitAuthFailureGivingUp :: Context -> STM () -> IO (Maybe a) -> IO (Either a ())+waitAuthFailureGivingUp ctx giveUp given = do+    rtt <- getRTT ctx+    late <- registerDelay rtt+    let between = (readTVar late >>= check) `orElse` giveUp+    r <-+        withReadLockGivingUp ctx giveUp $+            withRxGiveUp ctx (GiveUp between giveUp) $+                E.try $+                    recvData13 ctx+    case r of+        Left () -> return $ Right ()+        Right (Right dat) -> do+            modifyTLS13State ctx $ \st -> st{tls13stPendingRecv = PendingRecvData dat}+            return $ Right ()+        Right (Left e)+            | isJust (E.fromException @GaveUp e) -> return $ Right ()+            | otherwise -> given >>= maybe (E.throwIO e) (return . Left)+ rttFactor :: Int rttFactor = 3 @@ -134,25 +212,35 @@     let rtt' = max 10 $ fromIntegral $ min maxWaitRTT rtt     return (rtt' * rttFactor * 1000) -- ms to us --- | 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.+-- | Notify the peer that this side wants to close the connection, by+-- sending close_notify.  It should be called before closing the backend.+-- This doesn't actually close the backend.  Nothing is sent after a failed+-- handshake or a received alert, and a peer which has gone already is not+-- an error.  With 'getBackendSendWith', close_notify is given up on when+-- the peer does not read it for a second or so. -- -- Proper usage is as follows: -- -- > ctx <- contextNew <backend> <params> -- > handshake ctx -- > ...--- > bye+-- > bye ctx ----- The following code ensures nothing but is no harm.+-- The following code guarantees nothing more, but does no harm. -- -- > bracket (contextNew <backend> <params>) bye $ \ctx -> do -- >   handshake ctx -- >   ... bye :: MonadIO m => Context -> m ()-bye ctx = liftIO $ do+bye ctx = byeWith ctx (retry :: STM ())++-- | 'bye' which also gives up once the 'STM' action succeeds, on the+-- peer's last handshake messages and on close_notify alike.+--+-- @since 2.6.4+byeWith :: MonadIO m => Context -> STM a -> m ()+byeWith ctx giveUp0 = liftIO $ do+    let giveUp = void giveUp0     eof <- ctxEOF ctx     -- After a failed send, nothing is sent, so nothing is waited for either.     broken <- ctxTxBroken ctx@@ -161,13 +249,13 @@         role <- usingState_ ctx getRole         if role == ClientRole             then do-                withWriteLock ctx $ sendCFifNecessary ctx+                sending ctx giveUp $ sendCFifNecessary ctx                 -- receiving NewSessionTicket                 let chk = tls13stRecvNST <$> getTLS13State ctx                 recvNST <- chk                 unless recvNST $ do                     rtt <- getRTT ctx-                    tryRecvHS13 rtt chk+                    tryRecvHS13 giveUp rtt chk             else do                 -- receiving Client Finished                 let chk = tls13stRecvCF <$> getTLS13State ctx@@ -176,8 +264,8 @@                     -- no chance to measure RTT before receiving CF                     -- fixme: 1sec is good enough?                     let rtt = 1000000-                    tryRecvHS13 rtt chk-    bye_ ctx+                    tryRecvHS13 giveUp rtt chk+    bye_ ctx giveUp   where     -- Receiving these messages only improves the chances of a later session     -- resumption, so giving up on them costs nothing important.  We give up in@@ -195,26 +283,60 @@     -- abandon the receive.  Abandoning it can stop the connection part way     -- through a record, after which nothing can be read from it again -- which     -- is acceptable only because we are closing the connection here anyway.-    tryRecvHS13 :: Int -> IO Bool -> IO ()-    tryRecvHS13 rtt chk =-        void $ tryWithReadLock ctx $ timeout rtt $ recvHS13 ctx chk+    --+    -- A backend which can give up on a receive does so after 'rtt'; with+    -- one which cannot, the messages are not waited for at all.+    tryRecvHS13 :: STM () -> Int -> IO Bool -> IO ()+    tryRecvHS13 giveUp rtt chk = case ctxBackendRecvWith ctx of+        Nothing -> return ()+        Just _ -> do+            late <- registerDelay rtt+            let g = (readTVar late >>= check) `orElse` giveUp+            void $+                tryWithReadLock ctx $+                    withRxGiveUp ctx (GiveUp g g) $+                        recvHS13 ctx chk `catchException` \e ->+                            -- Only an IOException means that the connection is gone+                            -- (see 'backendRecv'); otherwise close_notify is sent.+                            when (isJust (E.fromException @E.IOException e)) $+                                setEOF ctx -bye_ :: MonadIO m => Context -> m ()-bye_ ctx = liftIO $ do+bye_ :: Context -> STM () -> IO ()+bye_ ctx giveUp = do     -- Although setEOF is always protected by the read lock, here we don't try     -- to wrap ctxEOF with it, so that function bye can still be called     -- concurrently to a blocked recvData.     eof <- ctxEOF ctx     broken <- ctxTxBroken ctx     tls13 <- tls13orLater ctx-    unless (eof || broken) $-        withWriteLock ctx $-            if tls13-                then sendPacket13 ctx $ Alert13 [(AlertLevel_Warning, CloseNotify)]-                else sendPacket12 ctx $ Alert [(AlertLevel_Warning, CloseNotify)]+    -- No response to a post-handshake authentication is waited for.+    (`E.finally` wakePHA ctx) $+        unless (eof || broken) $+            sending ctx giveUp $+                if tls13+                    then sendPacket13 ctx $ Alert13 [(AlertLevel_Warning, CloseNotify)]+                    else sendPacket12 ctx $ Alert [(AlertLevel_Warning, CloseNotify)] --- | If the ALPN extensions have been used, this will--- return get the protocol agreed upon.+-- | A send of 'bye', with the write lock: given up on, as is the wait for+-- the lock, after a second or after 'rtt' if longer, or with the 'STM'+-- action.  With a backend which cannot give up on a send, it may block.+-- The peer may have closed the connection without close_notify: EPIPE or+-- ECONNRESET is then just the end of it.+sending :: Context -> STM () -> IO () -> IO ()+sending ctx giveUp send = E.handleJust ignorable return $ do+    rtt <- getRTT ctx+    late <- registerDelay $ max 1000000 rtt+    let g = (readTVar late >>= check) `orElse` giveUp+    void $ withWriteLockGivingUp ctx g $ withTxGiveUp ctx g send+  where+    ignorable :: E.SomeException -> Maybe ()+    ignorable e+        | Just ioe <- E.fromException e, ioe_type ioe == ResourceVanished = Just ()+        | Just e' <- E.fromException e, e' == gaveUpSending = Just ()+        | otherwise = Nothing++-- | If the ALPN extension has been used, this will+-- return the protocol agreed upon. getNegotiatedProtocol :: MonadIO m => Context -> m (Maybe ByteString) getNegotiatedProtocol ctx = liftIO $ usingState_ ctx S.getNegotiatedProtocol @@ -236,34 +358,65 @@                 sendAction ctx                 writeIORef (ctxPendingSendAction ctx) Nothing --- | sendData sends a bunch of data.--- It will automatically chunk data to acceptable packet size+-- | Sending a bunch of data.+-- It will automatically chunk data to acceptable record sizes. sendData :: MonadIO m => Context -> L.ByteString -> m () sendData _ "" = return () sendData ctx dataToSend = liftIO $ do     tls13 <- tls13orLater ctx-    let sendP bs-            | tls13 = do-                updateKeyBeforeLimit ctx-                sendPacket13 ctx $ AppData13 bs-                -- a KeyUpdate requested from now on is answered again-                modifyTLS13State ctx $ \st -> st{tls13stKeyUpdateResponded = False}-                role <- usingState_ ctx getRole-                sentCF <- tls13stSentCF <$> getTLS13State ctx-                rtt0 <- tls13st0RTT <$> getTLS13State ctx-                when (role == ClientRole && rtt0 && not sentCF) $-                    modifyTLS13State ctx $-                        \st -> st{tls13stPendingSentData = tls13stPendingSentData st . (bs :)}-            | otherwise = sendPacket12 ctx $ AppData bs     when tls13 $ withWriteLock ctx $ sendCFifNecessary ctx-    withWriteLock ctx $ do-        checkValid ctx-        -- All chunks are protected with the same write lock because we don't-        -- want to interleave writes from other threads in the middle of our-        -- possibly large write.-        mlen <- getPeerRecordLimit ctx -- plaintext, don't adjust for TLS 1.3-        mapM_ (mapChunks_ mlen sendP) (L.toChunks dataToSend)+    withWriteLock ctx $ sendDataLocked ctx tls13 dataToSend +-- | 'sendData' which gives up once the 'STM' action succeeds, also while+-- waiting for the write lock.  Given up on before anything is sent, the+-- context can still be used.  Given up on after that, part of the data+-- may have been sent, and how much is not known, so later sends throw.+-- With a backend which cannot give up on a send, only the wait for the+-- lock is given up on.+--+-- @since 2.6.4+sendDataWith :: MonadIO m => Context -> L.ByteString -> STM a -> m (Either a ())+sendDataWith _ "" _ = return $ Right ()+sendDataWith ctx dataToSend giveUp = liftIO $ do+    early <- atomically $ (Just <$> giveUp) `orElse` return Nothing+    case early of+        Just a -> return $ Left a+        Nothing -> do+            tls13 <- tls13orLater ctx+            (giveUp', given) <- recording giveUp+            withWriteLockGivingUp ctx giveUp (withTxGiveUp ctx giveUp' (send tls13))+                `E.catch` \e ->+                    if e == gaveUpSending+                        then given >>= maybe (E.throwIO e) (return . Left)+                        else E.throwIO e+  where+    send tls13 = do+        when tls13 $ sendCFifNecessary ctx+        sendDataLocked ctx tls13 dataToSend++sendDataLocked :: Context -> Bool -> L.ByteString -> IO ()+sendDataLocked ctx tls13 dataToSend = do+    checkValid ctx+    -- All chunks are protected with the same write lock because we don't+    -- want to interleave writes from other threads in the middle of our+    -- possibly large write.+    mlen <- getPeerRecordLimit ctx -- plaintext, don't adjust for TLS 1.3+    mapM_ (mapChunks_ mlen sendP) (L.toChunks dataToSend)+  where+    sendP bs+        | tls13 = do+            updateKeyBeforeLimit ctx+            sendPacket13 ctx $ AppData13 bs+            -- a KeyUpdate requested from now on is answered again+            modifyTLS13State ctx $ \st -> st{tls13stKeyUpdateResponded = False}+            role <- usingState_ ctx getRole+            sentCF <- tls13stSentCF <$> getTLS13State ctx+            rtt0 <- tls13st0RTT <$> getTLS13State ctx+            when (role == ClientRole && rtt0 && not sentCF) $+                modifyTLS13State ctx $+                    \st -> st{tls13stPendingSentData = tls13stPendingSentData st . (bs :)}+        | otherwise = sendPacket12 ctx $ AppData bs+ -- RFC 9846 Section 5.5: the keys are updated before the records sent -- under them reach the limit.  Early data cannot do so and stops there. updateKeyBeforeLimit :: Context -> IO ()@@ -290,8 +443,12 @@             | otherwise = 2 ^ (24 :: Int)  -- | Get data out of Data packet, and automatically renegotiate if a Handshake--- ClientHello is received.  An empty result means EOF.  Use--- 'closeNotifyReceived' to tell an orderly closure from a truncation.+-- ClientHello is received.  An empty result means EOF, after which it+-- throws 'PostHandshake' 'Error_EOF'.  Use 'closeNotifyReceived' to tell+-- an orderly closure from a truncation.+--+-- An exception from the backend's receive passes through.  See+-- 'Network.TLS.backendRecv' for when it may be called again. recvData :: MonadIO m => Context -> m ByteString recvData ctx = liftIO $ do     tls13 <- tls13orLater ctx@@ -306,6 +463,24 @@         -- will impact the validity of the context.         if tls13 then recvData13 ctx else recvData12 ctx +-- | 'recvData' which gives up once the 'STM' action succeeds, also while+-- waiting for the read lock.  It gives up only between records, and the+-- context can still be used then.  A record which has begun is read to+-- its end unless the 'STM' action succeeds meanwhile: then it throws, and+-- so do later receives.  With a backend which cannot give up on a+-- receive, only the wait for the lock is given up on.+--+-- @since 2.6.4+recvDataWith :: MonadIO m => Context -> STM a -> m (Either a ByteString)+recvDataWith ctx giveUp = liftIO $ do+    tls13 <- tls13orLater ctx+    (giveUp', given) <- recording giveUp+    fmap join $ withReadLockGivingUp ctx giveUp $ do+        checkValid ctx+        withRxGiveUp ctx (GiveUp giveUp' giveUp') $+            (Right <$> if tls13 then recvData13 ctx else recvData12 ctx)+                `E.catch` \GaveUp -> given >>= maybe (E.throwIO GaveUp) (return . Left)+ recvData12 :: Context -> IO ByteString recvData12 ctx = do     pending <- atomicModifyIORef' (ctxPendingAppData ctx) $ \xs -> ([], reverse xs)@@ -314,9 +489,9 @@         else return $ B.concat pending   where     process (Handshake [ch@ClientHello{}] [b]) =-        handshakeWith ctx (ch, b) >> recvData12 ctx+        renegotiate ctx (ch, b) >> recvData12 ctx     process (Handshake [hr@HelloRequest] [b]) =-        handshakeWith ctx (hr, b) >> recvData12 ctx+        renegotiate ctx (hr, b) >> recvData12 ctx     -- UserCanceled should be followed by a close_notify.     -- fixme: is it safe to call recvData12?     process (Alert [(AlertLevel_Warning, UserCanceled)]) = return B.empty@@ -385,7 +560,7 @@     process (AppData13 "") = checkPHAResponse >> recvData13 ctx     process (AppData13 x) = do         checkPHAResponse-        let chunkLen = C8.length x+        let chunkLen = fromIntegral $ C8.length x         established <- ctxEstablished ctx         case established of             EarlyDataAllowed maxSize@@ -424,7 +599,7 @@             (_, usedCipher, _, _) <- getTxRecordState ctx             -- mMaxSize is always Just, but anyway             let extract (EarlyDataIndication mMaxSize) =-                    maybe 0 (fromIntegral . safeNonNegative32) mMaxSize+                    fromMaybe 0 mMaxSize             let choice = makeCipherChoice TLS13 usedCipher                 psk = derivePSK choice resumptionSecret nonce                 maxSize =@@ -538,7 +713,7 @@                         MsgTNewSessionTicket                         exts                         0-                        (\(EarlyDataIndication mms) -> fromIntegral $ safeNonNegative32 $ fromJust mms)+                        (\(EarlyDataIndication mms) -> fromJust mms)                 life7d = min life 604800 -- 7 days max             tinfo <- createTLS13TicketInfo life7d (Right add) Nothing             sdata <- getSessionData13 ctx usedCipher tinfo maxSize psk@@ -607,7 +782,7 @@ -- the other side could have close the connection already, so wrap -- this in a try and ignore all exceptions tryBye :: Context -> IO ()-tryBye ctx = catchException (bye_ ctx) (\_ -> return ()) `E.finally` setEOF ctx+tryBye ctx = catchException (bye_ ctx retry) (\_ -> return ()) `E.finally` setEOF ctx  onError     :: Monad m@@ -658,6 +833,6 @@  {-# DEPRECATED recvData' "use recvData that returns strict bytestring" #-} --- | same as recvData but returns a lazy bytestring.+-- | Same as 'recvData' but returns a lazy bytestring. recvData' :: MonadIO m => Context -> m L.ByteString recvData' ctx = L.fromChunks . (: []) <$> recvData ctx
Network/TLS/Error.hs view
@@ -13,7 +13,9 @@ -- -- 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'.+-- this library now throw 'TLSException' for TLS errors.  Exceptions+-- of the backend, such as an 'E.IOException' for a reset connection,+-- pass through 'Network.TLS.recvData' and 'Network.TLS.sendData' as they are. data TLSError     = -- | mainly for instance of Error       Error_Misc String
Network/TLS/Extra/FFDHE.hs view
@@ -1,5 +1,5 @@ -- |--- Module      : Network.TLS.Extra+-- Module      : Network.TLS.Extra.FFDHE -- License     : BSD-style -- Maintainer  : Kazu Yamamoto <kazu@iij.ad.jp> -- Stability   : experimental
Network/TLS/Handshake.hs view
@@ -1,6 +1,7 @@ module Network.TLS.Handshake (     handshake_,-    handshakeWith,+    handshakeLocked,+    renegotiate,     handshakeClientWith,     handshakeServerWith,     handshakeClient,@@ -16,17 +17,18 @@ import Control.Monad.State.Strict  handshake_ :: MonadIO m => Context -> m ()-handshake_ ctx =-    liftIO $-        withRWLock ctx $-            handleException ctx (doHandshake_ (ctxRoleParams ctx) ctx)+handshake_ ctx = liftIO $ withRWLock ctx $ handshakeLocked ctx +-- | 'handshake_' with the read and write locks taken already.+handshakeLocked :: Context -> IO ()+handshakeLocked ctx = handleException ctx (doHandshake_ (ctxRoleParams ctx) ctx)+ -- Handshake when requested by the remote end -- This is called automatically by 'recvData', in a context where the read lock -- is already taken.  So contrary to 'handshake' above, here we only need to -- call withWriteLock.-handshakeWith :: MonadIO m => Context -> HandshakeR -> m ()-handshakeWith ctx hsr =+renegotiate :: MonadIO m => Context -> HandshakeR -> m ()+renegotiate ctx hsr =     liftIO $         withWriteLock ctx $             handleException ctx $
Network/TLS/Handshake/Common.hs view
@@ -97,6 +97,9 @@                     sendPacket13 ctx $                         Alert13 [errorToAlert tlserror]             else sendPacket12 ctx $ Alert [errorToAlert tlserror]+    -- The connection is over: 'bye' neither waits nor sends close_notify.+    -- Both callers hold the read lock.+    setEOF ctx     handshakeFailed tlserror  errorToAlert :: TLSError -> (AlertLevel, AlertDescription)
Network/TLS/Handshake/Common13.hs view
@@ -25,7 +25,6 @@     getCurrentTimeFromBase,     getSessionData13,     isHashSignatureValid13,-    safeNonNegative32,     RecvHandshake13M,     runRecvHandshake13,     recvHandshake13,@@ -374,7 +373,7 @@ ----------------------------------------------------------------  getSessionData13-    :: Context -> Cipher -> TLS13TicketInfo -> Int -> ByteString -> IO SessionData+    :: Context -> Cipher -> TLS13TicketInfo -> Word32 -> ByteString -> IO SessionData getSessionData13 ctx usedCipher tinfo maxSize psk = do     ver <- usingState_ ctx getVersion     malpn <- usingState_ ctx getNegotiatedProtocol@@ -396,18 +395,6 @@             , sessionClientCertificate = clientCert             , sessionAppData = Nothing             }---------------------------------------------------------------------- Word32 is used in TLS 1.3 protocol.--- Int is used for API for Haskell TLS because it is natural.--- If Int is 64 bits, users can specify bigger number than Word32.--- If Int is 32 bits, 2^31 or larger may be converted into minus numbers.-safeNonNegative32 :: (Num a, Ord a, FiniteBits a) => a -> a-safeNonNegative32 x-    | x <= 0 = 0-    | finiteBitSize x <= 32 = x-    | otherwise = x `min` fromIntegral (maxBound :: Word32)  ---------------------------------------------------------------- 
Network/TLS/Handshake/Server/ServerHello13.hs view
@@ -156,7 +156,7 @@             False             (\PostHandshakeAuth -> True) -    rtt0max = safeNonNegative32 $ serverEarlyDataSize sparams+    rtt0max = serverEarlyDataSize sparams     rtt0accept = serverEarlyDataSize sparams > 0      decideCredentialInfo allCreds = do
Network/TLS/Handshake/Server/TLS13.hs view
@@ -159,7 +159,7 @@     sendPacket13 ctx $ Handshake13 [nst] []   where     choice = makeCipherChoice TLS13 usedCipher-    rtt0max = safeNonNegative32 $ serverEarlyDataSize sparams+    rtt0max = serverEarlyDataSize sparams     sendNST = PSK_DHE_KE `elem` dhModes      dhModes = case extensionLookup EID_PskKeyExchangeModes exts@@ -183,7 +183,7 @@             | maxSize == 0 = []             | otherwise = [earlyDataExt]           where-            earlyDataExt = toExtensionRaw $ EarlyDataIndication $ Just $ fromIntegral maxSize+            earlyDataExt = toExtensionRaw $ EarlyDataIndication $ Just maxSize     adjustLifetime i         | i < 0 = 0         | i > 604800 = 604800@@ -413,21 +413,27 @@     let (level, desc) = errorToAlert err         reason = errorToAlertMessage err         send = sendPacket13 ctx . Alert13-    catchException (send [(level, desc)]) (\_ -> return ())+    withWriteLock ctx $ catchException (send [(level, desc)]) (\_ -> return ())     setEOF ctx     E.throwIO $ Terminated False reason err  handleEx :: Context -> IO Bool -> IO Bool handleEx ctx f = catchException f $ \exception -> do+    -- The connection is closed already, e.g. by 'terminate' with its alert.+    eof <- ctxEOF ctx+    when eof $ E.throwIO exception     -- If the error was an Uncontextualized TLSException, we replace the-    -- context with HandshakeFailed. If it's anything else, we convert-    -- it to a string and wrap it with Error_Misc and HandshakeFailed.+    -- context with PostHandshake. If it's anything else, we convert+    -- it to a string and wrap it with Error_Misc and PostHandshake.     let tlserror = case E.fromException exception of             Just e | Uncontextualized e' <- e -> e'             _ -> Error_Misc (show exception)-    sendPacket13 ctx $ Alert13 [errorToAlert tlserror]-    void $ E.throwIO $ PostHandshake tlserror-    return False+    withWriteLock ctx $+        catchException+            (sendPacket13 ctx $ Alert13 [errorToAlert tlserror])+            (\_ -> return ())+    setEOF ctx+    E.throwIO $ PostHandshake tlserror  ---------------------------------------------------------------- 
Network/TLS/Parameters.hs view
@@ -60,14 +60,14 @@ -- | All settings should not be used in production data DebugParams = DebugParams     { 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+    -- ^ Disable the true randomness in favor of a deterministic seed,+    -- from which deterministic random values are produced.  This is+    -- useful for tests and debugging.  Do not use in production.     --     -- Default: 'Nothing'     , debugPrintSeed :: Seed -> IO ()-    -- ^ Add a way to print the seed that was randomly generated. reusing the same seed-    -- will reproduce the same randomness with 'debugSeed'+    -- ^ Add a way to print the seed that was randomly generated.  Reusing+    -- the same seed with 'debugSeed' will reproduce the same randomness.     --     -- Default: no printing     , debugVersionForced :: Maybe Version@@ -79,7 +79,14 @@     --     -- Default: no printing     , debugError :: String -> IO ()+    -- ^ Printing errors which terminate the connection.  A rejected+    -- certificate chain is printed in PEM.+    --+    -- Default: no printing     , debugTraceKey :: String -> IO ()+    -- ^ Printing transcript hashes for tracing the key schedule.+    --+    -- Default: no printing     }  {-# NOINLINE keyLogLock #-}@@ -117,13 +124,13 @@  data ClientParams = ClientParams     { clientUseMaxFragmentLength :: Maybe MaxFragmentEnum-    -- ^+    -- ^ Not used any more.  Use 'limitRecordSize' instead.     --     -- Default: 'Nothing'     , clientServerIdentification :: (HostName, ByteString)     -- ^ 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+    -- identification blob.  It is important that the hostname part+    -- is properly filled for security reasons, as it allows to properly     -- associate the remote side with the given certificate during a     -- handshake.     --@@ -135,25 +142,25 @@     -- This value is typically set by 'defaultParamsClient'.     , clientUseServerNameIndication :: Bool     -- ^ 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+    -- during handshake, which allows 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'     , clientWantSessionResume :: Maybe (SessionID, SessionData)-    -- ^ try to establish a connection using this session for TLS+    -- ^ Try to establish a connection using this session for TLS     -- 1.2/TLS 1.3.  This can be used for TLS 1.3 but for backward-    -- compatibility purpose only.  Use 'clientWantSessionResume13'+    -- compatibility purpose only.  Use 'clientWantSessionResumeList'     -- instead for TLS 1.3.     --     -- Default: 'Nothing'     , clientWantSessionResumeList :: [(SessionID, SessionData)]-    -- ^ try to establish a connection using one of this sessions-    -- especially for TLS 1.3.  This take precedence over+    -- ^ Try to establish a connection using one of these sessions+    -- especially for TLS 1.3.  This takes precedence over     -- 'clientWantSessionResume'.  For convenience, this can be     -- specified for TLS 1.2 but only the first entry is used.     ---    -- Default: '[]'+    -- Default: @[]@     , clientWantTicket :: Bool     -- ^ Whether to solicit TLS 1.2 session tickets (or TLS 1.3     -- resumption PSKs) from servers.  With a 'False' setting,@@ -169,14 +176,11 @@     , clientHooks :: ClientHooks     -- ^ See the default value of 'ClientHooks'.     , clientSupported :: Supported-    -- ^ In this element, you'll need to override the default empty-    -- value of of 'supportedCiphers' with a suitable cipherlist.-    ---    -- See the default value of 'Supported'.+    -- ^ See the default value of 'Supported'.     , clientDebug :: DebugParams     -- ^ See the default value of 'DebugParams'.     , clientUseEarlyData :: Bool-    -- ^ Client tries to send early data in TLS 1.3 via 'sendData' if+    -- ^ Client tries to send early data in TLS 1.3 via 'Network.TLS.sendData' if     -- possible.  If not accepted by the server, the early data is     -- automatically re-sent.     --@@ -218,13 +222,12 @@     --     -- Default: 'False'     , serverCACertificates :: [SignedCertificate]-    -- ^ This is a list of certificates from which the disinguished-    -- names are sent in certificate request messages.  For TLS1.0, it-    -- should not be empty.+    -- ^ This is a list of certificates from which the distinguished+    -- names are sent in certificate request messages.     ---    -- Default: '[]'+    -- Default: @[]@     , serverDHEParams :: Maybe DHParams-    -- ^ Server Optional Diffie Hellman parameters.  Setting+    -- ^ Server optional Diffie-Hellman parameters.  Setting     -- parameters is necessary for FFDHE key exchange when clients are     -- not compatible with RFC 7919.     --@@ -241,9 +244,9 @@     -- ^ See the default value of 'Supported'.     , serverDebug :: DebugParams     -- ^ See the default value of 'DebugParams'.-    , serverEarlyDataSize :: Int-    -- ^ Server accepts this size of early data in TLS 1.3.  0 (or-    -- lower) means that the server does not accept early data.+    , serverEarlyDataSize :: Word32+    -- ^ Server accepts this size of early data in TLS 1.3.  0 means+    -- that the server does not accept early data.     --     -- Early data can be replayed.  The server is to accept 0-RTT for the     -- same handshake at most once (RFC 9846 Section 8), which is left to@@ -260,7 +263,7 @@     , serverECHKey :: [(ConfigId, ByteString)]     -- ^ ECH secret keys.     ---    -- Default: '[]'+    -- Default: @[]@     --     -- @since 2.1.9     }@@ -297,12 +300,9 @@     --     -- Default: @[TLS13,TLS12]@     , supportedCiphers :: [Cipher]-    -- ^ Supported cipher methods.  The default is empty, specify a-    -- suitable cipher list.-    -- 'Network.TLS.Extra.Cipher.ciphersuite_default' is often a good-    -- choice.+    -- ^ Supported cipher methods.     ---    -- Default: @[]@+    -- Default: 'Network.TLS.Extra.Cipher.ciphersuite_default'     , supportedMinRSAKeySize :: Int     -- ^ The least size in bits of the RSA key in the peer's leaf     -- certificate.  A shorter one is refused with bad_certificate; 0 lets@@ -353,16 +353,14 @@     --     -- Default: @[nullCompression]@     , supportedHashSignatures :: [SignatureScheme]-    -- ^ All supported hash/signature algorithms pair for client+    -- ^ All supported signature schemes 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'.+    -- X.509 certificates).     --     -- The list also impacts the selection of possible algorithms when     -- generating signatures.@@ -387,7 +385,7 @@     --   Default: 'False'     , supportedExtendedMainSecret :: EMSMode     -- ^ The mode regarding extended main secret.  Enabling this-    -- extension provides better security for TLS versions 1.2.  TLS+    -- extension provides better security for TLS 1.2.  TLS     -- 1.3 provides the security properties natively and does not need     -- the extension.     --@@ -406,19 +404,16 @@     --     --   Default: 'True'     , 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.+    -- ^ A workaround for CBC in TLS 1.0.  Not used any more since TLS+    -- 1.0 is not supported.     --     --   Default: 'True'     , supportedHPKE :: [(KEM_ID, KDF_ID, AEAD_ID)]-    -- ^ Client only.+    -- ^ Client only.  HPKE cipher suites for ECH in preferred order.     --+    -- Default: X25519 and P-256 with AES-128-GCM or ChaCha20-Poly1305,+    -- and P-521 with AES-256-GCM+    --     -- @since 2.1.9     , supportedGroups :: [Group]     -- ^ A list of supported elliptic curves and finite-field groups@@ -552,10 +547,14 @@     , sharedECHConfigList :: ECHConfigList     -- ^ ECH configuration.     --+    -- Default: @[]@+    --     -- @since 2.1.9     , sharedLimit :: Limit     -- ^ Limitation parameters.     --+    -- See the default value of 'Limit'.+    --     -- @since 2.1.8     } @@ -621,7 +620,7 @@ -- | A set of callbacks run by the clients for various corners of TLS establishment data ClientHooks = ClientHooks     { onCertificateRequest :: OnCertificateRequest-    -- ^ This action is called when the a certificate request is+    -- ^ This action is called when 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@@ -644,7 +643,7 @@     --     -- 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+    -- certificate in the chain.  This key will be used for signing     -- the certificate verify message.     --     -- The public key in the first certificate, and the matching@@ -665,7 +664,7 @@     -- hint, since TLS 1.3 servers will generally list the RSASSA-PSS     -- schemes, whose first octet is @0x08@.     ---    -- Note that is is the responsibility of this action to select a+    -- Note that it 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.@@ -694,7 +693,7 @@     -- Default: 'validateDefault'     , onSuggestALPN :: IO (Maybe [ByteString])     -- ^ This action is called when the client sends ClientHello-    --   to determine ALPN values such as '["h2", "http/1.1"]'.+    --   to determine ALPN values such as @["h2", "http/1.1"]@.     --     -- Default: returns 'Nothing'     , onCustomFFDHEGroup :: DHParams -> DHPublic -> IO GroupUsage@@ -705,19 +704,21 @@     --     --   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.+    --   negotiated is 1.2.     ---    --   The default behavior with (dh_p, dh_g, dh_size) and pub as+    --   The default behavior with (dh_p, dh_g, dh_size) and pub is 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+    --   (3) rejecting unless 1 < pub && pub < dh_p - 1     --   (4) rejecting if dh_size < 1024 (to prevent Logjam attack)     --     --   See RFC 7919 section 3.1 for recommendations.     , onServerFinished :: Information -> IO ()-    -- ^ When a handshake is done, this hook can check `Information`.+    -- ^ When a handshake is done, this hook can check 'Information'.+    --+    -- Default: does nothing     , onSelectKeyShareGroups :: [Group] -> [Group]     -- ^ A function to select groups in "key_share" by TLS 1.3 client.     --@@ -728,19 +729,20 @@     --   The default function specifies a pair of hybrid (classical +     --   post quantum) group and classical group to transit from     --   classical key exchange to hybrid key exchange. With the-    --   default value of 'supportedGroups', X25519MLKEM and X25519+    --   default value of 'supportedGroups', X25519MLKEM768 and X25519     --   are chosen.     --     --   Middleboxes may drop a ClientHello that contains large-    --   X2219MLKEM. In such environment, @take 1@, which selects-    --   X22519 only with the default value, is maybe a good-    --   candidate.+    --   X25519MLKEM768. In such environment, @filter (== X25519)@,+    --   which selects X25519 only, is maybe a good candidate.     ---    --   In the case where X22519 is only contained in "key_share", a-    --   wise-server without nasty middleboxes may ask the client to-    --   send X2219MLKEM via HelloRetryRequest as X2219MLKEM is+    --   In the case where X25519 is only contained in "key_share", a+    --   wise server without nasty middleboxes may ask the client to+    --   send X25519MLKEM768 via HelloRetryRequest as X25519MLKEM768 is     --   specified in "supported_groups".     --+    --   Default: the first hybrid group and the first other group+    --     --   @since 2.2.3     } @@ -776,7 +778,7 @@     { 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.+    -- '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@@ -794,13 +796,12 @@     --     -- Default: returns 'False'     , 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 preferred with TLS < 1.1)+    -- ^ Allow the server to choose the cipher relative to the+    -- negotiated version and the ciphers in common with the client.+    -- They are in the order of 'supportedCiphers', or in the client's+    -- order with 'supportedClientCipherOrder'.     ---    -- The client cipher list cannot be empty.+    -- The list is never empty, and the result must be one of it.     --     -- Default: taking the head of ciphers.     , onServerNameIndication :: Maybe HostName -> IO Credentials@@ -817,14 +818,14 @@     -- Default: returns 'mempty'     , onNewHandshake :: Measurement -> IO Bool     -- ^ At each new handshake, we call this hook to see if we allow-    -- handshake to happens.+    -- the handshake to happen.     --     -- Default: returns 'True'     , 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.  If the server supports no-    --   protocols that the client advertises an empty 'ByteString'+    --   Protocol Negotiation) extension.  If the server supports no+    --   protocols that the client advertises, an empty 'ByteString'     --   should be returned.     --     -- Default: 'Nothing'@@ -841,8 +842,8 @@     -- ^ A function to select one key share by TLS 1.3 server.     --     -- The 1st argument is server's 'supportedGroupsTLS13'.-    -- The 2nd arguments is client's groups in "supported_groups"-    -- The 3rd arguments is client's groups in "key_share".+    -- The 2nd argument is client's groups in "supported_groups".+    -- The 3rd argument is client's groups in "key_share".     --     -- 'True' in the result indicates sending a hello retry request     -- with this group.@@ -910,17 +911,29 @@ -- | Information related to a running context, e.g. current cipher data Information = Information     { infoVersion :: Version+    -- ^ The negotiated version.     , infoCipher :: Cipher+    -- ^ The negotiated cipher.     , infoCompression :: Compression+    -- ^ The negotiated compression.     , infoMainSecret :: Maybe ByteString+    -- ^ The main secret of TLS 1.2.     , infoExtendedMainSecret :: Bool+    -- ^ Whether the extended main secret is used in TLS 1.2.     , infoClientRandom :: Maybe ClientRandom+    -- ^ The random of ClientHello.     , infoServerRandom :: Maybe ServerRandom+    -- ^ The random of ServerHello.     , infoSupportedGroup :: Maybe Group+    -- ^ The group used for the key exchange.     , infoTLS12Resumption :: Bool+    -- ^ Whether the TLS 1.2 session was resumed.     , infoTLS13HandshakeMode :: Maybe HandshakeMode13+    -- ^ The handshake mode of TLS 1.3.     , infoIsEarlyDataAccepted :: Bool+    -- ^ Whether the early data of TLS 1.3 was accepted.     , infoIsECHAccepted :: Bool+    -- ^ Whether Encrypted Client Hello was accepted.     , infoServerSignatureScheme :: Maybe SignatureScheme     -- ^ The scheme of the server's signature: ServerKeyExchange in TLS 1.2,     -- CertificateVerify in TLS 1.3.  'Nothing' on resumption.@@ -945,7 +958,7 @@     -- extension. When negotiated, both my limit and peer's limit are     -- enabled for protected communication.     ---    -- Default: Nothing+    -- Default: 'Nothing'     , limitHandshakeFragment :: Int     -- ^ The number of records that may carry a handshake message before     -- the one that completes it.  A peer may split a message into records@@ -956,7 +969,7 @@     -- ^ Maximum number of consecutive TLS 1.3 KeyUpdate messages accepted     -- without intervening non-empty application data.  This bounds the CPU     -- work and response amplification a peer can trigger while application-    -- code is blocked inside 'recvData'.  'Nothing' and non-positive values+    -- code is blocked inside 'Network.TLS.recvData'.  'Nothing' and non-positive values     -- disable the limit; they do not disable KeyUpdate processing.     --     -- Default: @Just 32@
Network/TLS/PostHandshake.hs view
@@ -23,7 +23,7 @@ -- exception is thrown if the authentication fails. Server only. -- -- This reads the client's response by itself, so it must not be called--- while another thread is in 'recvData', and application data received+-- while another thread is in 'Network.TLS.recvData', and application data received -- before the response closes the connection, against RFC 9846 Section 4.7.2. {-# DEPRECATED     requestCertificate@@ -34,12 +34,18 @@     checkValid ctx >> doRequestCertificate_ (ctxRoleParams ctx) ctx  -- | Post-handshake certificate request with TLS 1.3, without waiting for--- the response.  The response is processed by 'recvData', so another+-- the response.  The response is processed by 'Network.TLS.recvData', so another -- thread or the caller itself must keep calling it.  The returned action -- gives the result; with 'True' it blocks until the result is known, with -- 'False' it returns 'PHAPending' meanwhile.  Only one request may be--- pending.  'getClientCertificateChain' gives the authenticated chain.+-- pending.  'Network.TLS.getClientCertificateChain' gives the authenticated chain. -- Server only.+--+-- The blocking wait ends with the response, with the end of the+-- connection, e.g. a received alert, an 'Control.Exception.IOException'+-- from the backend or 'Network.TLS.bye', or with an exception inside a+-- record.  It waits as long as the client does not respond, and while+-- 'Network.TLS.recvData' is not called, so put a timeout on it if needed. requestCertificateAsync :: Context -> IO (Bool -> IO PHAResult) requestCertificateAsync ctx =     checkValid ctx >> doRequestCertificateAsync_ (ctxRoleParams ctx) ctx
Network/TLS/QUIC.hs view
@@ -152,7 +152,7 @@     , quicDone :: Context -> IO ()     -- ^ Called when 'handshake' is done. 'tlsQUICServer' is     -- finished after calling this hook. 'tlsQUICClient' calls-    -- 'recvData' after calling this hook to wait for new session+    -- 'Network.TLS.recvData' after calling this hook to wait for new session     -- tickets.     } @@ -261,5 +261,5 @@         }  -- | Max early data size for QUIC.-quicMaxEarlyDataSize :: Int+quicMaxEarlyDataSize :: Word32 quicMaxEarlyDataSize = 0xffffffff
Network/TLS/Record/Recv.hs view
@@ -1,14 +1,21 @@+{-# LANGUAGE TypeApplications #-}+ -- | TLS record layer in Rx direction module Network.TLS.Record.Recv (     recvRecord12,     recvRecord13, ) where +import Control.Concurrent.STM+import qualified Control.Exception as E import qualified Data.ByteString as B+import Data.IORef +import Network.TLS.Backend import Network.TLS.Context.Internal import Network.TLS.Hooks import Network.TLS.Imports+import Network.TLS.Measurement import Network.TLS.Packet import Network.TLS.Record import Network.TLS.Struct@@ -50,7 +57,7 @@     -- ^ TLS context     -> IO (Either TLSError (Record Plaintext)) recvRecord12 ctx =-    readExactBytes ctx 5+    readExactBytes ctx False 5         >>= either (return . Left) (recvLengthE . (decodeHeader >=> checkType))   where     recvLengthE = either (return . Left) recvLength@@ -66,12 +73,12 @@         if exceedsTLSCiphertext 2048 readlen             then return $ Left maximumSizeExceeded             else-                readExactBytes ctx (fromIntegral readlen)+                readExactBytes ctx True (fromIntegral readlen)                     >>= either (return . Left) (getRecord ctx header)  recvRecord13 :: Context -> IO (Either TLSError (Record Plaintext)) recvRecord13 ctx =-    readExactBytes ctx 5+    readExactBytes ctx False 5         >>= either (return . Left) (recvLengthE . (decodeHeader >=> checkType))   where     recvLengthE = either (return . Left) recvLength@@ -88,7 +95,7 @@         if exceedsTLSCiphertext 256 readlen             then return $ Left maximumSizeExceeded             else-                readExactBytes ctx (fromIntegral readlen)+                readExactBytes ctx True (fromIntegral readlen)                     >>= either (return . Left) (getRecord13 header)     -- RFC 9846 Section 4.2.10: a server that rejected early data skips the     -- records it cannot deprotect, until the first one it can.@@ -129,9 +136,11 @@  ---------------------------------------------------------------- -readExactBytes :: Context -> Int -> IO (Either TLSError ByteString)-readExactBytes ctx sz = do-    hdrbs <- contextRecv ctx sz+readExactBytes :: Context -> Bool -> Int -> IO (Either TLSError ByteString)+readExactBytes ctx inRecord sz = do+    ctxRxBrokenBy ctx >>= mapM_ (throwBroken "a previous receive failed")+    mgiveUp <- readIORef $ ctxRxGiveUp ctx+    hdrbs <- recv mgiveUp `E.catch` broken     if B.length hdrbs == sz         then return $ Right hdrbs         else do@@ -146,3 +155,41 @@                                 ++ " bytes, got: "                                 ++ show (B.length hdrbs)                             )+  where+    recv mgiveUp = case (mgiveUp, ctxBackendRecvWith ctx) of+        (Just giveUp, Just (RecvWith recvWith)) -> do+            updateMeasure ctx $ addBytesReceived sz+            let inside n = do+                    r <- recvWith n $ giveUpInside giveUp+                    gaveUp <- fired $ giveUpInside giveUp+                    case r of+                        Right bs | B.length bs == n || not gaveUp -> return bs+                        _ -> do+                            let e = PostHandshake $ Error_Misc "gave up inside a record"+                            setRxBroken ctx $ E.toException e+                            E.throwIO e+            if inRecord+                then inside sz+                else do+                    r <- recvWith sz $ giveUpBetween giveUp+                    case r of+                        Left () -> E.throwIO GaveUp+                        Right bs+                            | B.length bs == sz || B.null bs -> return bs+                            | otherwise -> do+                                -- Begun: the rest is given up on only inside.+                                gaveUp <- fired $ giveUpBetween giveUp+                                if gaveUp+                                    then (bs <>) <$> inside (sz - B.length bs)+                                    else return bs+        _ -> contextRecv ctx sz+    fired stm = atomically $ (True <$ stm) `orElse` return False+    -- A broken transport ends the connection.  Another exception inside a+    -- record leaves the stream there, so later receives fail at once.+    -- Both wake up those waiting for a post-handshake authentication.+    broken :: E.SomeException -> IO a+    broken e+        | isJust (E.fromException @E.IOException e) = setEOF ctx >> E.throwIO e+        | isJust (E.fromException @GaveUp e) = E.throwIO e+        | inRecord = setRxBroken ctx e >> E.throwIO e+        | otherwise = E.throwIO e
Network/TLS/Record/Send.hs view
@@ -61,11 +61,6 @@     -- The record state has advanced already, so a failed send leaves the     -- peer unable to decrypt any later record.  Later sends throw the same     -- exception, except an asynchronous one, which is not thrown again.-    ctxTxBrokenBy ctx >>= mapM_ (\e -> E.throwIO $ fromMaybe e $ asTLS e)+    ctxTxBrokenBy ctx >>= mapM_ (throwBroken "a previous send failed")     withLog ctx $ \logging -> loggingIOSent logging dataToSend     contextSend ctx dataToSend `E.catch` \e -> setTxBroken ctx e >> E.throwIO e-  where-    asTLS e = case E.fromException e of-        Just (E.SomeAsyncException _) ->-            Just $ E.toException $ PostHandshake $ Error_Misc "a previous send failed"-        Nothing -> Nothing
Network/TLS/Session.hs view
@@ -20,7 +20,7 @@     , sessionEstablish :: SessionIDorTicket -> SessionData -> IO (Maybe Ticket)     -- ^ Used on TLS 1.2\/1.3 servers to store 'SessionData' with 'SessionID' or to encrypt 'SessionData' to get 'Ticket' ignoring 'SessionID'. Used on TLS 1.2\/1.3 clients to store 'SessionData' with 'SessionIDorTicket' and then return 'Nothing'. For clients, only this field should be set with 'noSessionManager'.     , sessionInvalidate :: SessionIDorTicket -> IO ()-    -- ^ Used TLS 1.2 servers to delete 'SessionData' with 'SessionID' on errors.+    -- ^ Used on TLS 1.2 servers to delete 'SessionData' with 'SessionID' on errors.     , sessionUseTicket :: Bool     -- ^ Used on TLS 1.2 servers to decide to use 'SessionID' or 'Ticket'. Note that 'SessionID' and 'Ticket' are integrated as identity in TLS 1.3.     }
Network/TLS/Types/Session.hs view
@@ -44,7 +44,7 @@     , sessionGroup :: Maybe Group     , sessionTicketInfo :: Maybe TLS13TicketInfo     , sessionALPN :: Maybe ByteString-    , sessionMaxEarlyDataSize :: Int+    , sessionMaxEarlyDataSize :: Word32     , sessionFlags :: [SessionFlag]     , sessionClientCertificate :: Maybe ByteString     -- ^ On a server, the DER of the leaf certificate the client was@@ -52,7 +52,7 @@     , sessionAppData :: Maybe ByteString     -- ^ Data of the application's own, kept with the session and given     -- back on resumption; never set by this library.  A server can put-    -- what 0-RTT depends on here and check it in 'onAccept0RTT'.+    -- what 0-RTT depends on here and check it in 'Network.TLS.onAccept0RTT'.     --     -- @since 2.5.1     }
Network/TLS/X509.hs view
@@ -40,7 +40,7 @@     | CertificateRejectOther String     deriving (Show, Eq) --- | Certificate Usage callback possible returns values.+-- | Certificate usage callback possible return values. data CertificateUsage     = -- | usage of certificate accepted       CertificateUsageAccept@@ -62,9 +62,9 @@ pubkeyType = show . pubkeyToAlg  -- | A utility function for client authentication which can be used--- `onClientCertificate`.+-- as 'Network.TLS.onClientCertificate' with a store and a cache given. ----- Since: 2.1.7+-- @since 2.1.7 validateClientCertificate     :: CertificateStore     -> ValidationCache
test/ByeSpec.hs view
@@ -1,15 +1,21 @@ {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE TypeApplications #-}  module ByeSpec where  import Control.Concurrent import Control.Concurrent.Async+import Control.Concurrent.STM import qualified Control.Exception as E-import Control.Monad (forever, when)+import Control.Monad (when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B import Data.Either (isLeft) import Data.IORef import GHC.Clock (getMonotonicTime)+import qualified Network.Socket as N+import qualified Network.Socket.ByteString as NB import Network.TLS import System.Timeout import Test.Hspec@@ -20,27 +26,210 @@  spec :: Spec spec = describe "bye" $ do+    it "waits for the last handshake messages with the backend's recvWith" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        used <- newIORef False+        let noop = return ()+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)+        cCtx <-+            contextNew (GivingUp cBackend $ recvWithVia (readPipeC pipe) used) cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        -- close_notify still goes out after the receive in 'bye'.+        timeout 5000000 (concurrently (bye cCtx) (recvData sCtx))+            `shouldReturn` Just ((), mempty)+        readIORef used `shouldReturn` True++    it "sends close_notify when the backend gives up by itself" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        let noop = return ()+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)+            -- e.g. on shutdown, without waiting for 'bye' to give up+            shutdown = RecvWith $ \_ _ -> E.throwIO $ E.ErrorCall "shutdown"+        cCtx <- contextNew (GivingUp cBackend shutdown) cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        timeout 5000000 (concurrently (bye cCtx) (recvData sCtx))+            `shouldReturn` Just ((), mempty)+        closeNotifyReceived sCtx `shouldReturn` True++    it "gives up on a receive over a socket" $ do+#if MIN_VERSION_network(3,2,12)+        (cs, ss) <- N.socketPair N.AF_UNIX N.Stream N.defaultProtocol+        case getBackendRecvWith cs of+            Nothing -> expectationFailure "a socket should be able to give up"+            Just (RecvWith recvWith) -> do+                late <- registerDelay 50000+                recvWith 4 (readTVar late >>= check) `shouldReturn` Left ()+                NB.sendAll ss "abcd"+                recvWith 4 (retry :: STM ()) `shouldReturn` Right "abcd"+                -- The bytes received before giving up are not lost.+                NB.sendAll ss "ab"+                late' <- registerDelay 50000+                recvWith 4 (readTVar late' >>= check) `shouldReturn` Right "ab"+        N.close cs+        N.close ss+#else+        pendingWith "needs network 3.2.12 or later"+#endif++    it "gives up on a send over a socket" $ do+#if defined(mingw32_HOST_OS)+        -- The send does not wait for a reader there.+        pendingWith "Windows does not fill the send buffer"+#elif MIN_VERSION_network(3,2,12)+        (cs, ss) <- N.socketPair N.AF_UNIX N.Stream N.defaultProtocol+        case getBackendSendWith cs of+            Nothing -> expectationFailure "a socket should be able to give up"+            Just (SendWith sendWith) -> do+                -- Nobody reads, so the send buffer fills up.+                late <- registerDelay 100000+                sendWith (B.replicate 16000000 0) (readTVar late >>= check)+                    `shouldReturn` Left ()+        N.close cs+        N.close ss+#else+        pendingWith "needs network 3.2.12 or later"+#endif++    it "gives up on close_notify when the peer does not read" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        stuck <- newIORef False+        let noop = return ()+            -- a peer which no longer reads+            sendS bs = do+                s <- readIORef stuck+                if s then threadDelay maxBound else writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew (SendGivingUp sBackend $ sendWithVia stuck sendS) sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef stuck True+        timeout 5000000 (bye sCtx) `shouldReturn` Just ()+        -- The record may be partly sent, so nothing more is.+        r <- E.try @TLSException $ sendData sCtx "abc"+        r `shouldSatisfy` isLeft++    it "gives up on the answer to close_notify when the peer does not read" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        stuck <- newIORef False+        let noop = return ()+            sendS bs = do+                s <- readIORef stuck+                if s then threadDelay maxBound else writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew (SendGivingUp sBackend $ sendWithVia stuck sendS) sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef stuck True+        bye cCtx+        timeout 5000000 (recvData sCtx) `shouldReturn` Just mempty++    it "does not wait with a backend which cannot give up" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        armed <- newIORef False+        readAfter <- newIORef False+        let noop = return ()+            recvC n = do+                a <- readIORef armed+                when a $ writeIORef readAfter True+                readPipeC pipe n+            cBackend = Backend noop noop (writePipeC pipe) recvC+            sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef armed True+        timeout 5000000 (bye cCtx) `shouldReturn` Just ()+        readIORef readAfter `shouldReturn` False++    it "neither waits nor sends after a failed handshake" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        used <- newIORef False+        let noop = return ()+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)+            reject _ = return $ CertificateUsageReject $ CertificateRejectOther "test"+            sParams' =+                sParams+                    { serverWantClientCert = True+                    , serverHooks = (serverHooks sParams){onClientCertificate = reject}+                    }+        cCtx <- contextNew cBackend cParams+        sCtx <-+            contextNew (GivingUp sBackend $ recvWithVia (readPipeS pipe) used) sParams'+        (_, r) <-+            concurrently+                (E.try @E.SomeException $ handshake cCtx)+                (E.try @TLSException $ handshake sCtx)+        r `shouldSatisfy` isLeft+        timeout 5000000 (bye sCtx) `shouldReturn` Just ()+        readIORef used `shouldReturn` False++    it "does not throw when the peer has gone" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        (cs, ss) <- N.socketPair N.AF_UNIX N.Stream N.defaultProtocol+        cCtx <- contextNew cs cParams+        sCtx <- contextNew ss sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        N.close ss+        timeout 5000000 (bye cCtx) `shouldReturn` Just ()+        N.close cs++    it "sends close_notify when the last handshake message is cut short" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        let noop = return ()+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)+            -- Half of a record body arrives before giving up.+            cut = RecvWith $ \n giveUp -> do+                bs <- readPipeC pipe n+                if n == 5+                    then return $ Right bs+                    else atomically giveUp >> return (Right $ B.take (n `div` 2) bs)+        cCtx <- contextNew (GivingUp cBackend cut) cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        timeout 5000000 (concurrently (bye cCtx) (recvData sCtx))+            `shouldReturn` Just ((), mempty)+        closeNotifyReceived sCtx `shouldReturn` True+     it "waits for the last handshake messages a few seconds at most" $ do         (cParams, sParams) <- generate arbitraryPairParams13         pipe <- newPipe         _ <- runPipe pipe         sent <- newIORef False-        armed <- newIORef False         let noop = return ()             -- Every answer is late, which makes the RTT two seconds.             sendC bs = writeIORef sent True >> writePipeC pipe bs             recvC n = do-                a <- readIORef armed-                when a $ forever $ threadDelay 1000000                 s <- atomicModifyIORef' sent (\x -> (False, x))                 when s $ threadDelay 2000000                 readPipeC pipe n             cBackend = Backend noop noop sendC recvC             sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)-        cCtx <- contextNew cBackend cParams+            never = RecvWith $ \_ giveUp -> Left <$> atomically giveUp+        cCtx <- contextNew (GivingUp cBackend never) cParams         sCtx <- contextNew sBackend sParams         concurrently_ (handshake cCtx) (handshake sCtx)-        writeIORef armed True         t0 <- getMonotonicTime         bye cCtx         t1 <- getMonotonicTime@@ -67,8 +256,7 @@         E.try @E.AsyncException (sendData sCtx "abc") `shouldReturn` Left E.ThreadKilled         writeIORef failing False         -- An asynchronous exception is not thrown again.-        E.try @TLSException (sendData sCtx "abc")-            `shouldReturn` Left (PostHandshake (Error_Misc "a previous send failed"))+        E.try @TLSException (sendData sCtx "abc") `shouldReturn` Left (PostHandshake (Error_Misc "a previous send failed"))         n <- readIORef sent         timeout 5000000 (bye sCtx) `shouldReturn` Just ()         readIORef sent `shouldReturn` n@@ -92,30 +280,96 @@         E.try (sendData sCtx "abc") `shouldReturn` Left (E.ErrorCall "broken")         E.try (sendData sCtx "abc") `shouldReturn` Left (E.ErrorCall "broken") +    it "throws the exception of a receive interrupted inside a record again" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            -- only the body of a record, never its 5-byte header+            recvS n = do+                f <- readIORef failing+                when (f && n /= 5) $ E.throwIO $ E.ErrorCall "interrupted"+                readPipeS pipe n+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) recvS+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        sendData cCtx "abc"+        E.try (recvData sCtx) `shouldReturn` Left (E.ErrorCall "interrupted")+        writeIORef failing False+        sendData cCtx "def"+        timeout 1000000 (E.try (recvData sCtx))+            `shouldReturn` Just (Left (E.ErrorCall "interrupted"))+        -- close_notify can still be sent.+        bye sCtx+        timeout 1000000 (recvData cCtx) `shouldReturn` Just mempty++    it "does not throw an asynchronous exception of an interrupted receive again" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            recvS n = do+                f <- readIORef failing+                when (f && n /= 5) $ E.throwIO E.ThreadKilled+                readPipeS pipe n+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) recvS+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        sendData cCtx "abc"+        E.try @E.AsyncException (recvData sCtx) `shouldReturn` Left E.ThreadKilled+        timeout 1000000 (E.try @TLSException (recvData sCtx))+            `shouldReturn` Just (Left (PostHandshake (Error_Misc "a previous receive failed")))++    it "keeps receiving after an exception before a record" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            -- e.g. a timeout while waiting for the next record+            recvS n = do+                f <- atomicModifyIORef' failing (\x -> (False, x))+                when f $ E.throwIO $ E.ErrorCall "timeout"+                readPipeS pipe n+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) recvS+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        E.try (recvData sCtx) `shouldReturn` Left (E.ErrorCall "timeout")+        sendData cCtx "abc"+        timeout 1000000 (recvData sCtx) `shouldReturn` Just "abc"+     it "does not wait after a failed send" $ do         (cParams, sParams) <- generate arbitraryPairParams13         pipe <- newPipe         _ <- runPipe pipe         failing <- newIORef False-        readAfter <- newIORef False+        used <- newIORef False         let noop = return ()             sendC bs = do                 f <- readIORef failing                 when f $ E.throwIO E.ThreadKilled                 writePipeC pipe bs-            recvC n = do-                f <- readIORef failing-                when f $ writeIORef readAfter True-                readPipeC pipe n-            cBackend = Backend noop noop sendC recvC+            cBackend = Backend noop noop sendC (readPipeC pipe)             sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)-        cCtx <- contextNew cBackend cParams+        cCtx <-+            contextNew (GivingUp cBackend $ recvWithVia (readPipeC pipe) used) cParams         sCtx <- contextNew sBackend sParams         concurrently_ (handshake cCtx) (handshake sCtx)         writeIORef failing True         E.try @E.AsyncException (sendData cCtx "abc") `shouldReturn` Left E.ThreadKilled         timeout 5000000 (bye cCtx) `shouldReturn` Just ()-        readIORef readAfter `shouldReturn` False+        readIORef used `shouldReturn` False      it "sends nothing after a handshake whose send failed" $ do         (cParams, sParams) <- generate arbitraryPairParams13@@ -152,3 +406,34 @@             E.try @E.AsyncException (recvData sCtx) `shouldReturn` Left E.ThreadKilled             timeout 1000000 (E.try @TLSException (recvData sCtx))                 `shouldReturn` Just (Left (PostHandshake Error_EOF))++-- | A backend which can give up on a receive.+data GivingUp = GivingUp Backend RecvWith++instance HasBackend GivingUp where+    initializeBackend _ = return ()+    getBackend (GivingUp b _) = b+    getBackendRecvWith (GivingUp _ f) = Just f++-- | A receive given up on in STM, over a pipe which cannot be: the bytes+--   read after giving up are lost, which closing the connection allows.+recvWithVia :: (Int -> IO ByteString) -> IORef Bool -> RecvWith+recvWithVia rd used = RecvWith $ \n giveUp -> do+    writeIORef used True+    v <- newEmptyTMVarIO+    _ <- forkIO $ rd n >>= atomically . putTMVar v+    atomically $ (Right <$> takeTMVar v) `orElse` (Left <$> giveUp)++-- | A backend which can give up on a send.+data SendGivingUp = SendGivingUp Backend SendWith++instance HasBackend SendGivingUp where+    initializeBackend _ = return ()+    getBackend (SendGivingUp b _) = b+    getBackendSendWith (SendGivingUp _ f) = Just f++-- | Sending with the given send unless stuck, when only the give-up ends it.+sendWithVia :: IORef Bool -> (ByteString -> IO ()) -> SendWith+sendWithVia stuck snd' = SendWith $ \bs giveUp -> do+    s <- readIORef stuck+    if s then Left <$> atomically giveUp else Right <$> snd' bs
+ test/GiveUpSpec.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module GiveUpSpec where++import Control.Concurrent.Async+import Control.Concurrent.STM+import qualified Control.Exception as E+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Either (isLeft)+import GHC.Clock (getMonotonicTime)+import qualified Network.Socket as N+import qualified Network.Socket.ByteString as NB+import Network.TLS+import System.Timeout+import Test.Hspec+import Test.QuickCheck (generate)++import Arbitrary++spec :: Spec+spec = describe "giving up" $ do+#if MIN_VERSION_network(3,2,12)+    it "handshakeWith gives up on a silent server" $+        withSockets $ \(cs, _ss) -> do+            (cParams, _) <- generate arbitraryPairParams13+            cCtx <- contextNew cs cParams+            timeout 5000000 (handshakeWith cCtx =<< lateBy 50000)+                `shouldReturn` Just (Left ())++    it "handshakeWith and recvDataWith work as usual" $+        withPair $ \(cCtx, _) (sCtx, _) -> do+            sendData cCtx "abc"+            timeout 5000000 (recvDataWith sCtx (retry :: STM ())) `shouldReturn` Just (Right "abc")++    it "recvDataWith gives up between records, leaving the context usable" $+        withPair $ \(cCtx, _) (sCtx, _) -> do+            timeout 5000000 (recvDataWith sCtx =<< lateBy 50000) `shouldReturn` Just (Left ())+            sendData cCtx "abc"+            timeout 5000000 (recvData sCtx) `shouldReturn` Just "abc"++    it "recvDataWith throws when giving up inside a record" $+        withPair $ \(_, cs) (sCtx, _) -> do+            -- the first byte of a record, and no more+            NB.sendAll cs "\x17"+            r <- timeout 5000000 $ E.try @TLSException (recvDataWith sCtx =<< lateBy 50000)+            fmap isLeft r `shouldBe` Just True+            r' <- timeout 5000000 $ E.try @TLSException (recvData sCtx)+            fmap isLeft r' `shouldBe` Just True++    it "recvDataWith gives up waiting for another reader" $+        withPair $ \(cCtx, _) (sCtx, _) ->+            withAsync (recvData sCtx) $ \reader -> do+                waitReading+                timeout 5000000 (recvDataWith sCtx =<< lateBy 50000) `shouldReturn` Just (Left ())+                sendData cCtx "abc"+                timeout 5000000 (wait reader) `shouldReturn` Just "abc"++    it "sendDataWith gives up at once without sending" $+        withPair $ \(cCtx, _) (sCtx, _) -> do+            timeout 5000000 (sendDataWith sCtx "abc" (return ())) `shouldReturn` Just (Left ())+            timeout 5000000 (sendData sCtx "def") `shouldReturn` Just ()+            timeout 5000000 (recvData cCtx) `shouldReturn` Just "def"++#if !defined(mingw32_HOST_OS)+    it "sendDataWith gives up on a peer which does not read" $+        withPair $ \_ (sCtx, _) -> do+            timeout 5000000 (sendDataWith sCtx big =<< lateBy 100000)+                `shouldReturn` Just (Left ())+            r <- timeout 5000000 $ E.try @TLSException $ sendData sCtx "abc"+            fmap isLeft r `shouldBe` Just True++    it "sendDataWith gives up waiting for another writer" $+        withPair $ \_ (sCtx, _) ->+            withAsync (sendData sCtx big) $ \_ -> do+                waitReading+                timeout 5000000 (sendDataWith sCtx "abc" =<< lateBy 50000)+                    `shouldReturn` Just (Left ())++    it "byeWith gives up sooner than bye" $+        withPair $ \_ (sCtx, _) ->+            withAsync (sendData sCtx big) $ \_ -> do+                waitReading+                t0 <- getMonotonicTime+                timeout 5000000 (byeWith sCtx =<< lateBy 50000) `shouldReturn` Just ()+                t1 <- getMonotonicTime+                (t1 - t0) `shouldSatisfy` (< 0.5)+#endif+#else+    it "needs network 3.2.12 or later" $ pendingWith "network < 3.2.12"+#endif+  where+    big = L.fromStrict $ B.replicate 16000000 0+    -- letting the other thread start+    waitReading = timeout 100000 (atomically retry :: IO ()) >> return ()++-- | An 'STM' action which succeeds after the microseconds.+lateBy :: Int -> IO (STM ())+lateBy us = do+    late <- registerDelay us+    return $ readTVar late >>= check++withSockets :: ((N.Socket, N.Socket) -> IO a) -> IO a+withSockets =+    E.bracket+        (N.socketPair N.AF_UNIX N.Stream N.defaultProtocol)+        (\(cs, ss) -> N.close cs >> N.close ss)++-- | TLS 1.3 over a socket pair, the handshake done with 'handshakeWith'.+withPair :: ((Context, N.Socket) -> (Context, N.Socket) -> IO a) -> IO a+withPair body = withSockets $ \(cs, ss) -> do+    (cParams, sParams) <- generate arbitraryPairParams13+    cCtx <- contextNew cs cParams+    sCtx <- contextNew ss sParams+    r <-+        timeout 5000000 $+            concurrently+                (handshakeWith cCtx (retry :: STM ()))+                (handshakeWith sCtx (retry :: STM ()))+    r `shouldBe` Just (Right (), Right ())+    body (cCtx, cs) (sCtx, ss)
test/HandshakeSpec.hs view
@@ -308,6 +308,14 @@             post_handshake_auth_async_wait True         it "fails an asynchronous post-handshake auth with a rejected certificate" $             post_handshake_auth_async_wait False+        it "fails the waiter when the transport breaks" $+            post_handshake_auth_async_reset+        it "fails the waiter when a receive is interrupted inside a record" $+            post_handshake_auth_async_interrupted+        it "fails the waiter when the server says bye" $+            post_handshake_auth_async_bye+        it "closes the connection when a synchronous post-handshake auth fails" $+            post_handshake_auth_sync_fail         it "commits the client certificate of a post-handshake auth at Finished" $             post_handshake_auth_async_finished         it@@ -3423,6 +3431,24 @@         _ <- requestCertificate ctx -- two simultaneously         sendData ctx "response 2" +-- | After a rejected certificate, the alert has closed the connection.+post_handshake_auth_sync_fail :: IO ()+post_handshake_auth_sync_fail = do+    params <- generate arbitraryPairParams13+    cred <- generate arbitraryPHACredential+    withPairContext (phaParams False cred params) $ \(cCtx, sCtx) ->+        concurrently_ (hsServer sCtx) (hsClient cCtx)+  where+    hsClient ctx = do+        handshake ctx+        sendData ctx "request 1"+        void (recvData ctx) `shouldThrow` anyTLSException+    hsServer ctx = do+        handshake ctx+        recvDataAssert ctx "request 1"+        void (requestCertificate ctx) `shouldThrow` anyTLSException+        sendData ctx "response 1" `shouldThrow` anyTLSException+ type PairParams = (ClientParams, ServerParams)  -- | Client and server parameters for post-handshake authentication with@@ -3518,6 +3544,77 @@                 void (recvData ctx) `shouldThrow` anyTLSException                 takeMVar result >>= (`shouldSatisfy` isFailed)     isFailed (PHAFailed _) = True+    isFailed _ = False++-- | The transport breaks while a response is pending: the waiter fails+-- instead of blocking forever.+post_handshake_auth_async_reset :: IO ()+post_handshake_auth_async_reset = do+    params <- generate arbitraryPairParams13+    cred <- generate arbitraryPHACredential+    let (cParams, sParams) = phaParams True cred params+    pipe <- newPipe+    _ <- runPipe pipe+    broken <- newIORef False+    let noop = return ()+        sRecv n = do+            b <- readIORef broken+            if b then ioError (userError "reset") else readPipeS pipe n+        cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+        sBackend = Backend noop noop (writePipeS pipe) sRecv+    cCtx <- contextNew cBackend cParams+    sCtx <- contextNew sBackend sParams+    concurrently_ (handshake cCtx) (handshake sCtx)+    check <- requestCertificateAsync sCtx+    writeIORef broken True+    void (recvData sCtx) `shouldThrow` anyIOException+    timeout 1000000 (check True) >>= (`shouldSatisfy` isFailed)+  where+    isFailed (Just (PHAFailed _)) = True+    isFailed _ = False++-- | A receive is interrupted by an exception inside a record while a+-- response is pending: the waiter fails instead of blocking forever.+post_handshake_auth_async_interrupted :: IO ()+post_handshake_auth_async_interrupted = do+    params <- generate arbitraryPairParams13+    cred <- generate arbitraryPHACredential+    let (cParams, sParams) = phaParams True cred params+    pipe <- newPipe+    _ <- runPipe pipe+    broken <- newIORef False+    let noop = return ()+        -- only the body of a record, never its 5-byte header+        sRecv n = do+            b <- readIORef broken+            if b && n /= 5 then E.throwIO (E.ErrorCall "interrupted") else readPipeS pipe n+        cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+        sBackend = Backend noop noop (writePipeS pipe) sRecv+    cCtx <- contextNew cBackend cParams+    sCtx <- contextNew sBackend sParams+    concurrently_ (handshake cCtx) (handshake sCtx)+    check <- requestCertificateAsync sCtx+    writeIORef broken True+    sendData cCtx "request"+    void (recvData sCtx) `shouldThrow` errorCall "interrupted"+    timeout 1000000 (check True) >>= (`shouldSatisfy` isFailed)+  where+    isFailed (Just (PHAFailed _)) = True+    isFailed _ = False++-- | The server says bye while a response is pending and nobody reads: the+-- waiter fails instead of blocking forever.+post_handshake_auth_async_bye :: IO ()+post_handshake_auth_async_bye = do+    params <- generate arbitraryPairParams13+    cred <- generate arbitraryPHACredential+    withPairContext (phaParams True cred params) $ \(cCtx, sCtx) -> do+        concurrently_ (handshake cCtx) (handshake sCtx)+        check <- requestCertificateAsync sCtx+        bye sCtx+        timeout 1000000 (check True) >>= (`shouldSatisfy` isFailed)+  where+    isFailed (Just (PHAFailed _)) = True     isFailed _ = False  -- | The client's Finished is held back after its CertificateVerify has been
tls.cabal view
@@ -1,6 +1,6 @@ cabal-version:      2.0 name:               tls-version:            2.5.5+version:            2.6.4 license:            BSD3 license-file:       LICENSE copyright:          Vincent Hanquez <vincent@snarc.org>@@ -124,7 +124,7 @@         base16-bytestring,         bytestring >=0.10 && <0.13,         cereal >=0.5.3 && <0.6,-        crypton >=2.1.9 && <2.3,+        crypton >=2.1.9 && <2.4,         crypton-asn1-encoding >= 0.10.0 && < 0.12,         crypton-asn1-types >= 0.4.1 && < 0.5,         crypton-x509 >=1.10 && <1.12,@@ -138,6 +138,7 @@         ram >=0.22.0 && <0.23,         random >=1.2 && <1.4,         serialise >=0.2 && <0.3,+        stm,         transformers >=0.5 && <0.7,         unix-time >=0.4.11 && <0.7,         zlib >=0.7 && <0.8@@ -163,7 +164,7 @@         crypton-x509-system,         ech-config,         network,-        network-run,+        network-run >=0.8 && <0.9,         tls      if flag(devel)@@ -191,7 +192,7 @@         crypton-x509-system,         ech-config,         network,-        network-run >=0.6.0 && < 0.7,+        network-run >=0.8 && <0.9,         tls      if flag(devel)@@ -207,11 +208,12 @@     other-modules:         API         Arbitrary-        Certificate         ByeSpec+        Certificate         ChannelBindingSpec         CiphersSpec         ECHSpec+        GiveUpSpec         EncodeSpec         HandshakeSpec         PipeChan@@ -236,8 +238,13 @@         crypton-x509-validation,         ech-config,         hspec,+        network,         ram,         serialise,+        stm,         time-hourglass,         tls,         zlib++    if os(windows)+        ghc-options: -with-rtsopts=--io-manager=native