{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Encrypted tokens/tickets to keep state in the client side.
module Crypto.Token (
    -- * Configuration
    Config,
    defaultConfig,
    interval,
    tokenLifetime,
    threadName,

    -- * Token manager
    TokenManager,
    spawnTokenManager,
    killTokenManager,

    -- * Encryption and decryption
    encryptToken,
    decryptToken,
) where

import Control.Concurrent
import qualified Control.Exception as E
import Control.Monad (join, unless, when)
import Crypto.Cipher.AES (AES256)
import Crypto.Cipher.Types (AEADMode (..), AuthTag (..))
import qualified Crypto.Cipher.Types as C
import Crypto.Error (maybeCryptoError, throwCryptoError)
import Crypto.Random (getRandomBytes)
import Data.Array.IO
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.IORef as I
import Data.Maybe (isJust)
import Data.Word
import GHC.Clock (getMonotonicTimeNSec)
import GHC.Conc.Sync (labelThread)
#if !defined(mingw32_HOST_OS)
import GHC.Event (getSystemTimerManager, registerTimeout, unregisterTimeout)
#endif
import Network.ByteOrder
import System.Mem.Weak (deRefWeak)

----------------------------------------------------------------

type Index = Word16
type Counter = Word64

-- | Configuration for token manager.
data Config = Config
    { Config -> Int
interval :: Int
    -- ^ The interval to generate a new secret and remove the oldest one in seconds.
    , Config -> Int
tokenLifetime :: Int
    -- ^ The token lifetime in seconds, that is, tokens can be decrypted in this period.
    --   It is cut short if it spans more than 65535 intervals.
    , Config -> String
threadName :: String
    -- ^ The label of the thread used without the timer manager.
    }
    deriving (Config -> Config -> Bool
(Config -> Config -> Bool)
-> (Config -> Config -> Bool) -> Eq Config
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Config -> Config -> Bool
== :: Config -> Config -> Bool
$c/= :: Config -> Config -> Bool
/= :: Config -> Config -> Bool
Eq, Int -> Config -> ShowS
[Config] -> ShowS
Config -> String
(Int -> Config -> ShowS)
-> (Config -> String) -> ([Config] -> ShowS) -> Show Config
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Config -> ShowS
showsPrec :: Int -> Config -> ShowS
$cshow :: Config -> String
show :: Config -> String
$cshowList :: [Config] -> ShowS
showList :: [Config] -> ShowS
Show)

-- | Default configuration to update secrets in 30 minutes (1,800 seconds) and token lifetime is 2 hours (7,200 seconds)
--
-- >>> defaultConfig
-- Config {interval = 1800, tokenLifetime = 7200, threadName = "Crypto token manager"}
defaultConfig :: Config
defaultConfig :: Config
defaultConfig =
    Config
        { interval :: Int
interval = Int
1800
        , tokenLifetime :: Int
tokenLifetime = Int
7200
        , threadName :: String
threadName = String
"Crypto token manager"
        }

----------------------------------------------------------------

-- | The abstract data type for token manager.
data TokenManager = TokenManager
    { TokenManager -> AES256
headerKey :: AES256
    , TokenManager -> IO (Secret, Word16)
getEncryptSecret :: IO (Secret, Index)
    , TokenManager -> Word16 -> IO Secret
getDecryptSecret :: Index -> IO Secret
    , TokenManager -> Word64
lifetimeNSec :: Word64
    , TokenManager -> IO ()
stopRotation :: IO ()
    }

-- | Spawning a token manager.  Secrets are rotated every 'interval' by a
--   timer of the RTS, with no thread of its own, also when no token is
--   made.  The timer ends with 'killTokenManager', or once the manager is
--   garbage-collected.  Without the timer manager of the threaded RTS on
--   a POSIX system, a thread does the same.
--   This throws an 'IOError' if 'interval' is not positive.
spawnTokenManager :: Config -> IO TokenManager
spawnTokenManager :: Config -> IO TokenManager
spawnTokenManager Config{Int
String
interval :: Config -> Int
tokenLifetime :: Config -> Int
threadName :: Config -> String
interval :: Int
tokenLifetime :: Int
threadName :: String
..} = do
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
interval Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        IOError -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO (IOError -> IO ()) -> IOError -> IO ()
forall a b. (a -> b) -> a -> b
$
            String -> IOError
userError String
"Crypto.Token: interval must be positive"
    -- the secret a token was made with must outlive the token itself,
    -- and an index travels as Word16, so there are at most 65536 slots
    let lifetime :: Int
lifetime = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 Int
tokenLifetime
        slots :: Int
slots = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min Int
65536 (Int -> Int) -> Int -> Int
forall a b. (a -> b) -> a -> b
$ (Int
lifetime Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
interval Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
interval Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
    emp <- IO Secret
emptySecret
    arr <- newArray (0, slots - 1) emp
    ent <- generateSecret
    writeArray arr 0 ent
    epoch <- currentEpoch
    var <- newMVar (0, epoch)
    weak <- mkWeakMVar var (return ())
    stop <- startRotation threadName (untilNext interval) $ do
        mvar <- deRefWeak weak
        case mvar of
            Maybe (MVar (Int, Word64))
Nothing -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
            Just MVar (Int, Word64)
v -> Bool
True Bool -> IO (Secret, Word16) -> IO Bool
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ IOArray Int Secret -> MVar (Int, Word64) -> IO (Secret, Word16)
rotate IOArray Int Secret
arr MVar (Int, Word64)
v
    hkey <- newHeaderKey
    return $
        TokenManager
            { headerKey = hkey
            , getEncryptSecret = rotate arr var
            , getDecryptSecret = readSecret arr
            , lifetimeNSec = fromIntegral lifetime * 1000000000
            , stopRotation = do
                stop
                -- the secrets made so far are forgotten
                modifyMVar_ var $ \(Int, Word64)
st -> do
                    n <- (Int, Int) -> Int
forall a. Ix a => (a, a) -> Int
rangeSize ((Int, Int) -> Int) -> IO (Int, Int) -> IO Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOArray Int Secret -> IO (Int, Int)
forall i. Ix i => IOArray i Secret -> IO (i, i)
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> m (i, i)
getBounds IOArray Int Secret
arr
                    mapM_ (\Int
i -> IO Secret
generateSecret IO Secret -> (Secret -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IOArray Int Secret -> Int -> Secret -> IO ()
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> i -> e -> m ()
writeArray IOArray Int Secret
arr Int
i) [0 .. n - 1]
                    return st
            }
  where
    currentEpoch :: IO Word64
currentEpoch = (Word64 -> Word64 -> Word64
forall a. Integral a => a -> a -> a
`div` Word64
intervalNSec) (Word64 -> Word64) -> IO Word64 -> IO Word64
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO Word64
getMonotonicTimeNSec
    intervalNSec :: Word64
intervalNSec = Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
interval Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
1000000000 :: Word64
    -- The secrets of the intervals passed since the last rotation are
    -- replaced; with more of them than slots, each slot once.
    rotate :: IOArray Int Secret -> MVar (Int, Word64) -> IO (Secret, Index)
    rotate :: IOArray Int Secret -> MVar (Int, Word64) -> IO (Secret, Word16)
rotate IOArray Int Secret
arr MVar (Int, Word64)
var = MVar (Int, Word64)
-> ((Int, Word64) -> IO ((Int, Word64), (Secret, Word16)))
-> IO (Secret, Word16)
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar MVar (Int, Word64)
var (((Int, Word64) -> IO ((Int, Word64), (Secret, Word16)))
 -> IO (Secret, Word16))
-> ((Int, Word64) -> IO ((Int, Word64), (Secret, Word16)))
-> IO (Secret, Word16)
forall a b. (a -> b) -> a -> b
$ \(Int
idx, Word64
epoch0) -> do
        epoch <- Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
max Word64
epoch0 (Word64 -> Word64) -> IO Word64 -> IO Word64
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO Word64
currentEpoch
        n <- rangeSize <$> getBounds arr
        let steps = Word64
epoch Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
epoch0
            idx' = (Int
idx Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64
steps Word64 -> Word64 -> Word64
forall a. Integral a => a -> a -> a
`mod` Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
n)) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
n
            k = Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
min Word64
steps (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
n)) :: Int
        mapM_
            (\Int
j -> IO Secret
generateSecret IO Secret -> (Secret -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IOArray Int Secret -> Int -> Secret -> IO ()
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> i -> e -> m ()
writeArray IOArray Int Secret
arr ((Int
idx' Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
j) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
n))
            [0 .. k - 1]
        sec <- readArray arr idx'
        return ((idx', epoch), (sec, fromIntegral idx'))

-- | Microseconds until the next multiple of the interval in seconds, at
--   most 1000 seconds so that it fits a 32-bit 'Int'.
untilNext :: Int -> IO Int
untilNext :: Int -> IO Int
untilNext Int
interval = do
    now <- IO Word64
getMonotonicTimeNSec
    let i = Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
interval Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
1000000000 :: Word64
        ns = Word64
i Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
now Word64 -> Word64 -> Word64
forall a. Integral a => a -> a -> a
`mod` Word64
i
    return $ fromIntegral (min ns 1000000000000 `div` 1000) + 1

-- | Running the action at the times given until it answers 'False' or
--   the returned action is run.
startRotation :: String -> IO Int -> IO Bool -> IO (IO ())
#if defined(mingw32_HOST_OS)
startRotation = startRotationThread
#else
startRotation :: String -> IO Int -> IO Bool -> IO (IO ())
startRotation String
name IO Int
next IO Bool
tick
    | Bool
rtsSupportsBoundThreads = do
        mgr <- IO TimerManager
getSystemTimerManager
        -- Nothing once stopped
        ref <- I.newIORef $ Just Nothing
        let schedule = do
                us <- IO Int
next
                key <- registerTimeout mgr us fire
                live <- I.atomicModifyIORef' ref $ \Maybe (Maybe TimeoutKey)
m ->
                    (Maybe (Maybe TimeoutKey), Bool)
-> (Maybe TimeoutKey -> (Maybe (Maybe TimeoutKey), Bool))
-> Maybe (Maybe TimeoutKey)
-> (Maybe (Maybe TimeoutKey), Bool)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Maybe (Maybe TimeoutKey)
forall a. Maybe a
Nothing, Bool
False) ((Maybe (Maybe TimeoutKey), Bool)
-> Maybe TimeoutKey -> (Maybe (Maybe TimeoutKey), Bool)
forall a b. a -> b -> a
const (Maybe TimeoutKey -> Maybe (Maybe TimeoutKey)
forall a. a -> Maybe a
Just (TimeoutKey -> Maybe TimeoutKey
forall a. a -> Maybe a
Just TimeoutKey
key), Bool
True)) Maybe (Maybe TimeoutKey)
m
                unless live $ unregisterTimeout mgr key
            fire = do
                live <- Maybe (Maybe TimeoutKey) -> Bool
forall a. Maybe a -> Bool
isJust (Maybe (Maybe TimeoutKey) -> Bool)
-> IO (Maybe (Maybe TimeoutKey)) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IORef (Maybe (Maybe TimeoutKey)) -> IO (Maybe (Maybe TimeoutKey))
forall a. IORef a -> IO a
I.readIORef IORef (Maybe (Maybe TimeoutKey))
ref
                when live $ do
                    continue <- tick `E.catch` ignoreSync
                    when continue schedule
        schedule
        return $ do
            m <- I.atomicModifyIORef' ref $ \Maybe (Maybe TimeoutKey)
m -> (Maybe (Maybe TimeoutKey)
forall a. Maybe a
Nothing, Maybe (Maybe TimeoutKey)
m)
            mapM_ (unregisterTimeout mgr) (join m)
    | Bool
otherwise = String -> IO Int -> IO Bool -> IO (IO ())
startRotationThread String
name IO Int
next IO Bool
tick
#endif

startRotationThread :: String -> IO Int -> IO Bool -> IO (IO ())
startRotationThread :: String -> IO Int -> IO Bool -> IO (IO ())
startRotationThread String
name IO Int
next IO Bool
tick = do
    stopped <- Bool -> IO (IORef Bool)
forall a. a -> IO (IORef a)
I.newIORef Bool
False
    let loop = do
            IO Int
next IO Int -> (Int -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Int -> IO ()
threadDelay
            s <- IORef Bool -> IO Bool
forall a. IORef a -> IO a
I.readIORef IORef Bool
stopped
            unless s $ do
                continue <- tick `E.catch` ignoreSync
                when continue loop
    tid <- forkIO loop
    labelThread tid name
    return $ I.atomicWriteIORef stopped True

-- | A failed rotation is retried at the next time.
ignoreSync :: E.SomeException -> IO Bool
ignoreSync :: SomeException -> IO Bool
ignoreSync SomeException
e = case SomeException -> Maybe SomeAsyncException
forall e. Exception e => SomeException -> Maybe e
E.fromException SomeException
e of
    Just (E.SomeAsyncException e
_) -> SomeException -> IO Bool
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO SomeException
e
    Maybe SomeAsyncException
Nothing -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True

-- | Killing a token manager: its rotation stops and the secrets made so
--   far are forgotten.
killTokenManager :: TokenManager -> IO ()
killTokenManager :: TokenManager -> IO ()
killTokenManager = TokenManager -> IO ()
stopRotation

----------------------------------------------------------------

readSecret :: IOArray Int Secret -> Index -> IO Secret
readSecret :: IOArray Int Secret -> Word16 -> IO Secret
readSecret IOArray Int Secret
secrets Word16
idx0 = do
    n <- (Int, Int) -> Int
forall a. Ix a => (a, a) -> Int
rangeSize ((Int, Int) -> Int) -> IO (Int, Int) -> IO Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOArray Int Secret -> IO (Int, Int)
forall i. Ix i => IOArray i Secret -> IO (i, i)
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> m (i, i)
getBounds IOArray Int Secret
secrets
    readArray secrets $ fromIntegral idx0 `mod` n

----------------------------------------------------------------

data Secret = Secret
    { Secret -> ByteString
secretIV :: ByteString
    , Secret -> ByteString
secretKey :: ByteString
    , Secret -> IORef Word64
secretCounter :: I.IORef Counter
    }

emptySecret :: IO Secret
emptySecret :: IO Secret
emptySecret = ByteString -> ByteString -> IORef Word64 -> Secret
Secret ByteString
BS.empty ByteString
BS.empty (IORef Word64 -> Secret) -> IO (IORef Word64) -> IO Secret
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Word64 -> IO (IORef Word64)
forall a. a -> IO (IORef a)
I.newIORef Word64
0

generateSecret :: IO Secret
generateSecret :: IO Secret
generateSecret =
    ByteString -> ByteString -> IORef Word64 -> Secret
Secret
        (ByteString -> ByteString -> IORef Word64 -> Secret)
-> IO ByteString -> IO (ByteString -> IORef Word64 -> Secret)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO ByteString
genIV
        IO (ByteString -> IORef Word64 -> Secret)
-> IO ByteString -> IO (IORef Word64 -> Secret)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> IO ByteString
genKey
        IO (IORef Word64 -> Secret) -> IO (IORef Word64) -> IO Secret
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Word64 -> IO (IORef Word64)
forall a. a -> IO (IORef a)
I.newIORef Word64
0

genKey :: IO ByteString
genKey :: IO ByteString
genKey = Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
keyLength

genIV :: IO ByteString
genIV :: IO ByteString
genIV = Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
ivLength

----------------------------------------------------------------

-- 96 bits, the nonce length GCM is designed for
ivLength :: Int
ivLength :: Int
ivLength = Int
12

keyLength :: Int
keyLength :: Int
keyLength = Int
32

indexLength :: Int
indexLength :: Int
indexLength = Int
2

counterLength :: Int
counterLength :: Int
counterLength = Int
8

tagLength :: Int
tagLength :: Int
tagLength = Int
16

-- one AES block: index, counter and zero padding
headerLength :: Int
headerLength :: Int
headerLength = Int
16

----------------------------------------------------------------

data Header = Header
    { Header -> Word16
headerIndex :: Index
    , Header -> Word64
headerCounter :: Counter
    }

encodeHeader :: Header -> IO ByteString
encodeHeader :: Header -> IO ByteString
encodeHeader Header{Word16
Word64
headerIndex :: Header -> Word16
headerCounter :: Header -> Word64
headerIndex :: Word16
headerCounter :: Word64
..} = Int -> (WriteBuffer -> IO ()) -> IO ByteString
withWriteBuffer (Int
indexLength Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
counterLength) ((WriteBuffer -> IO ()) -> IO ByteString)
-> (WriteBuffer -> IO ()) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \WriteBuffer
wbuf -> do
    WriteBuffer -> Word16 -> IO ()
write16 WriteBuffer
wbuf Word16
headerIndex
    WriteBuffer -> Word64 -> IO ()
write64 WriteBuffer
wbuf Word64
headerCounter

decodeHeader :: ByteString -> IO Header
decodeHeader :: ByteString -> IO Header
decodeHeader ByteString
bs = ByteString -> (ReadBuffer -> IO Header) -> IO Header
forall a. ByteString -> (ReadBuffer -> IO a) -> IO a
withReadBuffer ByteString
bs ((ReadBuffer -> IO Header) -> IO Header)
-> (ReadBuffer -> IO Header) -> IO Header
forall a b. (a -> b) -> a -> b
$ \ReadBuffer
rbuf ->
    Word16 -> Word64 -> Header
Header (Word16 -> Word64 -> Header) -> IO Word16 -> IO (Word64 -> Header)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ReadBuffer -> IO Word16
forall a. Readable a => a -> IO Word16
read16 ReadBuffer
rbuf IO (Word64 -> Header) -> IO Word64 -> IO Header
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ReadBuffer -> IO Word64
forall a. Readable a => a -> IO Word64
read64 ReadBuffer
rbuf

newHeaderKey :: IO AES256
newHeaderKey :: IO AES256
newHeaderKey = do
    key <- Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
keyLength :: IO ByteString
    return $ throwCryptoError $ C.cipherInit key

----------------------------------------------------------------

-- The header is encrypted so that tokens do not reveal how they relate.
addHeader :: TokenManager -> Index -> Counter -> ByteString -> IO ByteString
addHeader :: TokenManager -> Word16 -> Word64 -> ByteString -> IO ByteString
addHeader TokenManager{IO ()
IO (Secret, Word16)
Word64
AES256
Word16 -> IO Secret
headerKey :: TokenManager -> AES256
getEncryptSecret :: TokenManager -> IO (Secret, Word16)
getDecryptSecret :: TokenManager -> Word16 -> IO Secret
lifetimeNSec :: TokenManager -> Word64
stopRotation :: TokenManager -> IO ()
headerKey :: AES256
getEncryptSecret :: IO (Secret, Word16)
getDecryptSecret :: Word16 -> IO Secret
lifetimeNSec :: Word64
stopRotation :: IO ()
..} Word16
idx Word64
counter ByteString
cipher = do
    hdrbin <- Header -> IO ByteString
encodeHeader (Header -> IO ByteString) -> Header -> IO ByteString
forall a b. (a -> b) -> a -> b
$ Word16 -> Word64 -> Header
Header Word16
idx Word64
counter
    let padding = Int -> Word8 -> ByteString
BS.replicate (Int
headerLength Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
hdrbin) Word8
0
        blk = AES256 -> ByteString -> ByteString
forall ba. ByteArray ba => AES256 -> ba -> ba
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
C.ecbEncrypt AES256
headerKey (ByteString
hdrbin ByteString -> ByteString -> ByteString
`BS.append` ByteString
padding)
    return (blk `BS.append` cipher)

delHeader
    :: TokenManager -> ByteString -> IO (Maybe (Index, Counter, ByteString))
delHeader :: TokenManager
-> ByteString -> IO (Maybe (Word16, Word64, ByteString))
delHeader TokenManager{IO ()
IO (Secret, Word16)
Word64
AES256
Word16 -> IO Secret
headerKey :: TokenManager -> AES256
getEncryptSecret :: TokenManager -> IO (Secret, Word16)
getDecryptSecret :: TokenManager -> Word16 -> IO Secret
lifetimeNSec :: TokenManager -> Word64
stopRotation :: TokenManager -> IO ()
headerKey :: AES256
getEncryptSecret :: IO (Secret, Word16)
getDecryptSecret :: Word16 -> IO Secret
lifetimeNSec :: Word64
stopRotation :: IO ()
..} ByteString
token
    | ByteString -> Int
BS.length ByteString
token Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
headerLength = Maybe (Word16, Word64, ByteString)
-> IO (Maybe (Word16, Word64, ByteString))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Word16, Word64, ByteString)
forall a. Maybe a
Nothing
    | Bool
otherwise = do
        let (ByteString
blk, ByteString
cipher) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
headerLength ByteString
token
            (ByteString
hdrbin, ByteString
padding) =
                Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (Int
indexLength Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
counterLength) (ByteString -> (ByteString, ByteString))
-> ByteString -> (ByteString, ByteString)
forall a b. (a -> b) -> a -> b
$ AES256 -> ByteString -> ByteString
forall ba. ByteArray ba => AES256 -> ba -> ba
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
C.ecbDecrypt AES256
headerKey ByteString
blk
        if (Word8 -> Bool) -> ByteString -> Bool
BS.any (Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
0) ByteString
padding
            then Maybe (Word16, Word64, ByteString)
-> IO (Maybe (Word16, Word64, ByteString))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Word16, Word64, ByteString)
forall a. Maybe a
Nothing
            else do
                Header{..} <- ByteString -> IO Header
decodeHeader ByteString
hdrbin
                return $ Just (headerIndex, headerCounter, cipher)

-- | Encrypting a target value to get a token.
encryptToken
    :: TokenManager
    -> ByteString
    -> IO ByteString
encryptToken :: TokenManager -> ByteString -> IO ByteString
encryptToken TokenManager
mgr ByteString
x = do
    (secret, idx) <- TokenManager -> IO (Secret, Word16)
getEncryptSecret TokenManager
mgr
    now <- getMonotonicTimeNSec
    (counter, cipher) <- encrypt secret (bytestring64 now `BS.append` x)
    addHeader mgr idx counter cipher

encrypt
    :: Secret
    -> ByteString
    -> IO (Counter, ByteString)
encrypt :: Secret -> ByteString -> IO (Word64, ByteString)
encrypt Secret
secret ByteString
plain = do
    counter <- IORef Word64 -> (Word64 -> (Word64, Word64)) -> IO Word64
forall a b. IORef a -> (a -> (a, b)) -> IO b
I.atomicModifyIORef' (Secret -> IORef Word64
secretCounter Secret
secret) (\Word64
i -> (Word64
i Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
1, Word64
i))
    let nonce = Word64 -> ByteString -> ByteString
makeNonce Word64
counter (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Secret -> ByteString
secretIV Secret
secret
        cipher = ByteString -> ByteString -> ByteString -> ByteString
aes256gcmEncrypt ByteString
plain (Secret -> ByteString
secretKey Secret
secret) ByteString
nonce
    return (counter, cipher)

-- | Decrypting a token to get a target value.
decryptToken
    :: TokenManager
    -> ByteString
    -> IO (Maybe ByteString)
decryptToken :: TokenManager -> ByteString -> IO (Maybe ByteString)
decryptToken TokenManager
mgr ByteString
token = do
    mx <- TokenManager
-> ByteString -> IO (Maybe (Word16, Word64, ByteString))
delHeader TokenManager
mgr ByteString
token
    case mx of
        Maybe (Word16, Word64, ByteString)
Nothing -> Maybe ByteString -> IO (Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe ByteString
forall a. Maybe a
Nothing
        Just (Word16
idx, Word64
counter, ByteString
cipher) -> do
            secret <- TokenManager -> Word16 -> IO Secret
getDecryptSecret TokenManager
mgr Word16
idx
            mplain <- decrypt secret counter cipher
            now <- getMonotonicTimeNSec
            return $ mplain >>= checkLifetime now
  where
    checkLifetime :: Word64 -> ByteString -> Maybe ByteString
checkLifetime Word64
now ByteString
plain
        | ByteString -> Int
BS.length ByteString
plain Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
8 = Maybe ByteString
forall a. Maybe a
Nothing
        | Word64
issued Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
now Bool -> Bool -> Bool
&& Word64
now Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
issued Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= TokenManager -> Word64
lifetimeNSec TokenManager
mgr = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
x
        | Bool
otherwise = Maybe ByteString
forall a. Maybe a
Nothing
      where
        (ByteString
hdr, ByteString
x) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
8 ByteString
plain
        issued :: Word64
issued = ByteString -> Word64
word64 ByteString
hdr

decrypt
    :: Secret
    -> Counter
    -> ByteString
    -> IO (Maybe ByteString)
decrypt :: Secret -> Word64 -> ByteString -> IO (Maybe ByteString)
decrypt Secret
secret Word64
counter ByteString
cipher = do
    let nonce :: ByteString
nonce = Word64 -> ByteString -> ByteString
makeNonce Word64
counter (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Secret -> ByteString
secretIV Secret
secret
    Maybe ByteString -> IO (Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe ByteString -> IO (Maybe ByteString))
-> Maybe ByteString -> IO (Maybe ByteString)
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString -> ByteString -> Maybe ByteString
aes256gcmDecrypt ByteString
cipher (Secret -> ByteString
secretKey Secret
secret) ByteString
nonce

makeNonce :: Counter -> ByteString -> ByteString
makeNonce :: Word64 -> ByteString -> ByteString
makeNonce Word64
counter ByteString
iv = ByteString
iv ByteString -> ByteString -> ByteString
forall a b c.
(ByteArrayAccess a, ByteArrayAccess b, ByteArray c) =>
a -> b -> c
`BA.xor` ByteString
cv
  where
    cv :: ByteString
cv = Int -> Word8 -> ByteString
BS.replicate (Int
ivLength Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
counterLength) Word8
0 ByteString -> ByteString -> ByteString
`BS.append` Word64 -> ByteString
bytestring64 Word64
counter

----------------------------------------------------------------

constantAdditionalData :: ByteString
constantAdditionalData :: ByteString
constantAdditionalData = ByteString
BS.empty

aes256gcmEncrypt
    :: ByteString
    -> ByteString
    -> ByteString
    -> ByteString
aes256gcmEncrypt :: ByteString -> ByteString -> ByteString -> ByteString
aes256gcmEncrypt ByteString
plain ByteString
key ByteString
nonce = ByteString
cipher ByteString -> ByteString -> ByteString
`BS.append` (Bytes -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert Bytes
tag)
  where
    conn :: AES256
conn = CryptoFailable AES256 -> AES256
forall a. CryptoFailable a -> a
throwCryptoError (ByteString -> CryptoFailable AES256
forall key. ByteArray key => key -> CryptoFailable AES256
forall cipher key.
(Cipher cipher, ByteArray key) =>
key -> CryptoFailable cipher
C.cipherInit ByteString
key) :: AES256
    aeadIni :: AEAD AES256
aeadIni = CryptoFailable (AEAD AES256) -> AEAD AES256
forall a. CryptoFailable a -> a
throwCryptoError (CryptoFailable (AEAD AES256) -> AEAD AES256)
-> CryptoFailable (AEAD AES256) -> AEAD AES256
forall a b. (a -> b) -> a -> b
$ AEADMode -> AES256 -> ByteString -> CryptoFailable (AEAD AES256)
forall cipher iv.
(BlockCipher cipher, ByteArrayAccess iv) =>
AEADMode -> cipher -> iv -> CryptoFailable (AEAD cipher)
forall iv.
ByteArrayAccess iv =>
AEADMode -> AES256 -> iv -> CryptoFailable (AEAD AES256)
C.aeadInit AEADMode
AEAD_GCM AES256
conn ByteString
nonce
    (AuthTag Bytes
tag, ByteString
cipher) = AEAD AES256
-> ByteString -> ByteString -> Int -> (AuthTag, ByteString)
forall aad ba a.
(ByteArrayAccess aad, ByteArray ba) =>
AEAD a -> aad -> ba -> Int -> (AuthTag, ba)
C.aeadSimpleEncrypt AEAD AES256
aeadIni ByteString
constantAdditionalData ByteString
plain Int
tagLength

aes256gcmDecrypt
    :: ByteString
    -> ByteString
    -> ByteString
    -> Maybe ByteString
aes256gcmDecrypt :: ByteString -> ByteString -> ByteString -> Maybe ByteString
aes256gcmDecrypt ByteString
ctexttag ByteString
key ByteString
nonce = do
    aes <- CryptoFailable AES256 -> Maybe AES256
forall a. CryptoFailable a -> Maybe a
maybeCryptoError (CryptoFailable AES256 -> Maybe AES256)
-> CryptoFailable AES256 -> Maybe AES256
forall a b. (a -> b) -> a -> b
$ ByteString -> CryptoFailable AES256
forall key. ByteArray key => key -> CryptoFailable AES256
forall cipher key.
(Cipher cipher, ByteArray key) =>
key -> CryptoFailable cipher
C.cipherInit ByteString
key :: Maybe AES256
    aead <- maybeCryptoError $ C.aeadInit AEAD_GCM aes nonce
    let (ctext, tag) = BS.splitAt (BS.length ctexttag - tagLength) ctexttag
        authtag = Bytes -> AuthTag
AuthTag (Bytes -> AuthTag) -> Bytes -> AuthTag
forall a b. (a -> b) -> a -> b
$ ByteString -> Bytes
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert ByteString
tag
    C.aeadSimpleDecrypt aead constantAdditionalData ctext authtag