@@ -4,73 +4,222 @@
4 Stability: beta
4 Stability: beta
5 Portability: portable
5 Portability: portable
7− Obtain entropy from system sources or x86 RDRAND when available.
7+ Obtain entropy from system sources.
8+ Currently, windows and *nix systems with a @\/dev\/urandom@ are supported.
9− Currently supporting:
19+import Control.Monad (liftM)
20+import Data.ByteString as B
21+import System.IO.Error (mkIOError, eofErrorType, ioeSetErrorString)
22+import Foreign (allocaBytes)
24+#if defined(isWindows)
25+{- C example for windows rng - taken from a blog, can't recall which one but thank you!
11− - Windows via CryptoAPI
26+ #include <Windows.h>
12− - *nix systems via @\/dev\/urandom@
27+ #include <Wincrypt.h>
13− - Includes QNX
28+ ...
14− - ghcjs/browser via JavaScript crypto API.
29+ //
30+ // DISCLAIMER: Don't forget to check your error codes!!
31+ // I am not checking as to make the example simple...
33+ HCRYPTPROV hCryptCtx = NULL;
34+ BYTE randomArray[128];
36+ CryptAcquireContext(&hCryptCtx, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
37+ CryptGenRandom(hCryptCtx, 128, randomArray);
38+ CryptReleaseContext(hCryptCtx, 0);
17−module System.Entropy
41+import Data.ByteString.Internal as BI
18− ( getEntropy,
42+import Data.Int (Int32)
19− getHardwareEntropy,
43+import Data.Word (Word32, Word8)
20− CryptHandle,
44+import Foreign.C.String (CString, withCString)
21− openHandle,
45+import Foreign.C.Types
22− hGetEntropy,
46+import Foreign.Ptr (Ptr, nullPtr, castPtr)
23− closeHandle
47+import Foreign.Marshal.Alloc (alloca)
24− ) where
48+import Foreign.Marshal.Utils (toBool)
25−
49+import Foreign.Storable (peek)
26−#ifdef ghcjs_HOST_OS
50+
27−import System.EntropyGhcjs
51+#ifdef HAVE_RDRAND
28−#elif defined(isWindows)
52+foreign import ccall unsafe "cpu_has_rdrand"
29−import System.EntropyWindows
53+ c_cpu_has_rdrand :: IO CInt
31−import System.EntropyNix
55+foreign import ccall unsafe "get_rand_bytes"
56+ c_get_rand_bytes :: Ptr CUChar -> CSize -> IO CInt
58+cpuHasRdRand :: IO Bool
59+cpuHasRdRand = (/= 0) `fmap` c_cpu_has_rdrand
34−import qualified Data.ByteString as B
62+data CryptHandle
35−import Control.Exception (bracket)
63+ = CH Word32
37−-- |Get a specific number of bytes of cryptographically
68+-- Define the constants we need from WinCrypt.h
38−-- secure random data using the *system-specific* sources.
69+msDefProv :: String
39−-- (As of 0.4. Versions <0.4 mixed system and hardware sources)
70+msDefProv = "Microsoft Base Cryptographic Provider v1.0"
40−--
71+provRSAFull :: Word32
41−-- The returned random value is considered cryptographically secure but not true entropy.
72+provRSAFull = fromIntegral 1
42−--
73+cryptVerifyContext :: Word32
43−-- On some platforms this requires a file handle which can lead to resource
74+cryptVerifyContext = fromIntegral 0xF0000000
44−-- exhaustion in some situations.
75+
45−getEntropy :: Int -- ^ Number of bytes
76+-- Declare the required CryptoAPI imports
77+foreign import stdcall unsafe "CryptAcquireContextA"
78+ c_cryptAcquireCtx :: Ptr Word32 -> CString -> CString -> Word32 -> Word32 -> IO Int32
79+foreign import stdcall unsafe "CryptGenRandom"
80+ c_cryptGenRandom :: Word32 -> Word32 -> Ptr Word8 -> IO Int32
81+foreign import stdcall unsafe "CryptReleaseContext"
82+ c_cryptReleaseCtx :: Word32 -> Word32 -> IO Int32
84+cryptAcquireCtx :: IO Word32
86+ alloca $ \handlePtr ->
87+ withCString msDefProv $ \provName -> do
88+ stat <- c_cryptAcquireCtx handlePtr nullPtr provName (fromIntegral 1) (fromIntegral cryptVerifyContext)
91+ else fail "c_cryptAcquireCtx"
46− -> IO B.ByteString
93+cryptGenRandom :: Word32 -> Int -> IO B.ByteString
47−getEntropy = bracket openHandle closeHandle . flip hGetEntropy
94+cryptGenRandom h i =
48−
95+ BI.create i $ \c_buffer -> do
49−-- |Get a specific number of bytes of cryptographically
96+ stat <- c_cryptGenRandom (fromIntegral h) (fromIntegral i) c_buffer
50−-- secure random data using a supported *hardware* random bit generator.
97+ if (toBool stat)
52−-- If there is no hardware random number generator then @Nothing@ is returned.
99+ else fail "c_cryptGenRandom"
53−-- If any call returns non-Nothing then it should never be @Nothing@ unless
100+
54−-- there has been a hardware failure.
101+cryptReleaseCtx :: Word32 -> IO ()
55−--
102+cryptReleaseCtx h = do
56−-- If trust of the CPU allows it and no context switching is important,
103+ stat <- c_cryptReleaseCtx h 0
57−-- a bias to the hardware rng with system rng as fall back is trivial:
104+ if (toBool stat)
59−-- @
106+ else fail "c_cryptReleaseCtx"
60−-- let fastRandom nr = maybe (getEntropy nr) pure =<< getHardwareEntropy nr
107+
61−-- @
108+-- |Inefficiently get a specific number of bytes of cryptographically
62−--
109+-- secure random data using the system-specific facilities.
63−-- The old, @<0.4@, behavior is possible using @xor@ from 'Data.Bits':
65−-- @
111+-- This function will return zero bytes
66−-- let oldRandom nr =
112+-- on platforms without a secure RNG!
67−-- do hwRnd <- maybe (replicate nr 0) BS.unpack <$> getHardwareEntropy nr
113+getEntropy :: Int -> IO B.ByteString
68−-- sysRnd <- BS.unpack <$> getEntropy nr
114+getEntropy n = do
69−-- pure $ BS.pack $ zipWith xor sysRnd hwRnd
115+#ifdef HAVE_RDRAND
70−-- @
116+ b <- cpuHasRdRand
117+ if b then hGetEntropy UseRdRand n
120+ h <- cryptAcquireCtx
121+ bs <- cryptGenRandom h n
126+-- |Open a handle from which random data can be read
127+openHandle :: IO CryptHandle
131+ if b then return UseRdRand
134+ liftM CH cryptAcquireCtx
136+-- |Close the `CryptHandle`
137+closeHandle (CH h) = cryptReleaseCtx h
139+-- |Read from `CryptHandle`
140+hGetEntropy :: CryptHandle -> Int -> IO B.ByteString
141+hGetEntropy (CH h) = cryptGenRandom h
143+hGetEntropy UseRdRand =
144+ B.create n $ \ptr -> do
145+ r <- c_get_rand_bytes (castPtr ptr) (fromIntegral n)
147+ (fail "RDRand failed to gather entropy")
151+{- Not windows, assuming nix with a /dev/urandom -}
152+import System.Posix (openFd, closeFd, fdReadBuf, OpenMode(..), defaultFileFlags, Fd)
156+source = "/dev/urandom"
158+-- |Handle for manual resource mangement
165+-- |Open a `CryptHandle`
166+openHandle :: IO CryptHandle
170+ if b then return UseRdRand
173+ liftM CH (openFd source ReadOnly Nothing defaultFileFlags)
175+-- |Close the `CryptHandle`
176+closeHandle :: CryptHandle -> IO ()
177+closeHandle (CH h) = closeFd h
179+closeHandle UseRdRand = return ()
182+fdReadBS :: Fd -> Int -> IO B.ByteString
184+ allocaBytes n $ \buf -> do
185+ rc <- fdReadBuf fd buf (fromIntegral n)
187+ 0 -> ioError (ioeSetErrorString (mkIOError eofErrorType "fdRead" Nothing Nothing) "EOF")
188+ n' -> B.packCStringLen (castPtr buf, fromIntegral n')
190+-- |Read random data from a `CryptHandle`
191+hGetEntropy :: CryptHandle -> Int -> IO B.ByteString
192+hGetEntropy (CH h) = fdReadBS h
194+hGetEntropy UseRdRand = \n -> do
195+ B.create n $ \ptr -> do
196+ r <- c_get_rand_bytes (castPtr ptr) (fromIntegral n)
198+ (fail "RDRand failed to gather entropy")
202+foreign import ccall unsafe "cpu_has_rdrand"
203+ c_cpu_has_rdrand :: IO CInt
205+foreign import ccall unsafe "get_rand_bytes"
206+ c_get_rand_bytes :: Ptr CUChar -> CSize -> IO CInt
208+cpuHasRdRand :: IO Bool
209+cpuHasRdRand = (/= 0) `fmap` c_cpu_has_rdrand
212+-- |Inefficiently get a specific number of bytes of cryptographically
213+-- secure random data using the system-specific facilities.
72−-- A less maliable mixing can be accomplished by replacing `xor` with a
215+-- Use '/dev/urandom' on *nix and CryptAPI when on Windows. In short,
73−-- composition of concat and cryptographic hash.
216+-- this entropy is considered "cryptographically secure" but not true
74−getHardwareEntropy :: Int -- ^ Number of bytes
217+-- entropy.
75− -> IO (Maybe B.ByteString)
218+getEntropy :: Int -> IO B.ByteString
76−getHardwareEntropy = hardwareRandom
219+getEntropy n = do
221+ e <- hGetEntropy h n