{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE PackageImports #-}
module Web.ClientSession
(
Key
, IV
, randomIV
, mkIV
, getKey
, getKeyEnv
, defaultKeyFile
, getDefaultKey
, initKey
, randomKey
, randomKeyEnv
, encrypt
, encryptIO
, decrypt
) where
import Control.Applicative ((<$>))
import Control.Concurrent (forkIO)
import Control.Monad (guard, when)
import Data.Bifunctor (first)
import Data.Function (on)
#if MIN_VERSION_base(4,7,0)
import System.Environment (lookupEnv, setEnv)
#elif MIN_VERSION_base(4,6,0)
import System.Environment (lookupEnv)
import System.SetEnv (setEnv)
#else
import System.LookupEnv (lookupEnv)
import System.SetEnv (setEnv)
#endif
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.IORef as I
import System.Directory (doesFileExist)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Base64 as B
import Data.Serialize (encode, Serialize (put, get), getBytes, putByteString)
import Data.Tagged (Tagged, untag)
import Crypto.Classes (constTimeEq)
import qualified Crypto.Cipher.AES as A
import Crypto.Cipher.Types(Cipher(..),BlockCipher(..),makeIV)
import Crypto.Error (eitherCryptoError)
import "cryptonite" Crypto.Random (ChaChaDRG,drgNew,randomBytesGenerate)
import Crypto.Skein (skeinMAC', Skein_512_256)
import System.Entropy (getEntropy)
data Key = Key { Key -> AES256
aesKey ::
!A.AES256
, Key -> ByteString -> Skein_512_256
macKey :: !(S.ByteString -> Skein_512_256)
, Key -> ByteString
keyRaw :: !S.ByteString
}
instance Eq Key where
Key AES256
_ ByteString -> Skein_512_256
_ ByteString
r1 == :: Key -> Key -> Bool
== Key AES256
_ ByteString -> Skein_512_256
_ ByteString
r2 = ByteString
r1 forall a. Eq a => a -> a -> Bool
== ByteString
r2
instance Serialize Key where
put :: Putter Key
put = Putter ByteString
putByteString forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> ByteString
keyRaw
get :: Get Key
get = forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall a. HasCallStack => String -> a
error forall a. a -> a
id forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either String Key
initKey forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> Get ByteString
getBytes Int
96
instance Show Key where
show :: Key -> String
show Key
_ = String
"<Web.ClientSession.Key>"
newtype IV = IV S.ByteString
unsafeMkIV :: S.ByteString -> IV
unsafeMkIV :: ByteString -> IV
unsafeMkIV ByteString
bs = (ByteString -> IV
IV ByteString
bs)
unIV :: IV -> S.ByteString
unIV :: IV -> ByteString
unIV (IV ByteString
bs) = ByteString
bs
instance Eq IV where
== :: IV -> IV -> Bool
(==) = forall a. Eq a => a -> a -> Bool
(==) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
/= :: IV -> IV -> Bool
(/=) = forall a. Eq a => a -> a -> Bool
(/=) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
instance Ord IV where
compare :: IV -> IV -> Ordering
compare = forall a. Ord a => a -> a -> Ordering
compare forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
<= :: IV -> IV -> Bool
(<=) = forall a. Ord a => a -> a -> Bool
(<=) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
< :: IV -> IV -> Bool
(<) = forall a. Ord a => a -> a -> Bool
(<) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
>= :: IV -> IV -> Bool
(>=) = forall a. Ord a => a -> a -> Bool
(>=) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
> :: IV -> IV -> Bool
(>) = forall a. Ord a => a -> a -> Bool
(>) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` IV -> ByteString
unIV
instance Show IV where
show :: IV -> String
show = forall a. Show a => a -> String
show forall b c a. (b -> c) -> (a -> b) -> a -> c
. IV -> ByteString
unIV
instance Serialize IV where
put :: Putter IV
put = forall t. Serialize t => Putter t
put forall b c a. (b -> c) -> (a -> b) -> a -> c
. IV -> ByteString
unIV
get :: Get IV
get = ByteString -> IV
unsafeMkIV forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall t. Serialize t => Get t
get
mkIV :: S.ByteString -> Maybe IV
mkIV :: ByteString -> Maybe IV
mkIV ByteString
bs | ByteString -> Int
S.length ByteString
bs forall a. Eq a => a -> a -> Bool
== Int
16 = forall a. a -> Maybe a
Just (ByteString -> IV
unsafeMkIV ByteString
bs)
| Bool
otherwise = forall a. Maybe a
Nothing
randomIV :: IO IV
randomIV :: IO IV
randomIV = IO IV
chaChaRNG
defaultKeyFile :: FilePath
defaultKeyFile :: String
defaultKeyFile = String
"client_session_key.aes"
getDefaultKey :: IO Key
getDefaultKey :: IO Key
getDefaultKey = String -> IO Key
getKey String
defaultKeyFile
getKey :: FilePath
-> IO Key
getKey :: String -> IO Key
getKey String
keyFile = do
Bool
exists <- String -> IO Bool
doesFileExist String
keyFile
if Bool
exists
then String -> IO ByteString
S.readFile String
keyFile forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> b -> a
const IO Key
newKey) forall (m :: * -> *) a. Monad m => a -> m a
return forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either String Key
initKey
else IO Key
newKey
where
newKey :: IO Key
newKey = do
(ByteString
bs, Key
key') <- IO (ByteString, Key)
randomKey
String -> ByteString -> IO ()
S.writeFile String
keyFile ByteString
bs
forall (m :: * -> *) a. Monad m => a -> m a
return Key
key'
getKeyEnv :: String
-> IO Key
getKeyEnv :: String -> IO Key
getKeyEnv String
envVar = do
Maybe String
mvalue <- String -> IO (Maybe String)
lookupEnv String
envVar
case Maybe String
mvalue of
Just String
value -> forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> b -> a
const IO Key
newKey) forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ ByteString -> Either String Key
initKey forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< String -> Either String ByteString
decode String
value
Maybe String
Nothing -> IO Key
newKey
where
decode :: String -> Either String ByteString
decode = ByteString -> Either String ByteString
B.decode forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> ByteString
C.pack
newKey :: IO Key
newKey = String -> IO Key
randomKeyEnv String
envVar
randomKey :: IO (S.ByteString, Key)
randomKey :: IO (ByteString, Key)
randomKey = do
ByteString
bs <- Int -> IO ByteString
getEntropy Int
96
case ByteString -> Either String Key
initKey ByteString
bs of
Left String
e -> forall a. HasCallStack => String -> a
error forall a b. (a -> b) -> a -> b
$ String
"Web.ClientSession.randomKey: never here, " forall a. [a] -> [a] -> [a]
++ String
e
Right Key
key -> forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString
bs, Key
key)
randomKeyEnv :: String -> IO Key
randomKeyEnv :: String -> IO Key
randomKeyEnv String
envVar = do
(ByteString
bs, Key
key) <- IO (ByteString, Key)
randomKey
let encoded :: String
encoded = ByteString -> String
C.unpack forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString
B.encode ByteString
bs
String -> String -> IO ()
setEnv String
envVar String
encoded
String -> IO ()
putStrLn forall a b. (a -> b) -> a -> b
$ String
envVar forall a. [a] -> [a] -> [a]
++ String
"=" forall a. [a] -> [a] -> [a]
++ String
encoded
forall (m :: * -> *) a. Monad m => a -> m a
return Key
key
initKey :: S.ByteString -> Either String Key
initKey :: ByteString -> Either String Key
initKey ByteString
bs | ByteString -> Int
S.length ByteString
bs forall a. Eq a => a -> a -> Bool
/= Int
96 = forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ String
"Web.ClientSession.initKey: length of " forall a. [a] -> [a] -> [a]
++
forall a. Show a => a -> String
show (ByteString -> Int
S.length ByteString
bs) forall a. [a] -> [a] -> [a]
++ String
" /= 96."
initKey ByteString
bs = do
let (ByteString
preMacKey, ByteString
preAesKey) = Int -> ByteString -> (ByteString, ByteString)
S.splitAt Int
64 ByteString
bs
AES256
aesKey <- forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first forall a. Show a => a -> String
show forall a b. (a -> b) -> a -> b
$ forall a. CryptoFailable a -> Either CryptoError a
eitherCryptoError (forall cipher key.
(Cipher cipher, ByteArray key) =>
key -> CryptoFailable cipher
cipherInit ByteString
preAesKey)
forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ Key { AES256
aesKey :: AES256
aesKey :: AES256
aesKey
, macKey :: ByteString -> Skein_512_256
macKey = forall skeinCtx digest.
(SkeinMAC skeinCtx, Hash skeinCtx digest) =>
ByteString -> ByteString -> digest
skeinMAC' ByteString
preMacKey
, keyRaw :: ByteString
keyRaw = ByteString
bs
}
encryptIO :: Key -> S.ByteString -> IO S.ByteString
encryptIO :: Key -> ByteString -> IO ByteString
encryptIO Key
key ByteString
x = do
IV
iv <- IO IV
randomIV
forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Key -> IV -> ByteString -> ByteString
encrypt Key
key IV
iv ByteString
x
encrypt :: Key
-> IV
-> S.ByteString
-> S.ByteString
encrypt :: Key -> IV -> ByteString -> ByteString
encrypt Key
key (IV ByteString
b) ByteString
x = case forall b c. (ByteArrayAccess b, BlockCipher c) => b -> Maybe (IV c)
makeIV ByteString
b of
Maybe (IV AES256)
Nothing -> forall a. HasCallStack => String -> a
error String
"Web.ClientSession.encrypt: Failed to makeIV"
Just IV AES256
iv -> ByteString -> ByteString
B.encode ByteString
final
where
encrypted :: ByteString
encrypted = forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> IV cipher -> ba -> ba
ctrCombine (Key -> AES256
aesKey Key
key) IV AES256
iv ByteString
x
toBeAuthed :: ByteString
toBeAuthed = ByteString
b ByteString -> ByteString -> ByteString
`S.append` ByteString
encrypted
auth :: Skein_512_256
auth = Key -> ByteString -> Skein_512_256
macKey Key
key ByteString
toBeAuthed
final :: ByteString
final = forall a. Serialize a => a -> ByteString
encode Skein_512_256
auth ByteString -> ByteString -> ByteString
`S.append` ByteString
toBeAuthed
decrypt :: Key
-> S.ByteString
-> Maybe S.ByteString
decrypt :: Key -> ByteString -> Maybe ByteString
decrypt Key
key ByteString
dataBS64 = do
ByteString
dataBS <- forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> b -> a
const forall a. Maybe a
Nothing) forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ ByteString -> Either String ByteString
B.decode ByteString
dataBS64
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (ByteString -> Int
S.length ByteString
dataBS forall a. Ord a => a -> a -> Bool
>= Int
48)
let (ByteString
auth, ByteString
toBeAuthed) = Int -> ByteString -> (ByteString, ByteString)
S.splitAt Int
32 ByteString
dataBS
auth' :: Skein_512_256
auth' = Key -> ByteString -> Skein_512_256
macKey Key
key ByteString
toBeAuthed
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (forall a. Serialize a => a -> ByteString
encode Skein_512_256
auth' ByteString -> ByteString -> Bool
`constTimeEq` ByteString
auth)
let (ByteString
iv, ByteString
encrypted) = Int -> ByteString -> (ByteString, ByteString)
S.splitAt Int
16 ByteString
toBeAuthed
IV AES256
iv' <- forall b c. (ByteArrayAccess b, BlockCipher c) => b -> Maybe (IV c)
makeIV ByteString
iv
forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> IV cipher -> ba -> ba
ctrCombine (Key -> AES256
aesKey Key
key) IV AES256
iv' ByteString
encrypted
data ChaChaState =
CCSt {-# UNPACK #-} !ChaChaDRG
{-# UNPACK #-} !Int
chaChaSeed :: IO ChaChaState
chaChaSeed :: IO ChaChaState
chaChaSeed = do
ChaChaDRG
drg <- forall (randomly :: * -> *).
MonadRandom randomly =>
randomly ChaChaDRG
drgNew
forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! ChaChaDRG -> Int -> ChaChaState
CCSt ChaChaDRG
drg Int
0
chaChaReseed :: IO ()
chaChaReseed :: IO ()
chaChaReseed = do
ChaChaDRG
drg' <- forall (randomly :: * -> *).
MonadRandom randomly =>
randomly ChaChaDRG
drgNew
forall a. IORef a -> a -> IO ()
I.writeIORef IORef ChaChaState
chaChaRef forall a b. (a -> b) -> a -> b
$ ChaChaDRG -> Int -> ChaChaState
CCSt ChaChaDRG
drg' Int
0
chaChaRef :: I.IORef ChaChaState
chaChaRef :: IORef ChaChaState
chaChaRef = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ IO ChaChaState
chaChaSeed forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. a -> IO (IORef a)
I.newIORef
{-# NOINLINE chaChaRef #-}
chaChaRNG :: IO IV
chaChaRNG :: IO IV
chaChaRNG = do
(ByteString
bs, Int
count) <-
forall a b. IORef a -> (a -> (a, b)) -> IO b
I.atomicModifyIORef IORef ChaChaState
chaChaRef forall a b. (a -> b) -> a -> b
$ \(CCSt ChaChaDRG
drg Int
count) ->
let (ByteString
bs', ChaChaDRG
drg') = forall gen byteArray.
(DRG gen, ByteArray byteArray) =>
Int -> gen -> (byteArray, gen)
randomBytesGenerate Int
16 ChaChaDRG
drg
in (ChaChaDRG -> Int -> ChaChaState
CCSt ChaChaDRG
drg' (forall a. Enum a => a -> a
succ Int
count), (ByteString
bs', Int
count))
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
count forall a. Eq a => a -> a -> Bool
== Int
threshold) forall a b. (a -> b) -> a -> b
$ forall {m :: * -> *} {a}. Monad m => m a -> m ()
void forall a b. (a -> b) -> a -> b
$ IO () -> IO ThreadId
forkIO IO ()
chaChaReseed
forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! ByteString -> IV
unsafeMkIV ByteString
bs
where
void :: m a -> m ()
void m a
f = m a
f forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> forall (m :: * -> *) a. Monad m => a -> m a
return ()
threshold :: Int
threshold :: Int
threshold = Int
100000