{-# LANGUAGE RecordWildCards #-}

-- | A manager for TLS 1.2/1.3 session ticket.
--
--   For TLS 1.3 0-RTT, a ticket is accepted at most once while a replay
--   of its ClientHello could still be fresh.
--
--   A dedicated thread is running repeatedly to replece
--   secret keys. So, energy saving is not achieved.
module Network.TLS.SessionTicket (
    newSessionTicketManager,
    newSessionTicketManager',
    Config,
    defaultConfig,
    ticketLifetime,
    secretKeyInterval,
) where

import Codec.Serialise
import qualified Crypto.Token as CT
import qualified Data.ByteString.Lazy as L
import Data.IORef
import Data.Int (Int64)
import qualified Data.OrdPSQ as Q
import Network.TLS
import Network.TLS.Internal
import System.Clock

-- | Configuration for session tickets.
data Config = Config
    { Config -> Int
ticketLifetime :: Int
    -- ^ Ticket lifetime in seconds.  It should match the lifetime the
    -- server announces, 'serverTicketLifetime'.  As the secret keys are
    -- replaced every 'secretKeyInterval', a ticket is accepted for up to
    -- one interval less.
    , Config -> Int
secretKeyInterval :: Int
    -- ^ The interval to replace the secret key in seconds.
    }

-- | ticketLifetime: 2 hours (7200 seconds), secretKeyInterval: 30 minutes (1800 seconds)
defaultConfig :: Config
defaultConfig :: Config
defaultConfig =
    Config
        { ticketLifetime :: Int
ticketLifetime = Int
7200 -- 2 hours
        , secretKeyInterval :: Int
secretKeyInterval = Int
1800 -- 30 minutes
        }

-- | Creating a session ticket manager.
newSessionTicketManager :: Config -> IO SessionManager
newSessionTicketManager :: Config -> IO SessionManager
newSessionTicketManager Config{Int
ticketLifetime :: Config -> Int
secretKeyInterval :: Config -> Int
ticketLifetime :: Int
secretKeyInterval :: Int
..} =
    TokenManager -> Used -> SessionManager
sessionTicketManager (TokenManager -> Used -> SessionManager)
-> IO TokenManager -> IO (Used -> SessionManager)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Config -> IO TokenManager
CT.spawnTokenManager Config
conf IO (Used -> SessionManager) -> IO Used -> IO SessionManager
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> OrdPSQ ByteString Int64 () -> IO Used
forall a. a -> IO (IORef a)
newIORef OrdPSQ ByteString Int64 ()
forall k p v. OrdPSQ k p v
Q.empty
  where
    conf :: Config
conf =
        Config
CT.defaultConfig
            { CT.interval = secretKeyInterval
            , CT.tokenLifetime = ticketLifetime
            , CT.threadName = "TLS ticket manager"
            }

newSessionTicketManager' :: Config -> IO (SessionManager, IO ())
newSessionTicketManager' :: Config -> IO (SessionManager, IO ())
newSessionTicketManager' Config{Int
ticketLifetime :: Config -> Int
secretKeyInterval :: Config -> Int
ticketLifetime :: Int
secretKeyInterval :: Int
..} = do
    tokenmgr <- Config -> IO TokenManager
CT.spawnTokenManager Config
conf
    used <- newIORef Q.empty
    return (sessionTicketManager tokenmgr used, CT.killTokenManager tokenmgr)
  where
    conf :: Config
conf =
        Config
CT.defaultConfig
            { CT.interval = secretKeyInterval
            , CT.tokenLifetime = ticketLifetime
            , CT.threadName = "TLS ticket manager"
            }

-- | Tickets used for 0-RTT, with when they may be forgotten in
-- milliseconds of the wall clock.
type Used = IORef (Q.OrdPSQ Ticket Int64 ())

sessionTicketManager :: CT.TokenManager -> Used -> SessionManager
sessionTicketManager :: TokenManager -> Used -> SessionManager
sessionTicketManager TokenManager
ctmgr Used
used =
    SessionManager
noSessionManager
        { sessionResume = resume ctmgr
        , sessionResumeOnlyOnce = resumeOnlyOnce ctmgr used
        , sessionEstablish = establish ctmgr
        , sessionInvalidate = \ByteString
_ -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        , sessionUseTicket = True
        }

establish :: CT.TokenManager -> SessionID -> SessionData -> IO (Maybe Ticket)
establish :: TokenManager -> ByteString -> SessionData -> IO (Maybe ByteString)
establish TokenManager
ctmgr ByteString
_ SessionData
sd = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (ByteString -> Maybe ByteString)
-> IO ByteString -> IO (Maybe ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TokenManager -> ByteString -> IO ByteString
CT.encryptToken TokenManager
ctmgr ByteString
b
  where
    b :: ByteString
b = LazyByteString -> ByteString
L.toStrict (LazyByteString -> ByteString) -> LazyByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ SessionData -> LazyByteString
forall a. Serialise a => a -> LazyByteString
serialise SessionData
sd

resume :: CT.TokenManager -> Ticket -> IO (Maybe SessionData)
resume :: TokenManager -> ByteString -> IO (Maybe SessionData)
resume TokenManager
ctmgr ByteString
ticket
    | ByteString -> Bool
isTicket ByteString
ticket = do
        msdb <- TokenManager -> ByteString -> IO (Maybe ByteString)
CT.decryptToken TokenManager
ctmgr ByteString
ticket
        case msdb of
            Maybe ByteString
Nothing -> Maybe SessionData -> IO (Maybe SessionData)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe SessionData
forall a. Maybe a
Nothing
            Just ByteString
sdb -> case LazyByteString -> Either DeserialiseFailure SessionData
forall a.
Serialise a =>
LazyByteString -> Either DeserialiseFailure a
deserialiseOrFail (LazyByteString -> Either DeserialiseFailure SessionData)
-> LazyByteString -> Either DeserialiseFailure SessionData
forall a b. (a -> b) -> a -> b
$ ByteString -> LazyByteString
L.fromStrict ByteString
sdb of
                Left DeserialiseFailure
_ -> Maybe SessionData -> IO (Maybe SessionData)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe SessionData
forall a. Maybe a
Nothing
                Right SessionData
sd -> Maybe SessionData -> IO (Maybe SessionData)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe SessionData -> IO (Maybe SessionData))
-> Maybe SessionData -> IO (Maybe SessionData)
forall a b. (a -> b) -> a -> b
$ SessionData -> Maybe SessionData
forall a. a -> Maybe a
Just SessionData
sd
    | Bool
otherwise = Maybe SessionData -> IO (Maybe SessionData)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe SessionData
forall a. Maybe a
Nothing

-- A replay has the same age, so the same expected arrival time E, which is
-- within the tolerance of the first use.  The server accepts it only within
-- the tolerance of E, so the ticket is remembered for twice the tolerance.
resumeOnlyOnce :: CT.TokenManager -> Used -> Ticket -> IO (Maybe SessionData)
resumeOnlyOnce :: TokenManager -> Used -> ByteString -> IO (Maybe SessionData)
resumeOnlyOnce TokenManager
ctmgr Used
used ByteString
ticket = do
    msd <- TokenManager -> ByteString -> IO (Maybe SessionData)
resume TokenManager
ctmgr ByteString
ticket
    case msd of
        Maybe SessionData
Nothing -> Maybe SessionData -> IO (Maybe SessionData)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe SessionData
forall a. Maybe a
Nothing
        Just SessionData
sd -> do
            now <- IO Int64
milliseconds
            -- Capped at 10 seconds as in the server, before it can wrap
            -- around as an Int64.
            let rtt = Int64 -> (Millisecond -> Int64) -> Maybe Millisecond -> Int64
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int64
0 (Millisecond -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Millisecond -> Int64)
-> (Millisecond -> Millisecond) -> Millisecond -> Int64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Millisecond -> Millisecond -> Millisecond
forall a. Ord a => a -> a -> a
min Millisecond
10000) (Maybe Millisecond -> Int64) -> Maybe Millisecond -> Int64
forall a b. (a -> b) -> a -> b
$ SessionData -> Maybe TLS13TicketInfo
sessionTicketInfo SessionData
sd Maybe TLS13TicketInfo
-> (TLS13TicketInfo -> Maybe Millisecond) -> Maybe Millisecond
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= TLS13TicketInfo -> Maybe Millisecond
estimatedRTT
                -- 'max 2000 rtt' as in the server, and a second of margin
                forget = Int64
now Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
+ Int64
2 Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
* Int64 -> Int64 -> Int64
forall a. Ord a => a -> a -> a
max Int64
2000 Int64
rtt Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
+ Int64
1000
            first <- atomicModifyIORef' used $ \OrdPSQ ByteString Int64 ()
q ->
                let q' :: OrdPSQ ByteString Int64 ()
q' = ([(ByteString, Int64, ())], OrdPSQ ByteString Int64 ())
-> OrdPSQ ByteString Int64 ()
forall a b. (a, b) -> b
snd (([(ByteString, Int64, ())], OrdPSQ ByteString Int64 ())
 -> OrdPSQ ByteString Int64 ())
-> ([(ByteString, Int64, ())], OrdPSQ ByteString Int64 ())
-> OrdPSQ ByteString Int64 ()
forall a b. (a -> b) -> a -> b
$ Int64
-> OrdPSQ ByteString Int64 ()
-> ([(ByteString, Int64, ())], OrdPSQ ByteString Int64 ())
forall k p v.
(Ord k, Ord p) =>
p -> OrdPSQ k p v -> ([(k, p, v)], OrdPSQ k p v)
Q.atMostView Int64
now OrdPSQ ByteString Int64 ()
q
                 in case ByteString -> OrdPSQ ByteString Int64 () -> Maybe (Int64, ())
forall k p v. Ord k => k -> OrdPSQ k p v -> Maybe (p, v)
Q.lookup ByteString
ticket OrdPSQ ByteString Int64 ()
q' of
                        Just (Int64, ())
_ -> (OrdPSQ ByteString Int64 ()
q', Bool
False)
                        Maybe (Int64, ())
Nothing -> (ByteString
-> Int64
-> ()
-> OrdPSQ ByteString Int64 ()
-> OrdPSQ ByteString Int64 ()
forall k p v.
(Ord k, Ord p) =>
k -> p -> v -> OrdPSQ k p v -> OrdPSQ k p v
Q.insert ByteString
ticket Int64
forget () OrdPSQ ByteString Int64 ()
q', Bool
True)
            return $ if first then Just sd else Nothing

-- The wall clock, as the server checks freshness with it.  If it goes
-- back, the ticket is remembered longer, just as a replay stays fresh.
milliseconds :: IO Int64
milliseconds :: IO Int64
milliseconds = do
    TimeSpec s ns <- Clock -> IO TimeSpec
getTime Clock
Realtime
    return $ s * 1000 + ns `div` 1000000