@@ -8,69 +8,246 @@
9 Currently supporting:
9 Currently supporting:
11− - Windows via CryptoAPI
11+ - Windows via CryptoAPO
12 - *nix systems via @\/dev\/urandom@
12 - *nix systems via @\/dev\/urandom@
13− - Includes QNX
13+ - QNX
14− - ghcjs/browser via JavaScript crypto API.
14+ - Xen only when RDRAND is available.
17module System.Entropy
17module System.Entropy
18− ( getEntropy,
18+ ( getEntropy
20− CryptHandle,
19+ , CryptHandle
21− openHandle,
20+ , openHandle
22− hGetEntropy,
21+ , hGetEntropy
23− closeHandle
22+ , closeHandle
26−#ifdef ghcjs_HOST_OS
25+#ifndef XEN
27−import System.EntropyGhcjs
26+import Control.Monad (liftM, when)
28−#elif defined(isWindows)
27+import System.IO.Error (mkIOError, eofErrorType, ioeSetErrorString)
29−import System.EntropyWindows
28+import Foreign (allocaBytes)
31−import System.EntropyNix
30+import Control.Monad (when)
32+import Data.ByteString as B
34−import qualified Data.ByteString as B
34+#if defined(isWindows)
35−import Control.Exception (bracket)
35+{- C example for windows rng - taken from a blog, can't recall which one but thank you!
37+ #include <Wincrypt.h>
40+ // DISCLAIMER: Don't forget to check your error codes!!
41+ // I am not checking as to make the example simple...
43+ HCRYPTPROV hCryptCtx = NULL;
44+ BYTE randomArray[128];
37−-- |Get a specific number of bytes of cryptographically
46+ CryptAcquireContext(&hCryptCtx, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
38−-- secure random data using the *system-specific* sources.
47+ CryptGenRandom(hCryptCtx, 128, randomArray);
39−-- (As of 0.4. Versions <0.4 mixed system and hardware sources)
48+ CryptReleaseContext(hCryptCtx, 0);
41−-- The returned random value is considered cryptographically secure but not true entropy.
50+
43−-- On some platforms this requires a file handle which can lead to resource
44−-- exhaustion in some situations.
45−getEntropy :: Int -- ^ Number of bytes
46− -> IO B.ByteString
51+import Data.ByteString.Internal as BI
47−getEntropy = bracket openHandle closeHandle . flip hGetEntropy
52+import Data.Int (Int32)
48−
53+import Data.Word (Word32, Word8)
49−-- |Get a specific number of bytes of cryptographically
54+import Foreign.C.String (CString, withCString)
50−-- secure random data using a supported *hardware* random bit generator.
55+import Foreign.C.Types
51−--
56+import Foreign.Ptr (Ptr, nullPtr, castPtr)
52−-- If there is no hardware random number generator then @Nothing@ is returned.
57+import Foreign.Marshal.Alloc (alloca)
53−-- If any call returns non-Nothing then it should never be @Nothing@ unless
58+import Foreign.Marshal.Utils (toBool)
54−-- there has been a hardware failure.
59+import Foreign.Storable (peek)
56−-- If trust of the CPU allows it and no context switching is important,
61+#ifdef HAVE_RDRAND
57−-- a bias to the hardware rng with system rng as fall back is trivial:
62+foreign import ccall unsafe "cpu_has_rdrand"
58−--
63+ c_cpu_has_rdrand :: IO CInt
60−-- let fastRandom nr = maybe (getEntropy nr) pure =<< getHardwareEntropy nr
65+foreign import ccall unsafe "get_rand_bytes"
61−-- @
66+ c_get_rand_bytes :: Ptr CUChar -> CSize -> IO CInt
63−-- The old, @<0.4@, behavior is possible using @xor@ from 'Data.Bits':
68+cpuHasRdRand :: IO Bool
69+cpuHasRdRand = (/= 0) `fmap` c_cpu_has_rdrand
78+-- Define the constants we need from WinCrypt.h
80+msDefProv = "Microsoft Base Cryptographic Provider v1.0"
82+provRSAFull = fromIntegral 1
83+cryptVerifyContext :: Word32
84+cryptVerifyContext = fromIntegral 0xF0000000
86+-- Declare the required CryptoAPI imports
87+foreign import stdcall unsafe "CryptAcquireContextA"
88+ c_cryptAcquireCtx :: Ptr Word32 -> CString -> CString -> Word32 -> Word32 -> IO Int32
89+foreign import stdcall unsafe "CryptGenRandom"
90+ c_cryptGenRandom :: Word32 -> Word32 -> Ptr Word8 -> IO Int32
91+foreign import stdcall unsafe "CryptReleaseContext"
92+ c_cryptReleaseCtx :: Word32 -> Word32 -> IO Int32
94+cryptAcquireCtx :: IO Word32
96+ alloca $ \handlePtr ->
97+ withCString msDefProv $ \provName -> do
98+ stat <- c_cryptAcquireCtx handlePtr nullPtr provName (fromIntegral 1) (fromIntegral cryptVerifyContext)
101+ else fail "c_cryptAcquireCtx"
103+cryptGenRandom :: Word32 -> Int -> IO B.ByteString
105+ BI.create i $ \c_buffer -> do
106+ stat <- c_cryptGenRandom (fromIntegral h) (fromIntegral i) c_buffer
109+ else fail "c_cryptGenRandom"
111+cryptReleaseCtx :: Word32 -> IO ()
112+cryptReleaseCtx h = do
113+ stat <- c_cryptReleaseCtx h 0
116+ else fail "c_cryptReleaseCtx"
118+-- |Inefficiently get a specific number of bytes of cryptographically
119+-- secure random data using the system-specific facilities.
65−-- @
121+-- This function will return zero bytes
66−-- let oldRandom nr =
122+-- on platforms without a secure RNG!
67−-- do hwRnd <- maybe (replicate nr 0) BS.unpack <$> getHardwareEntropy nr
123+getEntropy :: Int -> IO B.ByteString
68−-- sysRnd <- BS.unpack <$> getEntropy nr
124+getEntropy n = do
69−-- pure $ BS.pack $ zipWith xor sysRnd hwRnd
125+#ifdef HAVE_RDRAND
70−-- @
126+ b <- cpuHasRdRand
127+ if b then hGetEntropy UseRdRand n
130+ h <- cryptAcquireCtx
131+ bs <- cryptGenRandom h n
136+-- |Open a handle from which random data can be read
137+openHandle :: IO CryptHandle
141+ if b then return UseRdRand
144+ liftM CH cryptAcquireCtx
146+-- |Close the `CryptHandle`
147+closeHandle (CH h) = cryptReleaseCtx h
149+-- |Read from `CryptHandle`
150+hGetEntropy :: CryptHandle -> Int -> IO B.ByteString
151+hGetEntropy (CH h) = cryptGenRandom h
153+hGetEntropy UseRdRand =
154+ B.create n $ \ptr -> do
155+ r <- c_get_rand_bytes (castPtr ptr) (fromIntegral n)
157+ (fail "RDRand failed to gather entropy")
161+{- Not windows, assuming nix with a /dev/urandom -}
163+import Foreign.C.Types
164+import Data.ByteString.Internal as B
166+data CryptHandle = UseRdRand -- or die trying
168+import System.Posix (openFd, closeFd, fdReadBuf, OpenMode(..), defaultFileFlags, Fd)
171+source = "/dev/urandom"
173+-- |Handle for manual resource mangement
181+-- |Open a `CryptHandle`
182+openHandle :: IO CryptHandle
186+ if b then return UseRdRand
190+ error "entropy: On halvm there is no entropy other than RDRAND."
192+ liftM CH (openFd source ReadOnly Nothing defaultFileFlags)
195+-- |Close the `CryptHandle`
196+closeHandle :: CryptHandle -> IO ()
198+closeHandle (CH h) = closeFd h
201+closeHandle UseRdRand = return ()
205+fdReadBS :: Fd -> Int -> IO B.ByteString
207+ allocaBytes n $ \buf -> do
208+ rc <- fdReadBuf fd buf (fromIntegral n)
210+ 0 -> ioError (ioeSetErrorString (mkIOError eofErrorType "fdRead" Nothing Nothing) "EOF")
211+ n' -> B.packCStringLen (castPtr buf, fromIntegral n')
214+-- |Read random data from a `CryptHandle`
215+hGetEntropy :: CryptHandle -> Int -> IO B.ByteString
217+hGetEntropy (CH h) = fdReadBS h
220+hGetEntropy UseRdRand = \n -> do
221+ B.create n $ \ptr -> do
222+ r <- c_get_rand_bytes (castPtr ptr) (fromIntegral n)
224+ (fail "RDRand failed to gather entropy")
230+foreign import ccall unsafe "cpu_has_rdrand"
231+ c_cpu_has_rdrand :: IO CInt
233+foreign import ccall unsafe "get_rand_bytes"
234+ c_get_rand_bytes :: Ptr CUChar -> CSize -> IO CInt
236+cpuHasRdRand :: IO Bool
237+cpuHasRdRand = (/= 0) `fmap` c_cpu_has_rdrand
240+-- |Inefficiently get a specific number of bytes of cryptographically
241+-- secure random data using the system-specific facilities.
72−-- A less maliable mixing can be accomplished by replacing `xor` with a
243+-- Use '/dev/urandom' on *nix and CryptAPI when on Windows. In short,
73−-- composition of concat and cryptographic hash.
244+-- this entropy is considered cryptographically secure but not true
74−getHardwareEntropy :: Int -- ^ Number of bytes
245+-- entropy.
75− -> IO (Maybe B.ByteString)
246+getEntropy :: Int -> IO B.ByteString
76−getHardwareEntropy = hardwareRandom
247+getEntropy n = do
249+ e <- hGetEntropy h n