quic 0.3.25 → 0.3.26
raw patch · 13 files changed
+453/−59 lines, 13 filesPVP: major bump suggested
API removals or changes: PVP suggests a major version bump
API changes (from Hackage documentation)
+ Network.QUIC.Internal: AddrKey4 :: HostAddress -> AddrKey
+ Network.QUIC.Internal: AddrKey6 :: Word32 -> Word32 -> AddrKey
+ Network.QUIC.Internal: AddrKeyOther :: AddrKey
+ Network.QUIC.Internal: Admitted :: Admission
+ Network.QUIC.Internal: Handshakes :: Int -> Map (Bool, AddrKey) Int -> Handshakes
+ Network.QUIC.Internal: NeedRetry :: Admission
+ Network.QUIC.Internal: Refused :: Admission
+ Network.QUIC.Internal: [scMaxHandshakesPerAddress] :: ServerConfig -> Int
+ Network.QUIC.Internal: [scMaxHandshakes] :: ServerConfig -> Int
+ Network.QUIC.Internal: addrKey :: SockAddr -> AddrKey
+ Network.QUIC.Internal: admitHandshakeWith :: Int -> Int -> Bool -> AddrKey -> Handshakes -> (Admission, Handshakes)
+ Network.QUIC.Internal: data AddrKey
+ Network.QUIC.Internal: data Admission
+ Network.QUIC.Internal: data Handshakes
+ Network.QUIC.Internal: handshakeTimeout :: Milliseconds
+ Network.QUIC.Internal: maxPendingPackets :: Int
+ Network.QUIC.Internal: noHandshakes :: Handshakes
+ Network.QUIC.Internal: receiver :: Connection -> IO ()
+ Network.QUIC.Internal: receiverWith :: Connection -> TVar Bool -> IO ()
+ Network.QUIC.Internal: refusalLimit :: PerSecond
+ Network.QUIC.Internal: releaseHandshakeWith :: Bool -> AddrKey -> Handshakes -> Handshakes
+ Network.QUIC.Internal: withinRefusalLimit :: Rate -> IO Bool
+ Network.QUIC.Server: scMaxHandshakes :: ServerConfig -> Int
+ Network.QUIC.Server: scMaxHandshakesPerAddress :: ServerConfig -> Int
- Network.QUIC.Internal: ServerConfig :: [Version] -> [Cipher] -> [Group] -> [[Group]] -> Parameters -> (String -> IO ()) -> Maybe FilePath -> Credentials -> Hooks -> ServerHooks -> Bool -> Int -> [(IP, PortNumber)] -> Maybe (Version -> [ByteString] -> IO ByteString) -> Bool -> Bool -> Int -> SessionManager -> Maybe FilePath -> Int -> (ApplicationProtocolError, ReasonPhrase) -> (IO () -> IO ()) -> ServerConfig
+ Network.QUIC.Internal: ServerConfig :: [Version] -> [Cipher] -> [Group] -> [[Group]] -> Parameters -> (String -> IO ()) -> Maybe FilePath -> Credentials -> Hooks -> ServerHooks -> Bool -> Int -> [(IP, PortNumber)] -> Maybe (Version -> [ByteString] -> IO ByteString) -> Bool -> Bool -> Int -> Int -> Int -> SessionManager -> Maybe FilePath -> Int -> (ApplicationProtocolError, ReasonPhrase) -> (IO () -> IO ()) -> ServerConfig
- Network.QUIC.Internal: putOffCrypto :: Connection -> EncryptionLevel -> ReceivedPacket -> IO ()
+ Network.QUIC.Internal: putOffCrypto :: Connection -> EncryptionLevel -> ReceivedPacket -> IO Bool
Files
- ChangeLog.md +11/−0
- Network/QUIC/Config.hs +17/−0
- Network/QUIC/Connection/Crypto.hs +24/−14
- Network/QUIC/Connection/RateControl.hs +11/−0
- Network/QUIC/Internal.hs +18/−0
- Network/QUIC/Receiver.hs +86/−30
- Network/QUIC/Server.hs +2/−0
- Network/QUIC/Server/Reader.hs +103/−10
- Network/QUIC/Server/Run.hs +2/−0
- Network/QUIC/Types/Constants.hs +13/−0
- quic.cabal +3/−3
- test/HandshakeSpec.hs +94/−0
- test/PacketSpec.hs +69/−2
ChangeLog.md view
@@ -1,5 +1,16 @@ # ChangeLog +## 0.3.26++Security fixes against unauthenticated peers. Adds `scMaxHandshakes`+and `scMaxHandshakesPerAddress`.++* Bound the packets kept until their keys are there+* Restart the idle timer only on packets that decrypt+* Give a server's handshake 10 seconds+* Answer with a Retry or refuse over limits on handshakes going on+* Limit CONNECTION_REFUSED to 100 a second+ ## 0.3.25 From the v0.3 branch: main goes on to 0.4, whose types change. Fixes
Network/QUIC/Config.hs view
@@ -199,6 +199,21 @@ -- would open one more is answered with CONNECTION_REFUSED. 0 or less, -- the default being 0, sets no limit; a server open to the Internet -- should set one.+ , scMaxHandshakes :: Int+ -- ^ How many handshakes may be going on at once before an Initial+ -- packet from an address not validated yet is answered with a Retry+ -- instead of a new connection. 0 or less sets no limit. The default+ -- is 1000.+ --+ -- @since 0.3.26+ , scMaxHandshakesPerAddress :: Int+ -- ^ How many handshakes one address, an IPv6 /64 counting as one, may+ -- have going on at once. Past it, an Initial packet from an address+ -- not validated yet is answered with a Retry, and one from a+ -- validated address is refused. 0 or less sets no limit. The default+ -- is 100.+ --+ -- @since 0.3.26 , scSessionManager :: SessionManager -- ^ A session manager of TLS 1.3. , scDebugLog :: Maybe FilePath@@ -249,6 +264,8 @@ , scWantClientCert = False , scRequireRetry = False , scMaxConnections = 0+ , scMaxHandshakes = 1000+ , scMaxHandshakesPerAddress = 100 , scSessionManager = noSessionManager , scDebugLog = Nothing , scTicketLifetime = 7200
Network/QUIC/Connection/Crypto.hs view
@@ -42,21 +42,31 @@ ---------------------------------------------------------------- setEncryptionLevel :: Connection -> EncryptionLevel -> IO ()-setEncryptionLevel Connection{..} lvl = do- let q = connRecvQ- atomically $ do- writeTVar (encryptionLevel connState) lvl- case lvl of- HandshakeLevel -> do- readTVar (pendingQ ! RTT0Level) >>= mapM_ (prependRecvQ q)- readTVar (pendingQ ! HandshakeLevel) >>= mapM_ (prependRecvQ q)- RTT1Level ->- readTVar (pendingQ ! RTT1Level) >>= mapM_ (prependRecvQ q)- _ -> return ()+setEncryptionLevel Connection{..} lvl = atomically $ do+ writeTVar (encryptionLevel connState) lvl+ case lvl of+ HandshakeLevel -> do+ flush RTT0Level+ flush HandshakeLevel+ RTT1Level -> flush RTT1Level+ _ -> return ()+ where+ -- Emptied as well, or the packets stay for the connection's life.+ flush l = do+ let tv = pendingQ ! l+ readTVar tv >>= mapM_ (prependRecvQ connRecvQ)+ writeTVar tv [] -putOffCrypto :: Connection -> EncryptionLevel -> ReceivedPacket -> IO ()-putOffCrypto Connection{..} lvl rpkt =- atomically $ modifyTVar' (pendingQ ! lvl) (rpkt :)+-- | Keeping a packet until its keys are there, unless 'maxPendingPackets'+-- are kept already, which a peer not finishing the handshake could+-- otherwise push without bound. 'False' if it is dropped.+putOffCrypto :: Connection -> EncryptionLevel -> ReceivedPacket -> IO Bool+putOffCrypto Connection{..} lvl rpkt = atomically $ do+ let tv = pendingQ ! lvl+ rpkts <- readTVar tv+ if length rpkts < maxPendingPackets+ then writeTVar tv (rpkt : rpkts) >> return True+ else return False waitEncryptionLevel :: Connection -> EncryptionLevel -> IO () waitEncryptionLevel conn = atomically . waitEncryptionLevelSTM conn
Network/QUIC/Connection/RateControl.hs view
@@ -8,6 +8,7 @@ pathResponseLimit, queuedControlLimit, statelessResetLimit,+ refusalLimit, statelessResetSize, statelessResetSizeFor, @@ -16,6 +17,7 @@ withinPathResponseLimit, enforceQueuedControlLimit, withinStatelessResetLimit,+ withinRefusalLimit, ) where import Network.Control (Rate, addRate)@@ -68,6 +70,11 @@ statelessResetLimit :: PerSecond statelessResetLimit = PerSecond 20 +-- | Per server, CONNECTION_REFUSED sent. The rest are not sent: a client+-- not told gives up by itself.+refusalLimit :: PerSecond+refusalLimit = PerSecond 100+ -- | The largest stateless reset we send, in octets. statelessResetSize :: Int statelessResetSize = 1280@@ -130,3 +137,7 @@ -- | Whether a stateless reset may be sent under 'statelessResetLimit'. withinStatelessResetLimit :: Rate -> IO Bool withinStatelessResetLimit rate = addWithin rate 1 statelessResetLimit++-- | Whether a CONNECTION_REFUSED may be sent under 'refusalLimit'.+withinRefusalLimit :: Rate -> IO Bool+withinRefusalLimit rate = addWithin rate 1 refusalLimit
Network/QUIC/Internal.hs view
@@ -21,9 +21,18 @@ processFrame, processReceivedPacket, processReceivedPacketHandshake,+ receiver,+ receiverWith, newRecvQDict, lookupInsertRecvQDict, deleteRecvQDict,+ Handshakes (..),+ noHandshakes,+ AddrKey (..),+ addrKey,+ Admission (..),+ admitHandshakeWith,+ releaseHandshakeWith, ) where import Network.QUIC.Client.Reader (@@ -46,11 +55,20 @@ processFrame, processReceivedPacket, processReceivedPacketHandshake,+ receiver,+ receiverWith, ) import Network.QUIC.Recovery import Network.QUIC.Sender (adjustForRetransmit, sendOutput) import Network.QUIC.Server.Reader (+ Admission (..),+ AddrKey (..),+ Handshakes (..),+ addrKey,+ admitHandshakeWith, deleteRecvQDict,+ noHandshakes,+ releaseHandshakeWith, lookupInsertRecvQDict, newRecvQDict, )
Network/QUIC/Receiver.hs view
@@ -3,13 +3,16 @@ module Network.QUIC.Receiver ( receiver,+ receiverWith, processFrame, processReceivedPacket, processReceivedPacketHandshake, ) where import Control.Concurrent.STM (+ TVar, atomically,+ newTVarIO, orElse, readTVar, readTVarIO,@@ -40,17 +43,37 @@ import Network.QUIC.Types as QUIC receiver :: Connection -> IO ()-receiver conn = handleLogT logAction body+receiver conn = do+ -- A server's handshake has 'handshakeTimeout', however busy the peer.+ hsExpired <-+ if isServer conn+ then let Microseconds us = milliToMicro handshakeTimeout in registerDelay us+ else newTVarIO False+ receiverWith conn hsExpired++-- | 'receiver' whose handshake times out once the variable is 'True'.+receiverWith :: Connection -> TVar Bool -> IO ()+receiverWith conn hsExpired = do+ active <- getTimeMicrosecond >>= newIORef+ sendCounted <- newIORef False+ receiver' conn active sendCounted hsExpired++receiver'+ :: Connection -> IORef TimeMicrosecond -> IORef Bool -> TVar Bool -> IO ()+receiver' conn active sendCounted hsExpired = handleLogT logAction body where body = loopHandshake -- 'Nothing' once another thread has ended the connection.- recvTimeout = do+ recvTimeout inHandshake = do -- The spec says that CC is not sent when timeout. -- But we intentionally sends CC when timeout. -- Waited for beside the packet rather than thrown at the wait. mito <- getIdleTimeout conn- got <- waitIdle mito+ got <- waitIdle inHandshake mito case got of+ HandshakeExpired -> do+ qlogDebug conn $ Debug "handshake timeout"+ E.throwIO $ ConnectionIsTimeout "Server handshake" Expired -> do st <- getConnectionState conn let msg0@@ -59,40 +82,60 @@ msg = msg0 ++ " " ++ show st qlogDebug conn $ Debug "recv timeout" E.throwIO $ ConnectionIsTimeout msg- Got x -> do- atomically $ writeTVar (connAckElicitingSent conn) False- return $ Just x+ Got x -> return $ Just x _ -> return Nothing ended = Ended <$ connectionEndedSTM conn- -- RFC 9000 Sec 10.1: the timer restarts on receiving a packet and on- -- the first ack-eliciting packet sent after that.- waitIdle Nothing = atomically $ ended `orElse` (Got <$> connRecv conn)- waitIdle mito@(Just (Microseconds us)) = do- sent0 <- readTVarIO $ connAckElicitingSent conn- expired <- registerDelay us+ -- Not once the handshake is over: this loop learns that only from the+ -- next packet, which an idle peer may not send.+ handshakeOver inHandshake+ | inHandshake = do+ readTVar hsExpired >>= STM.check+ st <- readTVar $ connectionState $ connState conn+ STM.check $ st < Established+ return HandshakeExpired+ | otherwise = retry+ -- RFC 9000 Sec 10.1: the timer restarts on a packet received and+ -- processed successfully, and on the first ack-eliciting packet sent+ -- after that. A packet that does not decrypt restarts nothing.+ processed ok = when ok $ do+ getTimeMicrosecond >>= writeIORef active+ writeIORef sendCounted False+ atomically $ writeTVar (connAckElicitingSent conn) False+ waitIdle inHandshake Nothing =+ atomically $+ ended `orElse` (Got <$> connRecv conn) `orElse` handshakeOver inHandshake+ waitIdle inHandshake mito@(Just us) = do+ sent <- readTVarIO $ connAckElicitingSent conn+ counted <- readIORef sendCounted+ when (sent && not counted) $ do+ getTimeMicrosecond >>= writeIORef active+ writeIORef sendCounted True+ Microseconds left <- (us -) <$> (readIORef active >>= getElapsedTimeMicrosecond)+ expired <- registerDelay $ max 0 left let restarted- | sent0 = retry+ | sent = retry | otherwise = readTVar (connAckElicitingSent conn) >>= STM.check r <- atomically $ ended `orElse` (Got <$> connRecv conn) `orElse` (Restarted <$ restarted)+ `orElse` handshakeOver inHandshake `orElse` (Expired <$ (readTVar expired >>= STM.check)) case r of- Restarted -> waitIdle mito+ Restarted -> waitIdle inHandshake mito _ -> return r loopHandshake = do- mrpkt <- recvTimeout+ mrpkt <- recvTimeout True -- Not 'forM_', which would leave each loop a frame to return to. case mrpkt of Nothing -> return () Just rpkt -> do- processReceivedPacketHandshake conn rpkt+ processReceivedPacketHandshake'' conn rpkt >>= processed established <- isConnectionEstablished conn if established then loopEstablished else loopHandshake loopEstablished = do- mrpkt <- recvTimeout+ mrpkt <- recvTimeout False case mrpkt of Nothing -> return () Just rpkt -> do@@ -120,7 +163,7 @@ writeIORef (sentRetirePriorTo conn) False unless sent $ sendFrames conn RTT1Level [NewConnectionID cidInfo 0]- processReceivedPacket' conn (Just cidChanged) rpkt+ processReceivedPacket' conn (Just cidChanged) rpkt >>= processed shouldUpdatePeer <- if shouldUpdate then shouldUpdatePeerCID conn@@ -132,24 +175,30 @@ loopEstablished logAction msg = connDebugLog conn ("debug: receiver: " <> msg) -data Got = Got ReceivedPacket | Restarted | Expired | Ended+data Got = Got ReceivedPacket | Restarted | Expired | HandshakeExpired | Ended processReceivedPacketHandshake :: Connection -> ReceivedPacket -> IO ()-processReceivedPacketHandshake conn rpkt- | serverZeroRTT conn rpkt = dropServerZeroRTT conn rpkt+processReceivedPacketHandshake conn = void . processReceivedPacketHandshake'' conn++-- | 'True' if the packet decrypted and was processed.+processReceivedPacketHandshake'' :: Connection -> ReceivedPacket -> IO Bool+processReceivedPacketHandshake'' conn rpkt+ | serverZeroRTT conn rpkt = dropServerZeroRTT conn rpkt >> return False | otherwise = processReceivedPacketHandshake' conn rpkt -processReceivedPacketHandshake' :: Connection -> ReceivedPacket -> IO ()+processReceivedPacketHandshake' :: Connection -> ReceivedPacket -> IO Bool processReceivedPacketHandshake' conn rpkt = do let CryptPacket hdr crypt = rpCryptPacket rpkt lvl = rpEncryptionLevel rpkt mx <- waitWithin (Microseconds 10000) $ waitEncryptionLevelSTM conn lvl case mx of Nothing -> do- putOffCrypto conn lvl rpkt+ kept <- putOffCrypto conn lvl rpkt+ unless kept $ qlogDropped conn (hdr, "too_many_pending" :: String) when (isClient conn) $ do lvl' <- getEncryptionLevel conn speedup (connLDCC conn) lvl' ("not decryptable: " <> toLogStr (show lvl))+ return False -- RFC 9000 Sec 7.2 and RFC 9001 Sec 4.9.1: what a packet tells us of -- the connection is taken only once it decrypts, or anyone on the -- path could break the handshake with a packet of garbage.@@ -167,8 +216,9 @@ case mver of -- RFC 9368 Sec 4: only a version we offered. Just peerVer- | peerVer `notElem` otherVersions (origVersionInfo conn) ->+ | peerVer `notElem` otherVersions (origVersionInfo conn) -> do qlogDropped conn (hdr, "unoffered_version" :: String)+ return False _ -> do dcid <- getClientDstCID conn mplain <- decryptReceived conn rpkt $ case mver of@@ -215,13 +265,14 @@ processDecrypted conn Nothing rpkt mplain processReceivedPacket :: Connection -> ReceivedPacket -> IO ()-processReceivedPacket conn = processReceivedPacket' conn Nothing+processReceivedPacket conn = void . processReceivedPacket' conn Nothing -- | With whether the packet came on a CID other than the one in use, once--- the handshake is over: only then may the peer migrate.-processReceivedPacket' :: Connection -> Maybe Bool -> ReceivedPacket -> IO ()+-- the handshake is over: only then may the peer migrate. 'True' if it+-- decrypted and was processed.+processReceivedPacket' :: Connection -> Maybe Bool -> ReceivedPacket -> IO Bool processReceivedPacket' conn mcidChanged rpkt- | serverZeroRTT conn rpkt = dropServerZeroRTT conn rpkt+ | serverZeroRTT conn rpkt = dropServerZeroRTT conn rpkt >> return False | otherwise = do let CryptPacket _ crypt = rpCryptPacket rpkt mplain <- decryptReceived conn rpkt $ decryptCrypt conn crypt lvl@@ -259,8 +310,9 @@ decrypt -- | Processing what 'decryptReceived' gave, 'Nothing' if it did not decrypt.+-- 'True' if it was a new packet that decrypted. processDecrypted- :: Connection -> Maybe Bool -> ReceivedPacket -> Maybe Plain -> IO ()+ :: Connection -> Maybe Bool -> ReceivedPacket -> Maybe Plain -> IO Bool processDecrypted conn mcidChanged rpkt mplain = do let CryptPacket hdr crypt = rpCryptPacket rpkt lvl = rpEncryptionLevel rpkt@@ -270,7 +322,9 @@ Nothing -> return False case mplain of -- RFC 9000 Sec 12.3: a packet processed already is discarded.- Just _ | dup -> qlogDropped conn (hdr, "duplicate" :: String)+ Just _ | dup -> do+ qlogDropped conn (hdr, "duplicate" :: String)+ return False Just plain@Plain{..} -> do addRxBytes conn $ rpReceivedBytes rpkt when (isIllegalReservedBits plainMarks || isNoFrames plainMarks) $@@ -309,6 +363,7 @@ when sup $ do qlogDebug conn $ Debug "ping for speedup" sendFrames conn lvl [Ping]+ return True Nothing -> do -- RFC 9001 Sec 6.6: "endpoints MUST count the number of received -- packets that fail authentication during the lifetime of a@@ -328,6 +383,7 @@ <> bhow lvl <> " size = " <> bhow (BS.length $ cryptPacket crypt)+ return False isSendOnly :: Connection -> StreamId -> Bool isSendOnly conn sid
Network/QUIC/Server.hs view
@@ -13,6 +13,8 @@ scWantClientCert, scRequireRetry, scMaxConnections,+ scMaxHandshakes,+ scMaxHandshakesPerAddress, scUse0RTT, scMaxDatagramFrameSize, scCiphers,
Network/QUIC/Server/Reader.hs view
@@ -19,6 +19,15 @@ -- * Accepting Accept (..), + -- * Handshakes going on+ Handshakes (..),+ noHandshakes,+ AddrKey (..),+ addrKey,+ Admission (..),+ admitHandshakeWith,+ releaseHandshakeWith,+ -- * Receiving and reading RecvQ, RecvQDict,@@ -39,9 +48,11 @@ import Network.ByteOrder import Network.Control (Rate, newRate) import Network.Socket (+ HostAddress, SockAddr (..), Socket, isClosedSocketError,+ tupleToHostAddress, ) import qualified Network.Socket.ByteString as NSB import qualified System.ThreadManager as T@@ -65,6 +76,7 @@ , srcTable :: RecvQDict , genStatelessReset :: CID -> StatelessResetToken , statelessResetRate :: Rate+ , refusalRate :: Rate , connectionThreads :: T.ThreadManager , dispatcherThreads :: T.ThreadManager -- ^ The threads reading the listening sockets. They are waited for@@ -76,8 +88,68 @@ -- what a connection's 'stop' reaches it by. , connectionCount :: TVar Int -- ^ Connections forked and not yet ended, for 'scMaxConnections'.+ , handshakes :: TVar Handshakes+ -- ^ Handshakes going on, for 'scMaxHandshakes' and+ -- 'scMaxHandshakesPerAddress'. } +-- | All of them, and those of each address, validated or not.+data Handshakes = Handshakes Int (Map (Bool, AddrKey) Int)+ deriving (Eq, Show)++noHandshakes :: Handshakes+noHandshakes = Handshakes 0 M.empty++-- | An IPv4 address, or an IPv6 /64: a host has a /64 of its own.+data AddrKey = AddrKey4 HostAddress | AddrKey6 Word32 Word32 | AddrKeyOther+ deriving (Eq, Ord, Show)++addrKey :: SockAddr -> AddrKey+addrKey (SockAddrInet _ ha) = AddrKey4 ha+addrKey (SockAddrInet6 _ _ (a, b, c, d) _)+ -- IPv4-mapped: the tuple is in host byte order, a 'HostAddress' is not.+ | a == 0 && b == 0 && c == 0xffff =+ AddrKey4 $ tupleToHostAddress (byte 24, byte 16, byte 8, byte 0)+ | otherwise = AddrKey6 a b+ where+ byte n = fromIntegral (d `shiftR` n)+addrKey _ = AddrKeyOther++data Admission = Admitted | NeedRetry | Refused+ deriving (Eq, Show)++-- | Counting a handshake in under the two limits, unless they say a Retry+-- or a refusal. A Retry for an address not validated: one that is+-- spoofed is not counted against the address, so it cannot lock the+-- real one out.+admitHandshakeWith+ :: Int -> Int -> Bool -> AddrKey -> Handshakes -> (Admission, Handshakes)+admitHandshakeWith maxAll maxAddr valid key hs@(Handshakes n m)+ | not valid && (overAll || overAddr) = (NeedRetry, hs)+ | overAddr = (Refused, hs)+ | otherwise = (Admitted, Handshakes (n + 1) (M.insert (valid, key) (k + 1) m))+ where+ k = M.findWithDefault 0 (valid, key) m+ overAll = maxAll > 0 && n >= maxAll+ overAddr = maxAddr > 0 && k >= maxAddr++releaseHandshakeWith :: Bool -> AddrKey -> Handshakes -> Handshakes+releaseHandshakeWith valid key (Handshakes n m) =+ Handshakes (n - 1) (M.update dec (valid, key) m)+ where+ dec k+ | k <= 1 = Nothing+ | otherwise = Just (k - 1)++admitHandshake :: Dispatch -> ServerConfig -> Bool -> AddrKey -> STM Admission+admitHandshake Dispatch{..} ServerConfig{..} valid key =+ stateTVar handshakes $+ admitHandshakeWith scMaxHandshakes scMaxHandshakesPerAddress valid key++releaseHandshake :: Dispatch -> Bool -> AddrKey -> STM ()+releaseHandshake Dispatch{..} valid key =+ modifyTVar' handshakes $ releaseHandshakeWith valid key+ newDispatch :: ServerConfig -> IO () -> IO Dispatch newDispatch ServerConfig{..} stopNow = Dispatch@@ -86,10 +158,12 @@ <*> newRecvQDict <*> makeGenStatelessReset <*> newRate+ <*> newRate <*> T.newThreadManager <*> T.newThreadManager <*> pure stopNow <*> newTVarIO 0+ <*> newTVarIO noHandshakes where conf = CT.defaultConfig@@ -216,6 +290,8 @@ -- ^ Taking the receive queue out of the source table, once ended , accAddressValidated :: Bool , accTime :: TimeMicrosecond+ , accHandshakeOver :: IO ()+ -- ^ Counting the handshake out, once however often it is called } ----------------------------------------------------------------@@ -319,7 +395,7 @@ -> IO () dispatch d@Dispatch{..}- ServerConfig{..}+ conf@ServerConfig{..} forkConnection logAction mysock@@ -398,20 +474,36 @@ -- A retransmission of an Initial already accepted. Just q -> writeRecvQ q $ mkReceivedPacket cpkt tim siz lvl Nothing -> do- ok <- reserveConnection d scMaxConnections- if ok- then accept myAuthCIDs peerAuthCIDs addrValid key- else -- RFC 9000 Sec 5.2.2: "If a server refuses to- -- accept a new connection, it SHOULD send an Initial- -- packet containing a CONNECTION_CLOSE frame with- -- error code CONNECTION_REFUSED."- encodeInitialRefusal peerVer sCID dCID >>= send'+ adm <- atomically $ admitHandshake d conf addrValid akey+ case adm of+ NeedRetry -> sendRetry+ Refused -> refuse+ Admitted -> do+ ok <- reserveConnection d scMaxConnections+ if ok+ then accept myAuthCIDs peerAuthCIDs addrValid key+ else do+ atomically $ releaseHandshake d addrValid akey+ refuse+ akey = addrKey peersa+ -- RFC 9000 Sec 5.2.2: "If a server refuses to accept a new+ -- connection, it SHOULD send an Initial packet containing a+ -- CONNECTION_CLOSE frame with error code CONNECTION_REFUSED."+ refuse = do+ ok <- withinRefusalLimit refusalRate+ when ok $ encodeInitialRefusal peerVer sCID dCID >>= send' accept myAuthCIDs peerAuthCIDs addrValid key = do (q, exist) <- lookupInsertRecvQDict srcTable key writeRecvQ q $ mkReceivedPacket cpkt tim siz lvl -- Another dispatcher got there first.- when exist $ releaseConnection d+ when exist $ do+ releaseConnection d+ atomically $ releaseHandshake d addrValid akey unless exist $ do+ overRef <- newIORef False+ let over = do+ first <- atomicModifyIORef' overRef $ \b -> (True, b)+ unless first $ atomically $ releaseHandshake d addrValid akey let reg = registerConnectionDict dstTable unreg cid = fire' (Microseconds 1000000) $ unregisterConnectionDict dstTable cid@@ -429,6 +521,7 @@ , accForget = deleteRecvQDict srcTable key q , accAddressValidated = addrValid , accTime = tim+ , accHandshakeOver = over } forkConnection acc -- Initial: DCID=S1, SCID=C1 ->
Network/QUIC/Server/Run.hs view
@@ -249,6 +249,7 @@ handshaker <- handshakeServer conf' conn myAuthCIDs srt let server = do wait1RTTReady conn+ accHandshakeOver acc afterHandshakeServer conf conn server0 conn mainDone conn@@ -319,6 +320,7 @@ done = do closeRecvQ $ accRecvQ acc accForget acc+ accHandshakeOver acc releaseConnection dispatch open = createServerConnection conf dispatch acc -- 'killReaders' stops this connection's own threads and sees them out,
Network/QUIC/Types/Constants.hs view
@@ -53,6 +53,10 @@ idleTimeout :: Milliseconds idleTimeout = Milliseconds 30000 +-- | How long a server gives a handshake, whatever the peer sends meanwhile.+handshakeTimeout :: Milliseconds+handshakeTimeout = Milliseconds 10000+ ---------------------------------------------------------------- -- | How much out-of-order CRYPTO data one encryption level will hold.@@ -79,3 +83,12 @@ -- far above anything real and still a bound. maxReassFragments :: Int maxReassFragments = 1024++----------------------------------------------------------------++-- | How many packets one encryption level keeps until its keys are there.+--+-- Reordering around a key change brings a few; a full initial congestion+-- window of 0-RTT is about a dozen.+maxPendingPackets :: Int+maxPendingPackets = 32
quic.cabal view
@@ -1,6 +1,6 @@ cabal-version: 2.0 name: quic-version: 0.3.25+version: 0.3.26 license: BSD3 license-file: LICENSE maintainer: kazu@iij.ad.jp@@ -137,7 +137,7 @@ crypton-x509-store >=1.9.0 && <1.11, crypton-x509-system >=1.9.0 && <1.11, crypton-x509-validation >=1.9.0 && <1.12,- fast-logger >=3.2.8 && <3.3,+ fast-logger >=3.2.8 && <3.4, filepath, iproute >=1.7.12 && <1.9, network >=3.2.12,@@ -266,7 +266,7 @@ crypto-token, crypton, directory,- fast-logger >=3.2.8 && <3.3,+ fast-logger >=3.2.8 && <3.4, filepath, hspec, network >=3.2.12,
test/HandshakeSpec.hs view
@@ -9,6 +9,8 @@ import Control.Monad import qualified Data.ByteString as BS import Data.IORef+import Data.Maybe (listToMaybe)+import Network.Control (newRate) import qualified Network.Socket as NS import qualified Network.Socket.ByteString as NSB import Network.TLS (Group (..), HandshakeMode13 (..))@@ -43,6 +45,30 @@ Timeout.timeout 5000000 (takeMVar var) >>= \r -> case r of Just () -> return () Nothing -> expectationFailure "server never became ready"+ describe "handshakes going on" $ do+ let v4 = addrKey $ NS.SockAddrInet 443 $ NS.tupleToHostAddress (192, 0, 2, 1)+ v6 a = addrKey $ NS.SockAddrInet6 443 0 (0x20010db8, 0, 0, a) 0+ admitted = fst+ it "counts an IPv6 /64 as one address" $+ v6 1 `shouldBe` v6 2+ it "counts an IPv4-mapped address as the IPv4 one" $+ addrKey (NS.SockAddrInet6 443 0 (0, 0, 0xffff, 0xc0000201) 0) `shouldBe` v4+ it "answers an address not validated with a Retry over either limit" $ do+ let (a1, hs1) = admitHandshakeWith 2 1 False v4 noHandshakes+ a1 `shouldBe` Admitted+ admitted (admitHandshakeWith 2 1 False v4 hs1) `shouldBe` NeedRetry+ let (_, hs2) = admitHandshakeWith 2 1 False (v6 1) hs1+ admitted (admitHandshakeWith 2 0 False (v6 9) hs2) `shouldBe` NeedRetry+ it "refuses a validated address over its own limit only" $ do+ let (_, hs1) = admitHandshakeWith 1 1 True v4 noHandshakes+ admitted (admitHandshakeWith 1 1 True v4 hs1) `shouldBe` Refused+ admitted (admitHandshakeWith 1 1 True (v6 1) hs1) `shouldBe` Admitted+ it "counts validated and not validated apart" $ do+ let (_, hs1) = admitHandshakeWith 0 1 False v4 noHandshakes+ admitted (admitHandshakeWith 0 1 True v4 hs1) `shouldBe` Admitted+ it "gives the place back" $ do+ let (_, hs1) = admitHandshakeWith 0 1 False v4 noHandshakes+ releaseHandshakeWith False v4 hs1 `shouldBe` noHandshakes describe "handshake" $ do it "can handshake in the normal case" $ do let cc = testClientConfig@@ -168,6 +194,10 @@ te == cryptoError TLS.HandshakeFailure | otherwise = False testHandshake3 cc1 cc2 sc waitS handshakeFailure+ it "sends CONNECTION_REFUSED no more than 100 a second" $ do+ rate <- newRate+ sent <- replicateM 150 $ withinRefusalLimit rate+ length (filter id sent) `shouldBe` 100 -- RFC 9000 Sec 5.2.2: a connection over the limit is refused with -- CONNECTION_REFUSED, and one ending makes room for another (#170). it "refuses a connection over scMaxConnections" $ do@@ -193,6 +223,70 @@ putMVar done () wait h again 10+ -- A handshake is held open by a client stalling in its certificate+ -- hook, while the server waits for its flight.+ describe "with handshakes held open" $ do+ let TLS.Credentials credentials = scCredentials sc0+ certClient stall =+ testClientConfig+ { ccTlsHooks =+ (ccTlsHooks testClientConfig)+ { TLS.onCertificateRequest = \_ -> stall >> pure (listToMaybe credentials)+ }+ }+ scCert =+ sc0+ { scWantClientCert = True+ , scTlsHooks =+ (scTlsHooks sc0)+ { TLS.onClientCertificate = const (pure TLS.CertificateUsageAccept)+ , TLS.onUnverifiedClientCert = pure True+ }+ }+ retried = C.run (certClient (return ())) $ \conn ->+ waitEstablished conn >> retry <$> getConnectionInfo conn+ -- Runs the body with n clients stalled in their handshakes.+ withStalled sc n body =+ E.bracket (forkIO $ S.run sc $ \_ -> threadDelay 5000000) killThread $ \_ -> do+ waitS+ release <- newEmptyMVar+ let go 0 = body+ go k = do+ started <- newEmptyMVar+ let stall = putMVar started () >> readMVar release+ withAsync (C.run (certClient stall) waitEstablished) $ \_ -> do+ takeMVar started+ go (k - 1 :: Int)+ go n `E.finally` putMVar release ()+ it "answers with a Retry over scMaxHandshakes" $ do+ let sc = scCert{scMaxHandshakes = 1, scMaxHandshakesPerAddress = 0}+ withStalled sc 1 $ retried `shouldReturn` True+ it "answers with a Retry over scMaxHandshakesPerAddress" $ do+ let sc = scCert{scMaxHandshakes = 0, scMaxHandshakesPerAddress = 1}+ withStalled sc 1 $ retried `shouldReturn` True+ it "refuses a validated address over scMaxHandshakesPerAddress" $ do+ let sc = scCert{scMaxHandshakes = 0, scMaxHandshakesPerAddress = 1}+ refused (TransportErrorIsReceived ConnectionRefused _) = True+ refused _ = False+ withStalled sc 2 $ retried `shouldThrow` refused+ -- The first connection stays open while the second is made.+ it "counts a handshake out once it is done" $ do+ let sc = sc0{scMaxHandshakes = 0, scMaxHandshakesPerAddress = 1}+ retried = C.run testClientConfig $ \conn ->+ waitEstablished conn >> retry <$> getConnectionInfo conn+ first <- newEmptyMVar+ done <- newEmptyMVar+ let holder = C.run testClientConfig $ \conn -> do+ waitEstablished conn+ putMVar first ()+ takeMVar done+ E.bracket (forkIO $ S.run sc $ \_ -> threadDelay 5000000) killThread $ \_ -> do+ waitS+ withAsync holder $ \h -> do+ takeMVar first+ retried `shouldReturn` False+ putMVar done ()+ wait h it "reconnects with the version a Version Negotiation offers" $ do let cc = testClientConfig{ccVersion = Version2, ccVersions = [Version2, Version1]} sc = sc0{scVersions = [Version1]}
test/PacketSpec.hs view
@@ -2,7 +2,10 @@ module PacketSpec where -import Control.Monad (forM_)+import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (withAsync)+import qualified Control.Exception as E+import Control.Monad (forM_, forever, replicateM, replicateM_) import Data.Bits (shiftR, xor, (.&.), (.|.)) import Data.ByteString (ByteString) import qualified Data.ByteString as BS@@ -10,6 +13,7 @@ import Data.IORef import Data.Tuple (swap) import Foreign.Ptr (plusPtr)+import qualified System.Timeout as Timeout import Test.Hspec import Control.Concurrent.STM@@ -62,6 +66,69 @@ (PacketIC (CryptPacket _ crypt) lvl _, _) <- decodePacket bin True mplain <- decryptCrypt serverConn crypt lvl plainPacketNumber <$> mplain `shouldBe` Just 300+ describe "packets waiting for their keys" $ do+ let withPacket = do+ (clientConn, serverConn) <- makeConnections serverConf Version1+ bin <- packetFrom clientConn (Initial Version1 clientChosenCID (toCID "") "") False+ (PacketIC cpkt lvl _, _) <- decodePacket bin True+ tim <- getTimeMicrosecond+ return (serverConn, mkReceivedPacket cpkt tim (BS.length bin) lvl)+ it "are kept up to maxPendingPackets" $ do+ (serverConn, rpkt) <- withPacket+ kept <- replicateM (maxPendingPackets + 8) $ putOffCrypto serverConn RTT1Level rpkt+ length (filter id kept) `shouldBe` maxPendingPackets+ -- Emptied, the queue takes as many again.+ it "are let go once their keys are there" $ do+ (serverConn, rpkt) <- withPacket+ replicateM_ maxPendingPackets $ putOffCrypto serverConn RTT1Level rpkt+ setEncryptionLevel serverConn RTT1Level+ putOffCrypto serverConn RTT1Level rpkt `shouldReturn` True+ -- RFC 9000 Sec 10.1: the idle timer restarts on a packet received and+ -- processed successfully.+ describe "the idle timer" $ do+ it "is restarted by the first ack-eliciting packet sent" $ do+ (_, serverConn) <- makeConnections serverConf Version1+ writeIORef (minIdleTimeout serverConn) 1000+ Just (Microseconds us) <- getIdleTimeout serverConn+ t0 <- getTimeMicrosecond+ let sendHalfway = do+ threadDelay (us `div` 2)+ atomically $ writeTVar (connAckElicitingSent serverConn) True+ r <- withAsync sendHalfway $ \_ ->+ Timeout.timeout (3 * us) (E.try (receiver serverConn) :: IO (Either QUICException ()))+ Microseconds spent <- getElapsedTimeMicrosecond t0+ either (const True) (const False) <$> r `shouldBe` Just True+ spent `shouldSatisfy` (>= us + us `div` 2)+ it "is not restarted by packets that do not decrypt" $ do+ (clientConn, serverConn) <- makeConnections serverConf Version1+ let hdr = Initial Version1 clientChosenCID (toCID "") ""+ bin <- packetFrom clientConn hdr True+ (PacketIC cpkt lvl _, _) <- decodePacket bin True+ -- Three times the PTO.+ writeIORef (minIdleTimeout serverConn) 1000+ Just (Microseconds us) <- getIdleTimeout serverConn+ let feed = forever $ do+ tim <- getTimeMicrosecond+ writeRecvQ (connRecvQ serverConn) $+ mkReceivedPacket cpkt tim (BS.length bin) lvl+ threadDelay 50000+ r <- withAsync feed $ \_ -> Timeout.timeout (2 * us) $ E.try (receiver serverConn)+ let timedOut (Just (Left (ConnectionIsTimeout _))) = True+ timedOut _ = False+ r `shouldSatisfy` timedOut+ describe "a server's handshake" $ do+ it "times out however long the idle timeout" $ do+ (_, serverConn) <- makeConnections serverConf Version1+ expired <- newTVarIO True+ r <- Timeout.timeout 1000000 $ E.try (receiverWith serverConn expired)+ let handshakeTimedOut (Just (Left (ConnectionIsTimeout "Server handshake"))) = True+ handshakeTimedOut _ = False+ r `shouldSatisfy` handshakeTimedOut+ it "does not time out once established" $ do+ (_, serverConn) <- makeConnections serverConf Version1+ setConnectionEstablished serverConn+ expired <- newTVarIO True+ Timeout.timeout 500000 (receiverWith serverConn expired) `shouldReturn` Nothing -- RFC 9000 Sec 12.3: a packet processed already is discarded. describe "a duplicated packet" $ do it "is processed once" $ do@@ -331,7 +398,7 @@ q dq (\_ _ -> return ())- (return undefined)+ (readRecvQSTM q) genSRT initializeCoder serverConn InitialLevel $ initialSecrets ver serverCID ----