packages feed

tls 2.5.4 → 2.5.5

raw patch · 11 files changed

+272/−18 lines, 11 filesPVP ok

version bump matches the API change (PVP)

API changes (from Hackage documentation)

Files

CHANGELOG.md view
@@ -1,5 +1,16 @@ # Change log for "tls" +## Version 2.5.5++* 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.+  [#663](https://github.com/haskell-tls/hs-tls/pull/663)+* bye neither sends nor waits after a failed send.+  [#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)+ ## Version 2.5.4  * Use up a session for 0-RTT only after checking the ClientHello.
Network/TLS/Context.hs view
@@ -174,6 +174,7 @@     tlsstate <- newMVar st     eof <- newIORef False     closeNotify <- newIORef False+    txBroken <- newIORef Nothing     established <- newIORef NotEstablished     stats <- newIORef newMeasurement     needEmptyPacket <- newIORef False@@ -214,6 +215,7 @@                 , ctxMeasurement = stats                 , ctxEOF_ = eof                 , ctxCloseNotify_ = closeNotify+                , ctxTxBroken_ = txBroken                 , ctxEstablished_ = established                 , ctxNeedEmptyPacket = needEmptyPacket                 , ctxHooks = hooks
Network/TLS/Context/Internal.hs view
@@ -24,12 +24,15 @@     RoleParams (..),     ctxEOF,     ctxCloseNotify,+    ctxTxBroken,+    ctxTxBrokenBy,     ctxEstablished,     withLog,     ctxWithHooks,     contextModifyHooks,     setEOF,     setCloseNotify,+    setTxBroken,     setEstablished,     skipEarlyData,     contextFlush,@@ -137,6 +140,9 @@     -- ^ has the handle EOFed or not.     , ctxCloseNotify_ :: IORef Bool     -- ^ has close_notify been received or not.+    , ctxTxBroken_ :: IORef (Maybe E.SomeException)+    -- ^ the exception of the first failed send, which left the TX record+    -- state ahead of the peer.     , ctxEstablished_ :: IORef Established     -- ^ has the handshake been done and been successful.     , ctxTxRecordState :: MVar RecordState@@ -434,6 +440,15 @@  setCloseNotify :: Context -> IO () setCloseNotify ctx = writeIORef (ctxCloseNotify_ ctx) True++ctxTxBroken :: Context -> IO Bool+ctxTxBroken ctx = isJust <$> ctxTxBrokenBy ctx++ctxTxBrokenBy :: Context -> IO (Maybe E.SomeException)+ctxTxBrokenBy ctx = readIORef $ ctxTxBroken_ ctx++setTxBroken :: Context -> E.SomeException -> IO ()+setTxBroken ctx e = atomicModifyIORef' (ctxTxBroken_ ctx) $ \m -> (m <|> Just e, ())  ctxEstablished :: Context -> IO Established ctxEstablished ctx = readIORef $ ctxEstablished_ ctx
Network/TLS/Core.hs view
@@ -43,6 +43,7 @@ import Network.TLS.Context import Network.TLS.Context.Internal (     PHAResult (..),+    ctxTxBroken,     incrementTLS13KeyUpdateCount,     resetTLS13KeyUpdateCount,  )@@ -67,6 +68,7 @@     Bulk (..),     Cipher (..),     HostName,+    Millisecond,     Role (..),  ) import Network.TLS.Util (catchException, mapChunks_)@@ -121,10 +123,15 @@ rttFactor :: Int rttFactor = 3 +-- | An upper bound of the RTT measured in the handshake, which sets how+-- long to wait for the peer.+maxWaitRTT :: Millisecond+maxWaitRTT = 1000+ getRTT :: Context -> IO Int getRTT ctx = do     rtt <- tls13stRTT <$> getTLS13State ctx-    let rtt' = max (fromIntegral rtt) 10+    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.@@ -147,8 +154,10 @@ bye :: MonadIO m => Context -> m () bye ctx = liftIO $ do     eof <- ctxEOF ctx+    -- After a failed send, nothing is sent, so nothing is waited for either.+    broken <- ctxTxBroken ctx     tls13 <- tls13orLater ctx-    when (tls13 && not eof) $ do+    when (tls13 && not eof && not broken) $ do         role <- usingState_ ctx getRole         if role == ClientRole             then do@@ -196,8 +205,9 @@     -- 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 $+    unless (eof || broken) $         withWriteLock ctx $             if tls13                 then sendPacket13 ctx $ Alert13 [(AlertLevel_Warning, CloseNotify)]@@ -310,7 +320,7 @@     -- UserCanceled should be followed by a close_notify.     -- fixme: is it safe to call recvData12?     process (Alert [(AlertLevel_Warning, UserCanceled)]) = return B.empty-    process (Alert [(AlertLevel_Warning, CloseNotify)]) = setCloseNotify ctx >> tryBye ctx >> setEOF ctx >> return B.empty+    process (Alert [(AlertLevel_Warning, CloseNotify)]) = setCloseNotify ctx >> tryBye ctx >> return B.empty     process (Alert [(AlertLevel_Fatal, desc)]) = do         setEOF ctx         E.throwIO@@ -359,7 +369,7 @@     -- closure ones are error alerts, even at the warning level.     -- UserCanceled MUST be followed by a CloseNotify.     process (Alert13 [(_, UserCanceled)]) = return B.empty-    process (Alert13 [(_, CloseNotify)]) = setCloseNotify ctx >> tryBye ctx >> setEOF ctx >> return B.empty+    process (Alert13 [(_, CloseNotify)]) = setCloseNotify ctx >> tryBye ctx >> return B.empty     process (Alert13 [(_, desc)]) = do         setEOF ctx         E.throwIO@@ -498,7 +508,7 @@   where     -- UserCanceled MUST be followed by a CloseNotify.     process (Alert13 [(_, UserCanceled)]) = recvHS13 ctx breakLoop-    process (Alert13 [(_, CloseNotify)]) = setCloseNotify ctx >> tryBye ctx >> setEOF ctx+    process (Alert13 [(_, CloseNotify)]) = setCloseNotify ctx >> tryBye ctx     process (Alert13 [(_, _desc)]) = setEOF ctx     process (Handshake13 hs bs) = do         loopHandshake13 $ zip hs bs@@ -597,7 +607,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 ())+tryBye ctx = catchException (bye_ ctx) (\_ -> return ()) `E.finally` setEOF ctx  onError     :: Monad m
Network/TLS/Handshake/Common.hs view
@@ -87,7 +87,8 @@             _ -> Error_Misc (show exception)     established <- ctxEstablished ctx     setEstablished ctx NotEstablished-    E.handle ignoreIOErr $ do+    -- A failure of the send, whatever it is, must not skip 'setEOF'.+    (`catchException` \_ -> return ()) $ do         tls13 <- tls13orLater ctx         if tls13             then do@@ -97,9 +98,6 @@                         Alert13 [errorToAlert tlserror]             else sendPacket12 ctx $ Alert [errorToAlert tlserror]     handshakeFailed tlserror-  where-    ignoreIOErr :: E.IOException -> IO ()-    ignoreIOErr _ = return ()  errorToAlert :: TLSError -> (AlertLevel, AlertDescription) errorToAlert (Error_Protocol _ ad) = (AlertLevel_Fatal, ad)
Network/TLS/Handshake/Common13.hs view
@@ -21,6 +21,7 @@     isAgeValid,     getAge,     checkFreshness,+    maxRTT,     getCurrentTimeFromBase,     getSessionData13,     isHashSignatureValid13,@@ -326,7 +327,11 @@ getAge TLS13TicketInfo{..} = do     let clientReceiveTime = txrxTime     clientSendTime <- getCurrentTimeFromBase-    return $ fromIntegral (clientSendTime - clientReceiveTime) -- milliseconds+    -- The wall clock can go back, which must not wrap the age around.+    return $+        if clientSendTime > clientReceiveTime+            then fromIntegral (clientSendTime - clientReceiveTime) -- milliseconds+            else 0  checkFreshness :: TLS13TicketInfo -> Second -> IO Bool checkFreshness tinfo@TLS13TicketInfo{..} obfAge = do@@ -342,10 +347,16 @@     return $ isAlive && isFresh   where     serverSendTime = txrxTime-    rtt = fromJust estimatedRTT+    -- Capped also for a ticket issued before the RTT was capped.+    rtt = min maxRTT $ fromJust estimatedRTT     age = obfuscatedAgeToAge obfAge tinfo     expectedArrivalTime = serverSendTime + rtt + fromIntegral age     isAlive = isAgeValid age tinfo++-- | The RTT kept in a ticket is capped: it widens the tolerance of the+-- freshness check, and the client can delay its Finished to inflate it.+maxRTT :: Millisecond+maxRTT = 10000  getCurrentTimeFromBase :: IO Millisecond getCurrentTimeFromBase = millisecondsFromBase <$> getUnixTime
Network/TLS/Handshake/Server/TLS13.hs view
@@ -146,7 +146,10 @@     -> IO () sendNewSessionTicket sparams ctx usedCipher exts applicationSecret sfSentTime = when sendNST $ do     cfRecvTime <- getCurrentTimeFromBase-    let rtt = cfRecvTime - sfSentTime+    -- The wall clock can go back, which must not wrap the RTT around.+    let rtt+            | cfRecvTime > sfSentTime = min maxRTT $ cfRecvTime - sfSentTime+            | otherwise = 0     nonce <- TicketNonce <$> getStateRNG ctx 32     resumptionSecret <- calculateResumptionSecret ctx choice applicationSecret     let life = adjustLifetime $ serverTicketLifetime sparams
Network/TLS/Record/Send.hs view
@@ -6,6 +6,7 @@ ) where  import Control.Concurrent.MVar+import qualified Control.Exception as E import Control.Monad.State.Strict import qualified Data.ByteString as B @@ -57,5 +58,14 @@  sendBytes :: Context -> ByteString -> IO () sendBytes ctx dataToSend = do+    -- 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)     withLog ctx $ \logging -> loggingIOSent logging dataToSend-    contextSend ctx 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
+ test/ByeSpec.hs view
@@ -0,0 +1,154 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module ByeSpec where++import Control.Concurrent+import Control.Concurrent.Async+import qualified Control.Exception as E+import Control.Monad (forever, when)+import Data.Either (isLeft)+import Data.IORef+import GHC.Clock (getMonotonicTime)+import Network.TLS+import System.Timeout+import Test.Hspec+import Test.QuickCheck (generate)++import Arbitrary+import PipeChan++spec :: Spec+spec = describe "bye" $ do+    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+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef armed True+        t0 <- getMonotonicTime+        bye cCtx+        t1 <- getMonotonicTime+        (t1 - t0) `shouldSatisfy` (< 4)++    it "sends nothing after a failed send" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        sent <- newIORef (0 :: Int)+        let noop = return ()+            sendS bs = do+                f <- readIORef failing+                when f $ E.throwIO E.ThreadKilled+                modifyIORef' sent (+ 1)+                writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        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"))+        n <- readIORef sent+        timeout 5000000 (bye sCtx) `shouldReturn` Just ()+        readIORef sent `shouldReturn` n++    it "throws the exception of the failed send again" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            sendS bs = do+                f <- atomicModifyIORef' failing (\x -> (False, x))+                when f $ E.throwIO $ E.ErrorCall "broken"+                writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        E.try (sendData sCtx "abc") `shouldReturn` Left (E.ErrorCall "broken")+        E.try (sendData sCtx "abc") `shouldReturn` Left (E.ErrorCall "broken")++    it "does not wait after a failed send" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        readAfter <- 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+            sBackend = Backend noop noop (writePipeS pipe) (readPipeS pipe)+        cCtx <- contextNew cBackend 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++    it "sends nothing after a handshake whose send failed" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        let noop = return ()+            broken _ = E.throwIO $ E.ErrorCall "broken"+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop broken (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        withAsync (handshake cCtx) $ \_ -> do+            r <- E.try @TLSException $ handshake sCtx+            r `shouldSatisfy` isLeft+            timeout 5000000 (bye sCtx) `shouldReturn` Just ()++    it "ends the connection when the answer to close_notify fails" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            sendS bs = do+                f <- readIORef failing+                when f $ E.throwIO E.ThreadKilled+                writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        withAsync (bye cCtx) $ \_ -> do+            E.try @E.AsyncException (recvData sCtx) `shouldReturn` Left E.ThreadKilled+            timeout 1000000 (E.try @TLSException (recvData sCtx))+                `shouldReturn` Just (Left (PostHandshake Error_EOF))
test/HandshakeSpec.hs view
@@ -255,6 +255,10 @@             handshake13_0rtt_only_once True         it "refuses 0RTT, not the resumption, when the session is used up" $             handshake13_0rtt_only_once False+        it "caps the RTT of a ticket in the freshness check" $+            handshake13_0rtt_wrapped_rtt+        it "sends the age 0 of a ticket received in the client's future" $+            handshake13_0rtt_client_clock_back         it "authenticates a server rejecting the PSK of 0RTT" $             handshake13_0rtt_psk_rejected False         it "authenticates a server rejecting the PSK of 0RTT, asking a cert" $@@ -3000,7 +3004,17 @@ -- with a verified binder.  A stale one falls back to a full handshake -- without it; a session it has used up already is resumed without 0RTT. handshake13_0rtt_only_once :: Bool -> IO ()-handshake13_0rtt_only_once stale = do+handshake13_0rtt_only_once stale = handshake13_0rtt_aged $ if stale then Just id else Nothing++-- | An RTT wrapped around by a wall clock going back does not make a stale+-- ticket fresh.+handshake13_0rtt_wrapped_rtt :: IO ()+handshake13_0rtt_wrapped_rtt =+    handshake13_0rtt_aged $ Just $ \t -> t{estimatedRTT = Just (maxBound - 4)}++-- | The client's clock went back by an hour after receiving the ticket.+handshake13_0rtt_client_clock_back :: IO ()+handshake13_0rtt_client_clock_back = do     (cli, srv) <- generate arbitraryPairParams13     let supported =             defaultSupported@@ -3013,6 +3027,31 @@             , srv{serverSupported = supported, serverEarlyDataSize = 2048}             )     sessionRefs <- twoSessionRefs+    let params = setPairParamsSessionManagers (twoSessionManagers sessionRefs) params0+    runTLSSimple13 params FullHandshake+    Just (sid, sdata) <- readClientSessionRef sessionRefs+    let future t = t{txrxTime = txrxTime t + 3600000}+        sdata' = sdata{sessionTicketInfo = future <$> sessionTicketInfo sdata}+        (pc, ps) = setPairParamsSessionResuming (sid, sdata') params+    runTLS0RTT (pc{clientUseEarlyData = True}, ps) RTT0 "early data"++-- | With 'Just', the ticket is made an hour old and modified further.+handshake13_0rtt_aged :: Maybe (TLS13TicketInfo -> TLS13TicketInfo) -> IO ()+handshake13_0rtt_aged mmodify = do+    let stale = isJust mmodify+        modify = fromMaybe id mmodify+    (cli, srv) <- generate arbitraryPairParams13+    let supported =+            defaultSupported+                { supportedCiphers = [cipher13_AES_128_GCM_SHA256]+                , supportedGroups = [X25519]+                , supportedGroupsTLS13 = [[X25519]]+                }+        params0 =+            ( cli{clientSupported = supported}+            , srv{serverSupported = supported, serverEarlyDataSize = 2048}+            )+    sessionRefs <- twoSessionRefs     let (cmgr, smgr) = twoSessionManagers sessionRefs         params = setPairParamsSessionManagers (cmgr, smgr) params0     runTLSSimple13 params FullHandshake@@ -3024,7 +3063,7 @@         age sdata =             sdata                 { sessionTicketInfo =-                    (\t -> t{txrxTime = txrxTime t - 3600000}) <$> sessionTicketInfo sdata+                    (\t -> modify t{txrxTime = txrxTime t - 3600000}) <$> sessionTicketInfo sdata                 }         resume' f sid             | stale = fmap age <$> f sid
tls.cabal view
@@ -1,6 +1,6 @@ cabal-version:      2.0 name:               tls-version:            2.5.4+version:            2.5.5 license:            BSD3 license-file:       LICENSE copyright:          Vincent Hanquez <vincent@snarc.org>@@ -208,6 +208,7 @@         API         Arbitrary         Certificate+        ByeSpec         ChannelBindingSpec         CiphersSpec         ECHSpec