tls-session-manager-0.0.8/0000755000000000000000000000000007346545000013603 5ustar0000000000000000tls-session-manager-0.0.8/ChangeLog.md0000644000000000000000000000100107346545000015744 0ustar0000000000000000# ChangeLog for tls-session-manager ## 0.0.8 * Removing "basement". ## 0.0.7 * Naming threads. ## 0.0.6 * Preparing for tls v2.1. ## 0.0.5 * Supporting "tls" v2.0.0. ## 0.0.4 * Supporting "tls" v1.5.3. ## 0.0.3 * Adding Strict and StrictData pragma ## 0.0.2.1 * Supporting "tls" v1.5.0. ## 0.0.2.0 * Using ShortByteString internally to avoid ByteString's fragmentation. * The default value of dbMaxSize is now 1,000. ## 0.0.1.0 * Supporting sessionResumeOnlyOnce. ## 0.0.0.0 * A first release. tls-session-manager-0.0.8/LICENSE0000644000000000000000000000276507346545000014622 0ustar0000000000000000Copyright (c) 2017, IIJ Innovation Institute Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. tls-session-manager-0.0.8/Network/TLS/0000755000000000000000000000000007346545000015676 5ustar0000000000000000tls-session-manager-0.0.8/Network/TLS/Imports.hs0000644000000000000000000000052707346545000017673 0ustar0000000000000000module Network.TLS.Imports ( module Control.Applicative, module Control.Monad, module Data.Int, module Data.List, module Data.Maybe, module Data.Monoid, module Data.Word, ) where import Control.Applicative import Control.Monad import Data.Int import Data.List import Data.Maybe import Data.Monoid import Data.Word tls-session-manager-0.0.8/Network/TLS/SessionManager.hs0000644000000000000000000001265507346545000021161 0ustar0000000000000000-- | In-memory TLS 1.2/1.3 session manager. -- -- * Limitation: you can set the maximum size of the session data database. -- * Automatic pruning: old session data over their lifetime are pruned automatically. -- * Energy saving: no dedicate pruning thread is running when the size of session data database is zero. -- * Replay resistance: each session data is used at most once to prevent replay attacks against 0RTT early data of TLS 1.3. module Network.TLS.SessionManager ( newSessionManager, Config, defaultConfig, ticketLifetime, pruningDelay, dbMaxSize, ) where import Control.Exception (assert) import Control.Reaper import Data.ByteArray (convert) import Data.ByteString (ByteString) import Data.ByteString.Short (ShortByteString) import qualified Data.ByteString.Short as SBS import Data.IORef import Data.OrdPSQ (OrdPSQ) import qualified Data.OrdPSQ as Q import Network.TLS import qualified System.Clock as C import Network.TLS.Imports ---------------------------------------------------------------- -- | Configuration for session managers. data Config = Config { ticketLifetime :: Int -- ^ Ticket lifetime in seconds. , pruningDelay :: Int -- ^ Pruning delay in seconds. This is set to 'reaperDelay'. , dbMaxSize :: Int -- ^ The limit size of session data entries. } -- | ticketLifetime: 2 hours (7200 seconds), pruningDelay: 10 minutes (600 seconds), dbMaxSize: 1000 entries. defaultConfig :: Config defaultConfig = Config { ticketLifetime = 7200 , pruningDelay = 600 , dbMaxSize = 1000 } ---------------------------------------------------------------- toKey :: ByteString -> SessionIDCopy toKey = SBS.toShort toValue :: SessionData -> SessionDataCopy toValue sd = SessionDataCopy $ sd { sessionSecret = convert $ sessionSecret sd , sessionALPN = convert <$> sessionALPN sd } fromValue :: SessionDataCopy -> SessionData fromValue (SessionDataCopy sd) = sd { sessionSecret = convert $ sessionSecret sd , sessionALPN = convert <$> sessionALPN sd } ---------------------------------------------------------------- type SessionIDCopy = ShortByteString newtype SessionDataCopy = SessionDataCopy SessionData deriving (Show, Eq) type Sec = Int64 type Value = (SessionDataCopy, IORef Availability) type DB = OrdPSQ SessionIDCopy Sec Value type Item = (SessionIDCopy, Sec, Value, Operation) data Operation = Add | Del data Use = SingleUse | MultipleUse data Availability = Fresh | Used ---------------------------------------------------------------- -- | Creating an in-memory session manager. newSessionManager :: Config -> IO SessionManager newSessionManager conf = do let lifetime = fromIntegral $ ticketLifetime conf maxsiz = dbMaxSize conf reaper <- mkReaper defaultReaperSettings { reaperEmpty = Q.empty , reaperCons = cons maxsiz , reaperAction = clean , reaperNull = Q.null , reaperDelay = pruningDelay conf * 1000000 , reaperThreadName = "TLS session manager" } return $ noSessionManager { sessionResume = resume reaper MultipleUse , sessionResumeOnlyOnce = resume reaper SingleUse , sessionEstablish = \x y -> establish reaper lifetime x y >> return Nothing , sessionInvalidate = invalidate reaper , sessionUseTicket = False } cons :: Int -> Item -> DB -> DB cons lim (k, t, v, Add) db | lim <= 0 = Q.empty | Q.size db == lim = case Q.minView db of Nothing -> assert False $ Q.insert k t v Q.empty Just (_, _, _, db') -> Q.insert k t v db' | otherwise = Q.insert k t v db cons _ (k, _, _, Del) db = Q.delete k db clean :: DB -> IO (DB -> DB) clean olddb = do currentTime <- C.sec <$> C.getTime C.Monotonic let pruned = snd $ Q.atMostView currentTime olddb return $ merge pruned where ins db (k, p, v) = Q.insert k p v db -- There is not 'merge' API. -- We hope that newdb is smaller than pruned. merge pruned newdb = foldl' ins pruned entries where entries = Q.toList newdb ---------------------------------------------------------------- establish :: Reaper DB Item -> Sec -> SessionID -> SessionData -> IO () establish reaper lifetime k sd = do ref <- newIORef Fresh p <- (+ lifetime) . C.sec <$> C.getTime C.Monotonic let v = (sd', ref) reaperAdd reaper (k', p, v, Add) where k' = toKey k sd' = toValue sd resume :: Reaper DB Item -> Use -> SessionID -> IO (Maybe SessionData) resume reaper use k = do db <- reaperRead reaper case Q.lookup k' db of Nothing -> return Nothing Just (p, v@(sd, ref)) -> case use of SingleUse -> do available <- atomicModifyIORef' ref check reaperAdd reaper (k', p, v, Del) return $ if available then Just (fromValue sd) else Nothing MultipleUse -> return $ Just (fromValue sd) where check Fresh = (Used, True) check Used = (Used, False) k' = toKey k invalidate :: Reaper DB Item -> SessionID -> IO () invalidate reaper k = do db <- reaperRead reaper case Q.lookup k' db of Nothing -> return () Just (p, v) -> reaperAdd reaper (k', p, v, Del) where k' = toKey k tls-session-manager-0.0.8/Network/TLS/SessionTicket.hs0000644000000000000000000000462107346545000021024 0ustar0000000000000000{-# LANGUAGE RecordWildCards #-} -- | A manager for TLS 1.2/1.3 session ticket. -- -- Tracking client hello is not implemented yet. -- So, if this is used for TLS 1.3 0-RTT, -- replay attack is possible. -- If your application data in 0-RTT changes the status of server side, -- use 'Network.TLS.SessionManager' instead. -- -- A dedicated thread is running repeatedly to replece -- secret keys. So, energy saving is not achieved. module Network.TLS.SessionTicket ( newSessionTicketManager, Config, defaultConfig, ticketLifetime, secretKeyInterval, ) where import Codec.Serialise import qualified Crypto.Token as CT import qualified Data.ByteString.Lazy as L import Network.TLS import Network.TLS.Internal -- | Configuration for session tickets. data Config = Config { ticketLifetime :: Int -- ^ Ticket lifetime in seconds. , secretKeyInterval :: Int } -- | ticketLifetime: 2 hours (7200 seconds), secretKeyInterval: 30 minutes (1800 seconds) defaultConfig :: Config defaultConfig = Config { ticketLifetime = 7200 -- 2 hours , secretKeyInterval = 1800 -- 30 minites } -- | Creating a session ticket manager. newSessionTicketManager :: Config -> IO SessionManager newSessionTicketManager Config{..} = sessionTicketManager <$> CT.spawnTokenManager conf where conf = CT.defaultConfig { CT.interval = secretKeyInterval , CT.tokenLifetime = ticketLifetime , CT.threadName = "TLS ticket manager" } sessionTicketManager :: CT.TokenManager -> SessionManager sessionTicketManager ctmgr = noSessionManager { sessionResume = resume ctmgr , sessionResumeOnlyOnce = resume ctmgr , sessionEstablish = establish ctmgr , sessionInvalidate = \_ -> return () , sessionUseTicket = True } establish :: CT.TokenManager -> SessionID -> SessionData -> IO (Maybe Ticket) establish ctmgr _ sd = Just <$> CT.encryptToken ctmgr b where b = L.toStrict $ serialise sd resume :: CT.TokenManager -> Ticket -> IO (Maybe SessionData) resume ctmgr ticket | isTicket ticket = do msdb <- CT.decryptToken ctmgr ticket case msdb of Nothing -> return Nothing Just sdb -> case deserialiseOrFail $ L.fromStrict sdb of Left _ -> return Nothing Right sd -> return $ Just sd | otherwise = return Nothing tls-session-manager-0.0.8/Setup.hs0000644000000000000000000000005707346545000015241 0ustar0000000000000000import Distribution.Simple main = defaultMain tls-session-manager-0.0.8/tls-session-manager.cabal0000644000000000000000000000212007346545000020455 0ustar0000000000000000cabal-version: >=1.10 name: tls-session-manager version: 0.0.8 license: BSD3 license-file: LICENSE maintainer: kazu@iij.ad.jp author: Kazu Yamamoto synopsis: In-memory TLS session DB and session ticket description: TLS session manager with limitation, automatic pruning, energy saving and replay resistance and session ticket manager category: Web build-type: Simple extra-source-files: ChangeLog.md library exposed-modules: Network.TLS.SessionManager Network.TLS.SessionTicket other-modules: Network.TLS.Imports default-language: Haskell2010 ghc-options: -Wall build-depends: base >=4.7 && <5, auto-update >= 0.2.2 && < 0.3, bytestring >= 0.10 && < 0.13, clock >= 0.8 && < 0.9, crypto-token >= 0.1.2 && < 0.2, memory >= 0.18.0 && < 0.19, psqueues >= 0.2 && < 0.3, serialise >= 0.2 && < 0.3, tls >= 2.0 && < 2.3 if impl(ghc >=8) default-extensions: Strict StrictData