{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Network.TLS.Handshake.Server.ClientHello13 (
    processClientHello13,
    SelectKeyShareResult (..),
) where

import qualified Data.ByteString as B

import Network.TLS.Cipher
import Network.TLS.Context.Internal
import Network.TLS.Crypto
import Network.TLS.Extension
import Network.TLS.Handshake.Common (restoreClientCertificate)
import Network.TLS.Handshake.Common13
import Network.TLS.Handshake.Server.Common
import Network.TLS.Handshake.Signature
import Network.TLS.Handshake.State
import Network.TLS.IO.Encode
import Network.TLS.Imports
import Network.TLS.Parameters
import Network.TLS.Session
import Network.TLS.State
import Network.TLS.Struct
import Network.TLS.Types

limitSupportedGroups :: Int
limitSupportedGroups :: Int
limitSupportedGroups = Int
64

-- TLS 1.3 or later
processClientHello13
    :: ServerParams
    -> Context
    -> ClientHello
    -> IO
        ( SelectKeyShareResult
        , (Cipher, Hash, Bool) -- rtt0
        , (SecretPair EarlySecret, [ExtensionRaw], Bool, Bool, Maybe ByteString)
          -- authenticated, is0RTTvalid, ticket ALPN
        )
processClientHello13 :: ServerParams
-> Context
-> ClientHello
-> IO
     (SelectKeyShareResult, (Cipher, Hash, Bool),
      (SecretPair EarlySecret, [ExtensionRaw], Bool, Bool,
       Maybe ByteString))
processClientHello13 ServerParams
sparams Context
ctx ch :: ClientHello
ch@CH{[CompressionID]
[CipherId]
[ExtensionRaw]
Version
ClientRandom
Session
chVersion :: Version
chRandom :: ClientRandom
chSession :: Session
chCiphers :: [CipherId]
chComps :: [CompressionID]
chExtensions :: [ExtensionRaw]
chCiphers :: ClientHello -> [CipherId]
chComps :: ClientHello -> [CompressionID]
chExtensions :: ClientHello -> [ExtensionRaw]
chRandom :: ClientHello -> ClientRandom
chSession :: ClientHello -> Session
chVersion :: ClientHello -> Version
..} = do
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when
        ((ExtensionRaw -> Bool) -> [ExtensionRaw] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(ExtensionRaw ExtensionID
eid ByteString
_) -> ExtensionID
eid ExtensionID -> ExtensionID -> Bool
forall a. Eq a => a -> a -> Bool
== ExtensionID
EID_PreSharedKey) ([ExtensionRaw] -> Bool) -> [ExtensionRaw] -> Bool
forall a b. (a -> b) -> a -> b
$ [ExtensionRaw] -> [ExtensionRaw]
forall a. HasCallStack => [a] -> [a]
init [ExtensionRaw]
chExtensions)
        (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ TLSError -> IO ()
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore
        (TLSError -> IO ()) -> TLSError -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> AlertDescription -> TLSError
Error_Protocol String
"extension pre_shared_key must be last" AlertDescription
IllegalParameter
    -- RFC 9846 Section 9.2: the extensions a TLS 1.3 ClientHello must have.
    let has :: ExtensionID -> Bool
has ExtensionID
eid = Maybe ByteString -> Bool
forall a. Maybe a -> Bool
isJust (Maybe ByteString -> Bool) -> Maybe ByteString -> Bool
forall a b. (a -> b) -> a -> b
$ ExtensionID -> [ExtensionRaw] -> Maybe ByteString
extensionLookup ExtensionID
eid [ExtensionRaw]
chExtensions
        missing :: String -> m a
missing String
reason = TLSError -> m a
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> m a) -> TLSError -> m a
forall a b. (a -> b) -> a -> b
$ String -> AlertDescription -> TLSError
Error_Protocol String
reason AlertDescription
MissingExtension
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ExtensionID -> Bool
has ExtensionID
EID_PreSharedKey) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
        Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ExtensionID -> Bool
has ExtensionID
EID_SignatureAlgorithms) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
            String -> IO ()
forall {m :: * -> *} {a}. MonadIO m => String -> m a
missing String
"no signature_algorithms extension without pre_shared_key"
        Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ExtensionID -> Bool
has ExtensionID
EID_SupportedGroups) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
            String -> IO ()
forall {m :: * -> *} {a}. MonadIO m => String -> m a
missing String
"no supported_groups extension without pre_shared_key"
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ExtensionID -> Bool
has ExtensionID
EID_SupportedGroups Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= ExtensionID -> Bool
has ExtensionID
EID_KeyShare) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        String -> IO ()
forall {m :: * -> *} {a}. MonadIO m => String -> m a
missing String
"supported_groups and key_share must come together"
    -- Deciding cipher.
    -- The shared cipherlist can become empty after filtering for compatible
    -- creds, check now before calling onCipherChoosing, which does not handle
    -- empty lists.
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([Cipher] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Cipher]
ciphersFilteredVersion) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        TLSError -> IO ()
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> IO ()) -> TLSError -> IO ()
forall a b. (a -> b) -> a -> b
$
            String -> AlertDescription -> TLSError
Error_Protocol String
"no cipher in common with the TLS 1.3 client" AlertDescription
HandshakeFailure
    usedCipher <- ServerParams -> Version -> [CipherId] -> [Cipher] -> IO Cipher
chooseCipher ServerParams
sparams Version
TLS13 [CipherId]
chCiphers [Cipher]
ciphersFilteredVersion
    let usedHash = Cipher -> Hash
cipherHash Cipher
usedCipher
        rtt0 =
            ExtensionID
-> MessageType
-> [ExtensionRaw]
-> Bool
-> (EarlyDataIndication -> Bool)
-> Bool
forall e a.
Extension e =>
ExtensionID -> MessageType -> [ExtensionRaw] -> a -> (e -> a) -> a
lookupAndDecode
                ExtensionID
EID_EarlyData
                MessageType
MsgTClientHello
                [ExtensionRaw]
chExtensions
                Bool
False
                (\(EarlyDataIndication Maybe Word32
_) -> Bool
True)
    if rtt0
        then
            -- Skip up to this many bytes of rejected early data: a record's worth
            -- at least, even if early data is not accepted (0 by default), and
            -- more only if the server accepts more.  Updated if 0-RTT succeeds.
            setEstablished
                ctx
                (EarlyDataNotAllowed (max 16384 (serverEarlyDataSize sparams)))
        else
            -- In the case of HRR, EarlyDataNotAllowed is already set.
            -- It should be cleared here.
            setEstablished ctx NotEstablished
    -- Deciding key exchange from key shares
    let require =
            TLSError -> IO a
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> IO a) -> TLSError -> IO a
forall a b. (a -> b) -> a -> b
$
                String -> AlertDescription -> TLSError
Error_Protocol
                    String
"key exchange not implemented, expected key_share extension"
                    AlertDescription
MissingExtension
        extract (KeyShareClientHello [KeyShareEntry]
kses) = [KeyShareEntry] -> IO [KeyShareEntry]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [KeyShareEntry]
kses
        extract KeyShare
_ = IO [KeyShareEntry]
forall {a}. IO a
require
    keyShares <-
        lookupAndDecodeAndDo EID_KeyShare MsgTClientHello chExtensions require extract
    let allClientGroups =
            ExtensionID
-> MessageType
-> [ExtensionRaw]
-> [Group]
-> (SupportedGroups -> [Group])
-> [Group]
forall e a.
Extension e =>
ExtensionID -> MessageType -> [ExtensionRaw] -> a -> (e -> a) -> a
lookupAndDecode
                ExtensionID
EID_SupportedGroups
                MessageType
MsgTClientHello
                [ExtensionRaw]
chExtensions
                []
                (\(SupportedGroups [Group]
gs) -> [Group]
gs)
        clientGroups = Int -> [Group] -> [Group]
forall a. Int -> [a] -> [a]
take Int
limitSupportedGroups [Group]
allClientGroups
    -- RFC 9846 Section 4.2.8: after HelloRetryRequest, only the selected
    -- group is offered.
    hrr <- usingState_ ctx getTLS13HRR
    when hrr $ do
        mg <- usingHState ctx getSupportedGroup
        unless (map (Just . keyShareEntryGroup) keyShares == [mg]) $
            throwCore $
                Error_Protocol "key_share not for the group of hello retry" IllegalParameter
    -- RFC 9846 Section 4.2.8: servers MAY check this.
    unless (all ((`elem` allClientGroups) . keyShareEntryGroup) keyShares) $
        throwCore $
            Error_Protocol "key_share for a group not in supported_groups" IllegalParameter
    (mgroup, doHRR) <-
        onSelectKeyShare
            (serverHooks sparams)
            serverGroups
            clientGroups
            $ map keyShareEntryGroup keyShares
    keyshareResult <- case mgroup of
        Maybe Group
Nothing -> SelectKeyShareResult -> IO SelectKeyShareResult
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return SelectKeyShareResult
SelectKeyShareNotFound
        Just Group
g
            | Bool
doHRR -> SelectKeyShareResult -> IO SelectKeyShareResult
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (SelectKeyShareResult -> IO SelectKeyShareResult)
-> SelectKeyShareResult -> IO SelectKeyShareResult
forall a b. (a -> b) -> a -> b
$ Group -> SelectKeyShareResult
SelectKeyShareHRR Group
g
            | Bool
otherwise -> case (KeyShareEntry -> Bool) -> [KeyShareEntry] -> [KeyShareEntry]
forall a. (a -> Bool) -> [a] -> [a]
filter (\KeyShareEntry
e -> KeyShareEntry -> Group
keyShareEntryGroup KeyShareEntry
e Group -> Group -> Bool
forall a. Eq a => a -> a -> Bool
== Group
g) [KeyShareEntry]
keyShares of
                [] -> SelectKeyShareResult -> IO SelectKeyShareResult
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return SelectKeyShareResult
SelectKeyShareNotFound
                [KeyShareEntry
x] -> SelectKeyShareResult -> IO SelectKeyShareResult
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (SelectKeyShareResult -> IO SelectKeyShareResult)
-> SelectKeyShareResult -> IO SelectKeyShareResult
forall a b. (a -> b) -> a -> b
$ KeyShareEntry -> SelectKeyShareResult
SelectKeyShareFound KeyShareEntry
x
                [KeyShareEntry]
_ -> TLSError -> IO SelectKeyShareResult
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> IO SelectKeyShareResult)
-> TLSError -> IO SelectKeyShareResult
forall a b. (a -> b) -> a -> b
$ String -> AlertDescription -> TLSError
Error_Protocol String
"duplicated key_share" AlertDescription
IllegalParameter

    let triple = (Cipher
usedCipher, Hash
usedHash, Bool
rtt0)
    pskEarlySecret <- pskAndEarlySecret sparams ctx triple ch
    (ich, b) <- fromJust <$> usingHState ctx getClientHello
    updateTranscriptHash12 ctx (ClientHello ich, b)
    return (keyshareResult, triple, pskEarlySecret)
  where
    ciphersFilteredVersion :: [Cipher]
ciphersFilteredVersion = [CipherId] -> [Cipher] -> [Cipher]
intersectCiphers [CipherId]
chCiphers [Cipher]
serverCiphers
    serverCiphers :: [Cipher]
serverCiphers =
        (Cipher -> Bool) -> [Cipher] -> [Cipher]
forall a. (a -> Bool) -> [a] -> [a]
filter
            (Version -> Cipher -> Bool
cipherAllowedForVersion Version
TLS13)
            (Supported -> [Cipher]
supportedCiphers (Supported -> [Cipher]) -> Supported -> [Cipher]
forall a b. (a -> b) -> a -> b
$ ServerParams -> Supported
serverSupported ServerParams
sparams)
    serverGroups :: [[Group]]
serverGroups = Supported -> [[Group]]
supportedGroupsTLS13 (Supported -> [[Group]]) -> Supported -> [[Group]]
forall a b. (a -> b) -> a -> b
$ ServerParams -> Supported
serverSupported ServerParams
sparams

data SelectKeyShareResult
    = -- | Negotiation failure
      SelectKeyShareNotFound
    | -- | Send a hello retry request with this group
      SelectKeyShareHRR Group
    | -- | Use this key share
      SelectKeyShareFound KeyShareEntry
    deriving (SelectKeyShareResult -> SelectKeyShareResult -> Bool
(SelectKeyShareResult -> SelectKeyShareResult -> Bool)
-> (SelectKeyShareResult -> SelectKeyShareResult -> Bool)
-> Eq SelectKeyShareResult
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SelectKeyShareResult -> SelectKeyShareResult -> Bool
== :: SelectKeyShareResult -> SelectKeyShareResult -> Bool
$c/= :: SelectKeyShareResult -> SelectKeyShareResult -> Bool
/= :: SelectKeyShareResult -> SelectKeyShareResult -> Bool
Eq, Int -> SelectKeyShareResult -> ShowS
[SelectKeyShareResult] -> ShowS
SelectKeyShareResult -> String
(Int -> SelectKeyShareResult -> ShowS)
-> (SelectKeyShareResult -> String)
-> ([SelectKeyShareResult] -> ShowS)
-> Show SelectKeyShareResult
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SelectKeyShareResult -> ShowS
showsPrec :: Int -> SelectKeyShareResult -> ShowS
$cshow :: SelectKeyShareResult -> String
show :: SelectKeyShareResult -> String
$cshowList :: [SelectKeyShareResult] -> ShowS
showList :: [SelectKeyShareResult] -> ShowS
Show)

pskAndEarlySecret
    :: ServerParams
    -> Context
    -> (Cipher, Hash, Bool) -- rtt0
    -> ClientHello
    -> IO (SecretPair EarlySecret, [ExtensionRaw], Bool, Bool, Maybe ByteString)
    -- authenticated, is0RTTvalid, ticket ALPN
pskAndEarlySecret :: ServerParams
-> Context
-> (Cipher, Hash, Bool)
-> ClientHello
-> IO
     (SecretPair EarlySecret, [ExtensionRaw], Bool, Bool,
      Maybe ByteString)
pskAndEarlySecret ServerParams
sparams Context
ctx (Cipher
usedCipher, Hash
usedHash, Bool
rtt0) CH{[CompressionID]
[CipherId]
[ExtensionRaw]
Version
ClientRandom
Session
chCiphers :: ClientHello -> [CipherId]
chComps :: ClientHello -> [CompressionID]
chExtensions :: ClientHello -> [ExtensionRaw]
chRandom :: ClientHello -> ClientRandom
chSession :: ClientHello -> Session
chVersion :: ClientHello -> Version
chVersion :: Version
chRandom :: ClientRandom
chSession :: Session
chCiphers :: [CipherId]
chComps :: [CompressionID]
chExtensions :: [ExtensionRaw]
..} = do
    (psk, binderInfo, is0RTTvalid, ticketALPN) <- IO
  (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
choosePSK
    earlyKey <- calculateEarlySecret ctx choice (Left psk)
    let earlySecret = SecretPair EarlySecret -> BaseSecret EarlySecret
forall a. SecretPair a -> BaseSecret a
pairBase SecretPair EarlySecret
earlyKey
        authenticated = Maybe (ByteString, Int, Int) -> Bool
forall a. Maybe a -> Bool
isJust Maybe (ByteString, Int, Int)
binderInfo
    preSharedKeyExt <- checkBinder earlySecret binderInfo
    return (earlyKey, preSharedKeyExt, authenticated, is0RTTvalid, ticketALPN)
  where
    choice :: CipherChoice
choice = Version -> Cipher -> CipherChoice
makeCipherChoice Version
TLS13 Cipher
usedCipher

    choosePSK :: IO
  (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
choosePSK =
        ExtensionID
-> MessageType
-> [ExtensionRaw]
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
-> (PreSharedKey
    -> IO
         (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString))
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
forall a b.
Extension a =>
ExtensionID
-> MessageType -> [ExtensionRaw] -> IO b -> (a -> IO b) -> IO b
lookupAndDecodeAndDo
            ExtensionID
EID_PreSharedKey
            MessageType
MsgTClientHello
            [ExtensionRaw]
chExtensions
            ((ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString
zero, Maybe (ByteString, Int, Int)
forall a. Maybe a
Nothing, Bool
False, Maybe ByteString
forall a. Maybe a
Nothing))
            PreSharedKey
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
selectPSK

    selectPSK :: PreSharedKey
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
selectPSK (PreSharedKeyClientHello [PskIdentity]
ids [ByteString]
bnds) = do
        Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([PskKexMode] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PskKexMode]
dhModes) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
            TLSError -> IO ()
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> IO ()) -> TLSError -> IO ()
forall a b. (a -> b) -> a -> b
$
                String -> AlertDescription -> TLSError
Error_Protocol String
"no psk_key_exchange_modes extension" AlertDescription
MissingExtension
        if PskKexMode
PSK_DHE_KE PskKexMode -> [PskKexMode] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [PskKexMode]
dhModes
            then do
                let len :: Int
len = [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((ByteString -> Int) -> [ByteString] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (\ByteString
x -> ByteString -> Int
B.length ByteString
x Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [ByteString]
bnds) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2
                -- The first identity that can be resumed is chosen, each
                -- with its own age and binder.
                Int
-> [(Int, PskIdentity, ByteString)]
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
forall {t} {a}.
t
-> [(Int, PskIdentity, a)]
-> IO (ByteString, Maybe (a, Int, t), Bool, Maybe ByteString)
tryPSK Int
len ([(Int, PskIdentity, ByteString)]
 -> IO
      (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString))
-> [(Int, PskIdentity, ByteString)]
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
forall a b. (a -> b) -> a -> b
$ [Int]
-> [PskIdentity]
-> [ByteString]
-> [(Int, PskIdentity, ByteString)]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 [Int
0 ..] [PskIdentity]
ids [ByteString]
bnds
            else (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString
zero, Maybe (ByteString, Int, Int)
forall a. Maybe a
Nothing, Bool
False, Maybe ByteString
forall a. Maybe a
Nothing)
    selectPSK PreSharedKey
_ = (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
-> IO
     (ByteString, Maybe (ByteString, Int, Int), Bool, Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString
zero, Maybe (ByteString, Int, Int)
forall a. Maybe a
Nothing, Bool
False, Maybe ByteString
forall a. Maybe a
Nothing)

    tryPSK :: t
-> [(Int, PskIdentity, a)]
-> IO (ByteString, Maybe (a, Int, t), Bool, Maybe ByteString)
tryPSK t
_ [] = (ByteString, Maybe (a, Int, t), Bool, Maybe ByteString)
-> IO (ByteString, Maybe (a, Int, t), Bool, Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString
zero, Maybe (a, Int, t)
forall a. Maybe a
Nothing, Bool
False, Maybe ByteString
forall a. Maybe a
Nothing)
    tryPSK t
len ((Int
n, PskIdentity ByteString
identity Word32
obfAge, a
bnd) : [(Int, PskIdentity, a)]
rest) = do
        let mgr :: SessionManager
mgr = Shared -> SessionManager
sharedSessionManager (Shared -> SessionManager) -> Shared -> SessionManager
forall a b. (a -> b) -> a -> b
$ ServerParams -> Shared
serverShared ServerParams
sparams
        -- sessionInvalidate is not used for TLS 1.3
        -- because PSK is always changed.
        -- So, identity is not stored in Context.
        -- Early data is only with the first identity.
        msdata <-
            if Bool
rtt0 Bool -> Bool -> Bool
&& Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0
                then SessionManager -> ByteString -> IO (Maybe SessionData)
sessionResumeOnlyOnce SessionManager
mgr ByteString
identity
                else SessionManager -> ByteString -> IO (Maybe SessionData)
sessionResume SessionManager
mgr ByteString
identity
        case msdata of
            -- RFC 8446 Section 4.6.1: only a TLS 1.3 session, which
            -- has its ticket information, is resumed with a PSK.  A
            -- TLS 1.2 one found under the same identity falls back
            -- to a full handshake.
            Just SessionData
sdata
                | SessionData -> Version
sessionVersion SessionData
sdata Version -> Version -> Bool
forall a. Eq a => a -> a -> Bool
== Version
TLS13
                , Just TLS13TicketInfo
tinfo <- SessionData -> Maybe TLS13TicketInfo
sessionTicketInfo SessionData
sdata -> do
                    let psk :: ByteString
psk = SessionData -> ByteString
sessionSecret SessionData
sdata
                    isFresh <- TLS13TicketInfo -> Word32 -> IO Bool
checkFreshness TLS13TicketInfo
tinfo Word32
obfAge
                    (isPSKvalid, is0RTTvalid) <- checkSessionEquality sdata
                    if isPSKvalid && isFresh
                        then do
                            restoreClientCertificate ctx sdata
                            -- The application is asked only when 0-RTT is
                            -- otherwise possible.
                            accepted <-
                                if rtt0 && is0RTTvalid && n == 0
                                    then onAccept0RTT (serverHooks sparams) sdata
                                    else return False
                            return
                                ( psk
                                , Just (bnd, n :: Int, len)
                                , accepted
                                , sessionALPN sdata
                                )
                        else tryPSK len rest
            Maybe SessionData
_ -> t
-> [(Int, PskIdentity, a)]
-> IO (ByteString, Maybe (a, Int, t), Bool, Maybe ByteString)
tryPSK t
len [(Int, PskIdentity, a)]
rest

    checkBinder :: BaseSecret EarlySecret
-> Maybe (ByteString, a, Int) -> IO [ExtensionRaw]
checkBinder BaseSecret EarlySecret
_ Maybe (ByteString, a, Int)
Nothing = [ExtensionRaw] -> IO [ExtensionRaw]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
    checkBinder BaseSecret EarlySecret
earlySecret (Just (ByteString
binder, a
n, Int
tlen)) = do
        (_, b) <- Maybe (ClientHello, [ByteString]) -> (ClientHello, [ByteString])
forall a. HasCallStack => Maybe a -> a
fromJust (Maybe (ClientHello, [ByteString]) -> (ClientHello, [ByteString]))
-> IO (Maybe (ClientHello, [ByteString]))
-> IO (ClientHello, [ByteString])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Context
-> HandshakeM (Maybe (ClientHello, [ByteString]))
-> IO (Maybe (ClientHello, [ByteString]))
forall (m :: * -> *) a. MonadIO m => Context -> HandshakeM a -> m a
usingHState Context
ctx HandshakeM (Maybe (ClientHello, [ByteString]))
getClientHello
        binder' <- makePSKBinder ctx earlySecret usedHash tlen $ B.concat b
        unless (binder == binder') $
            decryptError "PSK binder validation failed"
        return [toExtensionRaw $ PreSharedKeyServerHello $ fromIntegral n]

    checkSessionEquality :: SessionData -> IO (Bool, Bool)
checkSessionEquality SessionData
sdata = do
        msni <- Context -> TLSSt (Maybe String) -> IO (Maybe String)
forall a. Context -> TLSSt a -> IO a
usingState_ Context
ctx TLSSt (Maybe String)
getClientSNI
        let isSameSNI = SessionData -> Maybe String
sessionClientSNI SessionData
sdata Maybe String -> Maybe String -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe String
msni
            isSameCipher = SessionData -> Word16
sessionCipher SessionData
sdata Word16 -> Word16 -> Bool
forall a. Eq a => a -> a -> Bool
== Cipher -> Word16
cipherID Cipher
usedCipher
            ciphers = Supported -> [Cipher]
supportedCiphers (Supported -> [Cipher]) -> Supported -> [Cipher]
forall a b. (a -> b) -> a -> b
$ ServerParams -> Supported
serverSupported ServerParams
sparams
            scid = SessionData -> Word16
sessionCipher SessionData
sdata
            isSameKDF = case Word16 -> [Cipher] -> Maybe Cipher
findCipher Word16
scid [Cipher]
ciphers of
                Maybe Cipher
Nothing -> Bool
False
                Just Cipher
c -> Cipher -> Hash
cipherHash Cipher
c Hash -> Hash -> Bool
forall a. Eq a => a -> a -> Bool
== Cipher -> Hash
cipherHash Cipher
usedCipher
            isSameVersion = Version
TLS13 Version -> Version -> Bool
forall a. Eq a => a -> a -> Bool
== SessionData -> Version
sessionVersion SessionData
sdata
            -- RFC 9846 does not require the same SNI, but a session of
            -- another name may have other credentials and settings.
            isPSKvalid = Bool
isSameKDF Bool -> Bool -> Bool
&& Bool
isSameSNI
            is0RTTvalid = Bool
isSameVersion Bool -> Bool -> Bool
&& Bool
isSameCipher
        return (isPSKvalid, is0RTTvalid)

    dhModes :: [PskKexMode]
dhModes =
        ExtensionID
-> MessageType
-> [ExtensionRaw]
-> [PskKexMode]
-> (PskKeyExchangeModes -> [PskKexMode])
-> [PskKexMode]
forall e a.
Extension e =>
ExtensionID -> MessageType -> [ExtensionRaw] -> a -> (e -> a) -> a
lookupAndDecode
            ExtensionID
EID_PskKeyExchangeModes
            MessageType
MsgTClientHello
            [ExtensionRaw]
chExtensions
            []
            (\(PskKeyExchangeModes [PskKexMode]
ms) -> [PskKexMode]
ms)

    hashSize :: Int
hashSize = Hash -> Int
hashDigestSize Hash
usedHash
    zero :: ByteString
zero = Int -> CompressionID -> ByteString
B.replicate Int
hashSize CompressionID
0