packages feed

crypto-token 0.2.1 → 0.2.2

raw patch · 4 files changed

+173/−42 lines, 4 files

Files

ChangeLog.md view
@@ -1,5 +1,10 @@ # ChangeLog for crypto-token +## 0.2.2++* Rotate secrets by an RTS timer, with no thread of its own+  [#2](https://github.com/kazu-yamamoto/crypto-token/pull/2)+ ## 0.2.1  * `tokenLifetime` is exact.  A token carries its issue time and is refused
Crypto/Token.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-}@@ -23,7 +24,7 @@  import Control.Concurrent import qualified Control.Exception as E-import Control.Monad (when)+import Control.Monad (join, unless, when) import Crypto.Cipher.AES (AES256) import Crypto.Cipher.Types (AEADMode (..), AuthTag (..)) import qualified Crypto.Cipher.Types as C@@ -33,10 +34,15 @@ 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)  ---------------------------------------------------------------- @@ -51,6 +57,7 @@     -- ^ 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.     , threadName :: String+    -- ^ The label of the thread used without the timer manager.     }     deriving (Eq, Show) @@ -73,11 +80,15 @@     { headerKey :: AES256     , getEncryptSecret :: IO (Secret, Index)     , getDecryptSecret :: Index -> IO Secret-    , threadId :: ThreadId     , lifetimeNSec :: Word64+    , stopRotation :: IO ()     } --- | Spawning a token manager.+-- | 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{..} = do@@ -92,44 +103,108 @@     arr <- newArray (0, slots - 1) emp     ent <- generateSecret     writeArray arr 0 ent-    ref <- I.newIORef 0-    tid <- forkIO $ loop arr ref-    labelThread tid threadName+    epoch <- currentEpoch+    var <- newMVar (0, epoch)+    weak <- mkWeakMVar var (return ())+    stop <- startRotation threadName (untilNext interval) $ do+        mvar <- deRefWeak weak+        case mvar of+            Nothing -> return False+            Just v -> True <$ rotate arr v     hkey <- newHeaderKey     return $-        TokenManager hkey (readCurrentSecret arr ref) (readSecret arr) tid $-            fromIntegral lifetime * 1000000000+        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 $ \st -> do+                    n <- rangeSize <$> getBounds arr+                    mapM_ (\i -> generateSecret >>= writeArray arr i) [0 .. n - 1]+                    return st+            }   where-    loop arr ref = do-        delaySeconds interval-        -- a failed rotation is retried at the next interval-        update arr ref `E.catch` ignoreSync-        loop arr ref-    ignoreSync :: E.SomeException -> IO ()-    ignoreSync e = case E.fromException e of-        Just (E.SomeAsyncException _) -> E.throwIO e-        Nothing -> return ()-    update :: IOArray Int Secret -> I.IORef Int -> IO ()-    update arr ref = do-        idx0 <- I.readIORef ref+    currentEpoch = (`div` intervalNSec) <$> getMonotonicTimeNSec+    intervalNSec = fromIntegral interval * 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 arr var = modifyMVar var $ \(idx, epoch0) -> do+        epoch <- max epoch0 <$> currentEpoch         n <- rangeSize <$> getBounds arr-        let idx = (idx0 + 1) `mod` n-        sec <- generateSecret-        writeArray arr idx sec-        I.writeIORef ref idx+        let steps = epoch - epoch0+            idx' = (idx + fromIntegral (steps `mod` fromIntegral n)) `mod` n+            k = fromIntegral (min steps (fromIntegral n)) :: Int+        mapM_+            (\j -> generateSecret >>= writeArray arr ((idx' - j) `mod` n))+            [0 .. k - 1]+        sec <- readArray arr idx'+        return ((idx', epoch), (sec, fromIntegral idx')) --- threadDelay's microseconds overflow a 32-bit Int after 35 minutes.-delaySeconds :: Int -> IO ()-delaySeconds n-    | n <= 0 = return ()-    | otherwise = do-        let m = min n 1000-        threadDelay (m * 1000000)-        delaySeconds (n - m)+-- | 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 interval = do+    now <- getMonotonicTimeNSec+    let i = fromIntegral interval * 1000000000 :: Word64+        ns = i - now `mod` i+    return $ fromIntegral (min ns 1000000000000 `div` 1000) + 1 --- | Killing a token manager.+-- | 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 name next tick+    | rtsSupportsBoundThreads = do+        mgr <- getSystemTimerManager+        -- Nothing once stopped+        ref <- I.newIORef $ Just Nothing+        let schedule = do+                us <- next+                key <- registerTimeout mgr us fire+                live <- I.atomicModifyIORef' ref $ \m ->+                    maybe (Nothing, False) (const (Just (Just key), True)) m+                unless live $ unregisterTimeout mgr key+            fire = do+                live <- isJust <$> I.readIORef ref+                when live $ do+                    continue <- tick `E.catch` ignoreSync+                    when continue schedule+        schedule+        return $ do+            m <- I.atomicModifyIORef' ref $ \m -> (Nothing, m)+            mapM_ (unregisterTimeout mgr) (join m)+    | otherwise = startRotationThread name next tick+#endif++startRotationThread :: String -> IO Int -> IO Bool -> IO (IO ())+startRotationThread name next tick = do+    stopped <- I.newIORef False+    let loop = do+            next >>= threadDelay+            s <- I.readIORef 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 e = case E.fromException e of+    Just (E.SomeAsyncException _) -> E.throwIO e+    Nothing -> return True++-- | Killing a token manager: its rotation stops and the secrets made so+--   far are forgotten. killTokenManager :: TokenManager -> IO ()-killTokenManager TokenManager{..} = killThread threadId+killTokenManager = stopRotation  ---------------------------------------------------------------- @@ -137,12 +212,6 @@ readSecret secrets idx0 = do     n <- rangeSize <$> getBounds secrets     readArray secrets $ fromIntegral idx0 `mod` n--readCurrentSecret :: IOArray Int Secret -> I.IORef Int -> IO (Secret, Index)-readCurrentSecret arr ref = do-    idx <- I.readIORef ref-    sec <- readArray arr idx-    return (sec, fromIntegral idx)  ---------------------------------------------------------------- 
crypto-token.cabal view
@@ -1,6 +1,6 @@ cabal-version: >=1.10 name:          crypto-token-version:       0.2.1+version:       0.2.2 license:       BSD3 license-file:  LICENSE maintainer:    Kazu Yamamoto <kazu@iij.ad.jp>@@ -23,7 +23,7 @@         base >=4.11 && <5,         array >=0.5 && <0.6,         bytestring >=0.10 && <0.13,-        crypton >=1.1.0 && <2.3,+        crypton >=1.1.0 && <2.4,         network-byte-order >=0.1.6 && <0.2,         ram >=0.19 && <0.23 
test/TokenSpec.hs view
@@ -6,8 +6,12 @@ import Control.Concurrent import qualified Control.Exception as E import Crypto.Token+import Control.Monad import Data.Bits (xor) import qualified Data.ByteString as BS+import Data.IORef+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec) import Test.Hspec  ----------------------------------------------------------------@@ -30,6 +34,46 @@             decryptToken mgr tb `shouldReturn` Just "Bar"             killTokenManager mgr +        it "rotates after intervals with no tokens, more than the slots" $ do+            mgr <- spawnTokenManager $ defaultConfig{interval = 1, tokenLifetime = 1}+            t1 <- encryptToken mgr "Foo"+            threadDelay 3500000+            t2 <- encryptToken mgr "Bar"+            decryptToken mgr t1 `shouldReturn` Nothing+            decryptToken mgr t2 `shouldReturn` Just "Bar"++        it "rotates once per interval while many threads make tokens" $ do+            -- two slots: a second rotation would replace the secret of+            -- the tokens made before the boundary+            mgr <- spawnTokenManager $ defaultConfig{interval = 2, tokenLifetime = 2}+            -- from 0.6 s before a boundary to 0.6 s after it+            now <- getMonotonicTimeNSec+            let boundary = (now `div` 2000000000 + 1) * 2000000000+                start = boundary - 600000000+            when (now < start) $ sleepUntil start+            dones <- replicateM 8 $ do+                done <- newEmptyMVar+                ref <- newIORef []+                _ <- forkIO $ do+                    makeTokens mgr (boundary + 600000000) ref (0 :: Int)+                    putMVar done ()+                return (done, ref)+            mapM_ (takeMVar . fst) dones+            ts <- concat <$> mapM (readIORef . snd) dones+            any ((< boundary) . fst) ts `shouldBe` True+            any ((> boundary) . fst) ts `shouldBe` True+            forM_ (reverse ts) $ \(_, t) ->+                decryptToken mgr t `shouldReturn` Just "Foo"+            killTokenManager mgr++        it "forgets its secrets when killed" $ do+            mgr <- spawnTokenManager defaultConfig+            t <- encryptToken mgr "Foo"+            killTokenManager mgr+            decryptToken mgr t `shouldReturn` Nothing+            t' <- encryptToken mgr "Bar"+            decryptToken mgr t' `shouldReturn` Just "Bar"+         it "refuses a tampered token" $ do             mgr <- spawnTokenManager defaultConfig             t <- encryptToken mgr "Foo"@@ -57,6 +101,19 @@         it "refuses a non-positive interval" $             spawnTokenManager defaultConfig{interval = 0}                 `shouldThrow` (\(_ :: E.IOException) -> True)++-- Making tokens as fast as possible, keeping some of them.+makeTokens :: TokenManager -> Word64 -> IORef [(Word64, BS.ByteString)] -> Int -> IO ()+makeTokens mgr deadline ref i = do+    t <- encryptToken mgr "Foo"+    now <- getMonotonicTimeNSec+    when (i `mod` 64 == 0) $ modifyIORef' ref ((now, t) :)+    when (now < deadline) $ makeTokens mgr deadline ref (i + 1)++sleepUntil :: Word64 -> IO ()+sleepUntil t = do+    now <- getMonotonicTimeNSec+    when (now < t) $ threadDelay $ fromIntegral ((t - now) `div` 1000)  roundTrip :: Config -> IO () roundTrip conf =